-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathraster_table_ocr.rs
More file actions
5333 lines (4819 loc) · 176 KB
/
Copy pathraster_table_ocr.rs
File metadata and controls
5333 lines (4819 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Recover text signal from raster table images using local OCR.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::OnceLock;
use std::time::{SystemTime, UNIX_EPOCH};
use image::{GenericImageView, GrayImage, Luma};
use serde::Deserialize;
use crate::models::bbox::BoundingBox;
use crate::models::chunks::{ImageChunk, TextChunk};
use crate::models::content::ContentElement;
use crate::models::enums::{PdfLayer, TextFormat, TextType};
use crate::models::table::{
TableBorder, TableBorderCell, TableBorderRow, TableToken, TableTokenType,
};
// Broaden image eligibility so moderately cropped tables are considered.
const MIN_IMAGE_WIDTH_RATIO: f64 = 0.40;
const MIN_IMAGE_AREA_RATIO: f64 = 0.035;
const MAX_NATIVE_TEXT_CHARS_IN_IMAGE: usize = 250;
const MAX_NATIVE_TEXT_CHUNKS_IN_IMAGE: usize = 12;
// Accuracy-first: accept degraded glyphs at lower confidence —
// dual-OEM consensus and spatial coherence filtering will eliminate noise.
const MIN_OCR_WORD_CONFIDENCE: f64 = 6.0;
// Reject artificially-high confidence noise (Tesseract artefacts above 100).
const MAX_OCR_WORD_CONFIDENCE: f64 = 101.0;
const RASTER_DARK_THRESHOLD: u8 = 180;
const RASTER_CHART_INK_THRESHOLD: u8 = 240;
const MIN_BORDERED_VERTICAL_LINES: usize = 3;
const MIN_BORDERED_HORIZONTAL_LINES: usize = 3;
// Accuracy-first: lighter lines are still valid table borders.
const MIN_LINE_DARK_RATIO: f64 = 0.28;
const MIN_CELL_SIZE_PX: u32 = 10;
const CELL_INSET_PX: u32 = 5;
const TABLE_RASTER_OCR_BORDER_PX: u32 = 14;
// Typography-grounded scale: pdftoppm renders at PDFTOPPM_DPI (150). Scaling by 2
// gives 300 DPI effective — the Tesseract-documented optimum. At 12pt body text,
// cap height ≈ 25px raw → 50px scaled, squarely in Tesseract's 32-40px sweet spot.
// Over-scaling (×5 = 125px) amplifies anti-aliasing and hurts LSTM segmentation.
const PDFTOPPM_DPI: u32 = 150;
const OCR_SCALE_FACTOR: u32 = 2;
/// Effective DPI seen by Tesseract = PDFTOPPM_DPI × OCR_SCALE_FACTOR.
const TESSERACT_EFFECTIVE_DPI: u32 = PDFTOPPM_DPI * OCR_SCALE_FACTOR;
const MIN_DOMINANT_IMAGE_WIDTH_RATIO: f64 = 0.65;
const MIN_DOMINANT_IMAGE_AREA_RATIO: f64 = 0.40;
const MAX_NATIVE_TEXT_CHARS_IN_DOMINANT_IMAGE: usize = 80;
const MIN_DOMINANT_IMAGE_OCR_WORDS: usize = 18;
const MIN_DOMINANT_IMAGE_TEXT_LINES: usize = 6;
const MIN_DENSE_PROSE_BLOCK_LINES: usize = 3;
const MIN_DENSE_PROSE_BLOCK_WIDTH_RATIO: f64 = 0.32;
// Permit minor breaks in rasterized lines while still enforcing structure.
const MIN_TRUE_GRID_LINE_CONTINUITY: f64 = 0.60;
const MAX_NATIVE_TEXT_CHARS_FOR_PAGE_RASTER_OCR: usize = 180;
const MIN_EMPTY_TABLE_COVERAGE_FOR_PAGE_RASTER_OCR: f64 = 0.08;
const MAX_EMPTY_TABLES_FOR_PAGE_RASTER_OCR: usize = 24;
const LOCAL_BINARIZATION_RADIUS: u32 = 14;
const MIN_BINARIZATION_BLOCK_PIXELS: usize = 81;
// Handle sparse numeric tables where only a few cells OCR cleanly.
const MIN_RASTER_TABLE_TEXT_CELL_RATIO: f64 = 0.05;
const MIN_RASTER_TABLE_ROWS_WITH_TEXT: usize = 1;
const MIN_NUMERIC_TABLE_MEDIAN_FILL_RATIO: f64 = 0.40;
const MIN_BORDERED_CELL_DARK_RATIO: f64 = 0.03;
const MIN_BORDERED_INKED_CELL_RATIO: f64 = 0.18;
const MIN_BORDERED_ROWS_WITH_INK: usize = 2;
const MAX_BORDERED_TABLE_PER_CELL_FALLBACK_CELLS: usize = 24;
const MIN_BRIGHT_PHOTO_MID_TONE_RATIO: f64 = 0.24;
const MIN_BRIGHT_PHOTO_HISTOGRAM_BINS: usize = 8;
const MIN_BRIGHT_PHOTO_ENTROPY: f64 = 1.6;
#[derive(Debug, Clone)]
struct OcrWord {
line_key: (u32, u32, u32),
left: u32,
top: u32,
width: u32,
height: u32,
text: String,
confidence: f64,
}
#[derive(Debug, Clone)]
struct XCluster {
center: f64,
count: usize,
lines: HashSet<(u32, u32, u32)>,
}
#[derive(Clone)]
struct OcrRowBuild {
top_y: f64,
bottom_y: f64,
cell_texts: Vec<String>,
}
#[derive(Debug, Clone)]
struct EmptyCellRaster {
row_idx: usize,
cell_idx: usize,
x1: u32,
y1: u32,
x2: u32,
y2: u32,
}
#[derive(Debug, Clone)]
struct RasterTableGrid {
vertical_lines: Vec<u32>,
horizontal_lines: Vec<u32>,
}
#[derive(Debug, Clone)]
struct OcrCandidateScore {
words: Vec<OcrWord>,
score: f64,
}
#[derive(Debug, Clone)]
struct PdfImagesListEntry {
image_type: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OcrEngine {
Tesseract,
RapidOcr,
}
#[derive(Debug, Deserialize)]
struct RapidOcrLine {
left: u32,
top: u32,
width: u32,
height: u32,
text: String,
confidence: f64,
}
static OCR_ENGINE: OnceLock<OcrEngine> = OnceLock::new();
static RAPIDOCR_PYTHON: OnceLock<Option<String>> = OnceLock::new();
const RAPIDOCR_RUNNER: &str = r#"
import json, sys
from rapidocr import RapidOCR
engine = RapidOCR()
result = engine(sys.argv[1], use_det=True, use_cls=True, use_rec=True)
if result is None:
print('[]')
raise SystemExit(0)
boxes = getattr(result, 'boxes', []) or []
txts = getattr(result, 'txts', []) or []
scores = getattr(result, 'scores', []) or []
out = []
for box, text, score in zip(boxes, txts, scores):
if not text or not str(text).strip():
continue
xs = [pt[0] for pt in box]
ys = [pt[1] for pt in box]
out.append({
'left': int(min(xs)),
'top': int(min(ys)),
'width': max(1, int(max(xs) - min(xs))),
'height': max(1, int(max(ys) - min(ys))),
'text': str(text),
'confidence': float(score),
})
print(json.dumps(out, ensure_ascii=False))
"#;
fn selected_ocr_engine() -> OcrEngine {
*OCR_ENGINE.get_or_init(|| match env::var("EDGEPARSE_OCR_ENGINE") {
Ok(value) => match value.to_ascii_lowercase().as_str() {
"rapidocr" if rapidocr_python_command().is_some() => OcrEngine::RapidOcr,
"rapidocr" => OcrEngine::Tesseract,
_ => OcrEngine::Tesseract,
},
Err(_) => OcrEngine::Tesseract,
})
}
fn rapidocr_python_command() -> Option<&'static str> {
RAPIDOCR_PYTHON
.get_or_init(|| {
let preferred = env::var("EDGEPARSE_OCR_PYTHON").ok();
let mut candidates = Vec::new();
if let Some(cmd) = preferred {
candidates.push(cmd);
}
candidates.push("python3".to_string());
candidates.push("python".to_string());
for candidate in candidates {
let ok = Command::new(&candidate)
.arg("-c")
.arg("import rapidocr")
.output()
.ok()
.is_some_and(|out| out.status.success());
if ok {
return Some(candidate);
}
}
None
})
.as_deref()
}
fn rapidocr_lines_to_words(lines: Vec<RapidOcrLine>) -> Vec<OcrWord> {
let mut words = Vec::new();
for (line_idx, line) in lines.into_iter().enumerate() {
let tokens: Vec<&str> = line.text.split_whitespace().collect();
if tokens.is_empty() {
continue;
}
let total_chars: u32 = tokens
.iter()
.map(|token| token.chars().count() as u32)
.sum();
if total_chars == 0 {
continue;
}
let mut cursor = line.left;
let mut remaining_width = line.width.max(tokens.len() as u32);
let mut remaining_chars = total_chars;
for (token_idx, token) in tokens.iter().enumerate() {
let token_chars = token.chars().count() as u32;
let width = if token_idx == tokens.len() - 1 || remaining_chars <= token_chars {
remaining_width.max(1)
} else {
let proportional = ((remaining_width as f64) * (token_chars as f64)
/ (remaining_chars as f64))
.round() as u32;
proportional.max(1).min(remaining_width)
};
words.push(OcrWord {
line_key: (0, line_idx as u32, 0),
left: cursor,
top: line.top,
width,
height: line.height.max(1),
text: (*token).to_string(),
confidence: line.confidence,
});
cursor = cursor.saturating_add(width);
remaining_width = remaining_width.saturating_sub(width);
remaining_chars = remaining_chars.saturating_sub(token_chars);
}
}
words
}
fn run_rapidocr_words(image: &GrayImage) -> Option<Vec<OcrWord>> {
let python = rapidocr_python_command()?;
let temp_dir = create_temp_dir(0).ok()?;
let image_path = temp_dir.join("ocr.png");
if image.save(&image_path).is_err() {
let _ = fs::remove_dir_all(&temp_dir);
return None;
}
let output = Command::new(python)
.current_dir(&temp_dir)
.arg("-c")
.arg(RAPIDOCR_RUNNER)
.arg("ocr.png")
.output()
.ok()?;
let _ = fs::remove_dir_all(&temp_dir);
if !output.status.success() {
return None;
}
let json = String::from_utf8_lossy(&output.stdout);
let lines: Vec<RapidOcrLine> = serde_json::from_str(&json).ok()?;
let words = rapidocr_lines_to_words(lines);
(!words.is_empty()).then_some(words)
}
/// Recover OCR text chunks for image-backed table regions on a single page.
pub fn recover_raster_table_text_chunks(
input_path: &Path,
page_bbox: &BoundingBox,
page_number: u32,
text_chunks: &[TextChunk],
image_chunks: &[ImageChunk],
) -> Vec<TextChunk> {
if page_bbox.area() <= 0.0 || image_chunks.is_empty() {
return Vec::new();
}
let candidates: Vec<&ImageChunk> = image_chunks
.iter()
.filter(|image| is_ocr_candidate(image, page_bbox, text_chunks))
.collect();
if candidates.is_empty() {
return Vec::new();
}
let temp_dir = match create_temp_dir(page_number) {
Ok(dir) => dir,
Err(_) => return Vec::new(),
};
let result =
recover_from_page_images(input_path, &temp_dir, page_number, candidates, text_chunks);
let _ = fs::remove_dir_all(&temp_dir);
result
}
/// Recover OCR text lines from dominant non-table page images.
///
/// This is for infographic-like pages where the PDF contains a large raster
/// image but little or no native text. The extracted OCR signal is injected
/// back into the normal text pipeline as line chunks so downstream grouping can
/// rebuild headings, paragraphs, and lists.
pub fn recover_dominant_image_text_chunks(
input_path: &Path,
page_bbox: &BoundingBox,
page_number: u32,
text_chunks: &[TextChunk],
image_chunks: &[ImageChunk],
) -> Vec<TextChunk> {
if page_bbox.area() <= 0.0 || image_chunks.is_empty() {
return Vec::new();
}
let candidates: Vec<&ImageChunk> = image_chunks
.iter()
.filter(|image| is_dominant_image_text_candidate(image, page_bbox, text_chunks))
.collect();
if candidates.is_empty() {
return Vec::new();
}
let temp_dir = match create_temp_dir(page_number) {
Ok(dir) => dir,
Err(_) => return Vec::new(),
};
let image_files = match extract_visible_page_image_files(input_path, page_number, &temp_dir) {
Some(files) => files,
None => {
let _ = fs::remove_dir_all(&temp_dir);
return Vec::new();
}
};
let mut recovered = Vec::new();
for image in candidates {
let Some(image_index) = image.index else {
continue;
};
let Some(image_path) = image_files.get(image_index.saturating_sub(1) as usize) else {
continue;
};
let Ok(gray) = image::open(image_path).map(|img| img.to_luma8()) else {
continue;
};
if recover_bordered_raster_table_from_gray(&gray, image).is_some()
|| is_obvious_bar_chart_raster(&gray)
|| is_natural_photograph_raster(&gray)
|| is_dark_ui_screenshot_raster(&gray)
{
continue;
}
let Some(words) = run_tesseract_tsv_words_best(&gray, &["11", "6"], |candidate| {
looks_like_dense_prose_image_ocr(candidate)
}) else {
continue;
};
recovered.extend(lines_from_ocr_words(
&words,
image,
gray.width(),
gray.height(),
text_chunks,
));
}
let _ = fs::remove_dir_all(&temp_dir);
recovered
}
/// Recover synthetic table borders for strongly numeric raster tables.
pub fn recover_raster_table_borders(
input_path: &Path,
page_bbox: &BoundingBox,
page_number: u32,
text_chunks: &[TextChunk],
image_chunks: &[ImageChunk],
) -> Vec<TableBorder> {
if page_bbox.area() <= 0.0 || image_chunks.is_empty() {
return Vec::new();
}
let candidates: Vec<&ImageChunk> = image_chunks
.iter()
.filter(|image| is_ocr_candidate(image, page_bbox, text_chunks))
.collect();
if candidates.is_empty() {
return Vec::new();
}
let temp_dir = match create_temp_dir(page_number) {
Ok(dir) => dir,
Err(_) => return Vec::new(),
};
let image_files = match extract_visible_page_image_files(input_path, page_number, &temp_dir) {
Some(files) => files,
None => {
let _ = fs::remove_dir_all(&temp_dir);
return Vec::new();
}
};
let mut tables = Vec::new();
for image in candidates {
let Some(image_index) = image.index else {
continue;
};
let Some(image_path) = image_files.get(image_index.saturating_sub(1) as usize) else {
continue;
};
let Ok(gray) = image::open(image_path).map(|img| img.to_luma8()) else {
continue;
};
if is_obvious_bar_chart_raster(&gray)
|| is_natural_photograph_raster(&gray)
|| is_dark_ui_screenshot_raster(&gray)
{
continue;
}
if let Some(table) = recover_bordered_raster_table_from_gray(&gray, image) {
let chart_words = run_tesseract_tsv_words_best(&gray, &["6", "11"], |_| true);
if chart_words
.as_deref()
.is_some_and(looks_like_chart_label_ocr)
{
continue;
}
tables.push(table);
continue;
}
let Some(words) = run_tesseract_tsv_words_best(&gray, &["6", "11"], |candidate| {
looks_like_table_ocr(candidate)
}) else {
continue;
};
if looks_like_numeric_table_ocr(&words) {
if let Some(table) = build_numeric_table_border(&words, image) {
if is_matrixish_ocr_artifact_table(&table) {
continue;
}
tables.push(table);
continue;
}
}
if let Some(table) = build_structured_ocr_table_border(&words, image) {
if is_matrixish_ocr_artifact_table(&table) {
continue;
}
tables.push(table);
}
}
let _ = fs::remove_dir_all(&temp_dir);
tables
}
/// Recover OCR text into empty bordered tables by rasterizing the full page.
///
/// This targets graphics-dominant pages where native PDF text is sparse but the
/// page still exposes strong bordered geometry. It enriches existing empty
/// `TableBorder` cells directly from the rendered page appearance.
pub fn recover_page_raster_table_cell_text(
input_path: &Path,
page_bbox: &BoundingBox,
page_number: u32,
elements: &mut [ContentElement],
) {
if page_bbox.area() <= 0.0 {
return;
}
let native_text_chars = page_native_text_chars(elements);
let candidate_indices: Vec<usize> = elements
.iter()
.enumerate()
.filter_map(|(idx, elem)| {
let table = table_candidate_ref(elem)?;
let local_text_chars = native_text_chars_in_region(elements, &table.bbox);
if !table_needs_page_raster_ocr(table) {
return None;
}
if native_text_chars > MAX_NATIVE_TEXT_CHARS_FOR_PAGE_RASTER_OCR
&& local_text_chars > MAX_NATIVE_TEXT_CHARS_FOR_PAGE_RASTER_OCR
{
return None;
}
Some(idx)
})
.take(MAX_EMPTY_TABLES_FOR_PAGE_RASTER_OCR)
.collect();
if candidate_indices.is_empty() {
return;
}
let coverage: f64 = candidate_indices
.iter()
.filter_map(|idx| table_candidate_ref(&elements[*idx]).map(|table| table.bbox.area()))
.sum::<f64>()
/ page_bbox.area().max(1.0);
if coverage < MIN_EMPTY_TABLE_COVERAGE_FOR_PAGE_RASTER_OCR {
return;
}
let temp_dir = match create_temp_dir(page_number) {
Ok(dir) => dir,
Err(_) => return,
};
let prefix = temp_dir.join("page");
let status = Command::new("pdftoppm")
.arg("-png")
.arg("-f")
.arg(page_number.to_string())
.arg("-l")
.arg(page_number.to_string())
.arg("-singlefile")
.arg(input_path)
.arg(&prefix)
.status();
match status {
Ok(s) if s.success() => {}
_ => {
let _ = fs::remove_dir_all(&temp_dir);
return;
}
}
let page_image_path = prefix.with_extension("png");
let gray = match image::open(&page_image_path) {
Ok(img) => img.to_luma8(),
Err(_) => {
let _ = fs::remove_dir_all(&temp_dir);
return;
}
};
for idx in candidate_indices {
let Some(elem) = elements.get_mut(idx) else {
continue;
};
let Some(table) = table_candidate_mut(elem) else {
continue;
};
enrich_empty_table_from_page_raster(&gray, page_bbox, table);
}
let _ = fs::remove_dir_all(&temp_dir);
}
fn table_candidate_ref(elem: &ContentElement) -> Option<&TableBorder> {
match elem {
ContentElement::TableBorder(table) => Some(table),
ContentElement::Table(table) => Some(&table.table_border),
_ => None,
}
}
fn table_candidate_mut(elem: &mut ContentElement) -> Option<&mut TableBorder> {
match elem {
ContentElement::TableBorder(table) => Some(table),
ContentElement::Table(table) => Some(&mut table.table_border),
_ => None,
}
}
fn page_native_text_chars(elements: &[ContentElement]) -> usize {
native_text_chars_in_region(elements, &BoundingBox::new(None, f64::MIN, f64::MIN, f64::MAX, f64::MAX))
}
fn native_text_chars_in_region(elements: &[ContentElement], region: &BoundingBox) -> usize {
elements
.iter()
.filter(|elem| region.overlaps(elem.bbox()))
.map(|elem| match elem {
ContentElement::Paragraph(p) => p.base.value().chars().count(),
ContentElement::Heading(h) => h.base.base.value().chars().count(),
ContentElement::NumberHeading(h) => h.base.base.base.value().chars().count(),
ContentElement::TextBlock(tb) => tb.value().chars().count(),
ContentElement::TextLine(tl) => tl.value().chars().count(),
ContentElement::TextChunk(tc) => tc.value.chars().count(),
ContentElement::List(list) => list
.list_items
.iter()
.flat_map(|item| item.contents.iter())
.map(|content| match content {
ContentElement::Paragraph(p) => p.base.value().chars().count(),
ContentElement::TextBlock(tb) => tb.value().chars().count(),
ContentElement::TextLine(tl) => tl.value().chars().count(),
ContentElement::TextChunk(tc) => tc.value.chars().count(),
_ => 0,
})
.sum(),
_ => 0,
})
.sum()
}
fn recover_from_page_images(
input_path: &Path,
temp_dir: &Path,
page_number: u32,
candidates: Vec<&ImageChunk>,
text_chunks: &[TextChunk],
) -> Vec<TextChunk> {
let image_files = match extract_visible_page_image_files(input_path, page_number, temp_dir) {
Some(files) => files,
None => return Vec::new(),
};
if image_files.is_empty() {
return Vec::new();
}
let mut recovered = Vec::new();
for image in candidates {
let Some(image_index) = image.index else {
continue;
};
let Some(image_path) = image_files.get(image_index.saturating_sub(1) as usize) else {
continue;
};
let bordered_table = recover_bordered_raster_table(image_path, image);
if let Some(caption) = recover_bordered_raster_caption(image_path, image) {
recovered.push(caption);
}
if bordered_table.is_some() {
continue;
}
let Some(file_name) = image_path.file_name().and_then(|name| name.to_str()) else {
continue;
};
// Images extracted via pdfimages are at their native PDF DPI.
// We pass PDFTOPPM_DPI as a reasonable hint; Tesseract uses this only for
// geometry heuristics, not LSTM recognition, so approximate is fine.
let native_dpi = PDFTOPPM_DPI.to_string();
let Ok(tsv_output) = Command::new("tesseract")
.current_dir(temp_dir)
.arg(file_name)
.arg("stdout")
.arg("--dpi")
.arg(&native_dpi)
.arg("--psm")
.arg("6")
.arg("-c")
.arg("load_system_dawg=0")
.arg("-c")
.arg("load_freq_dawg=0")
.arg("tsv")
.output()
else {
continue;
};
if !tsv_output.status.success() {
continue;
}
let tsv = String::from_utf8_lossy(&tsv_output.stdout);
let words = parse_tesseract_tsv(&tsv);
if !looks_like_table_ocr(&words) {
continue;
}
recovered.extend(words_to_text_chunks(&words, image, text_chunks));
}
recovered
}
fn table_needs_page_raster_ocr(table: &TableBorder) -> bool {
if table.num_rows < 1 || table.num_columns < 2 {
return false;
}
let total_cells = table.rows.iter().map(|row| row.cells.len()).sum::<usize>();
if total_cells == 0 {
return false;
}
let text_cells = table_text_cell_count(table);
let text_cell_ratio = text_cells as f64 / total_cells as f64;
text_cells == 0 || text_cell_ratio < MIN_RASTER_TABLE_TEXT_CELL_RATIO
}
fn table_text_cell_count(table: &TableBorder) -> usize {
table
.rows
.iter()
.flat_map(|row| row.cells.iter())
.filter(|cell| cell_has_substantive_text(cell))
.count()
}
fn cell_has_substantive_text(cell: &TableBorderCell) -> bool {
let has_token_text = cell.content.iter().any(|token| {
matches!(token.token_type, TableTokenType::Text)
&& token.base.value.chars().any(|ch| ch.is_alphanumeric())
});
if has_token_text {
return true;
}
cell.contents.iter().any(|elem| match elem {
ContentElement::Paragraph(p) => p.base.value().chars().any(|ch| ch.is_alphanumeric()),
ContentElement::Heading(h) => h.base.base.value().chars().any(|ch| ch.is_alphanumeric()),
ContentElement::NumberHeading(h) => h
.base
.base
.base
.value()
.chars()
.any(|ch| ch.is_alphanumeric()),
ContentElement::TextBlock(tb) => tb.value().chars().any(|ch| ch.is_alphanumeric()),
ContentElement::TextLine(tl) => tl.value().chars().any(|ch| ch.is_alphanumeric()),
ContentElement::TextChunk(tc) => tc.value.chars().any(|ch| ch.is_alphanumeric()),
_ => false,
})
}
fn enrich_empty_table_from_page_raster(
gray: &GrayImage,
page_bbox: &BoundingBox,
table: &mut TableBorder,
) {
// Collect empty cells first, so we can OCR the whole table once and then
// distribute words into cells. This avoids calling tesseract per cell.
let mut empty_cells: Vec<EmptyCellRaster> = Vec::new();
for (row_idx, row) in table.rows.iter().enumerate() {
for (cell_idx, cell) in row.cells.iter().enumerate() {
if cell
.content
.iter()
.any(|token| matches!(token.token_type, TableTokenType::Text))
{
continue;
}
let Some((x1, y1, x2, y2)) = page_bbox_to_raster_box(gray, page_bbox, &cell.bbox)
else {
continue;
};
empty_cells.push(EmptyCellRaster {
row_idx,
cell_idx,
x1,
y1,
x2,
y2,
});
}
}
if empty_cells.is_empty() {
return;
}
// Fallback to legacy per-cell OCR when we can't build a stable table crop.
let Some((tx1, ty1, tx2, ty2)) = page_bbox_to_raster_box(gray, page_bbox, &table.bbox) else {
fill_cells_with_per_cell_ocr(gray, table, &empty_cells);
return;
};
let pad = CELL_INSET_PX * 2;
let crop_left = tx1.saturating_sub(pad);
let crop_top = ty1.saturating_sub(pad);
let crop_right = (tx2 + pad).min(gray.width());
let crop_bottom = (ty2 + pad).min(gray.height());
if crop_right <= crop_left || crop_bottom <= crop_top {
fill_cells_with_per_cell_ocr(gray, table, &empty_cells);
return;
}
let crop_width = crop_right - crop_left;
let crop_height = crop_bottom - crop_top;
if crop_width < MIN_CELL_SIZE_PX || crop_height < MIN_CELL_SIZE_PX {
fill_cells_with_per_cell_ocr(gray, table, &empty_cells);
return;
}
let cropped = gray
.view(crop_left, crop_top, crop_width, crop_height)
.to_image();
let is_bar_chart = is_obvious_bar_chart_raster(&cropped);
let is_photo = is_natural_photograph_raster(&cropped);
let is_ui = is_dark_ui_screenshot_raster(&cropped);
if is_bar_chart || is_photo || is_ui {
return;
}
let bordered = expand_white_border(&cropped, TABLE_RASTER_OCR_BORDER_PX);
let scaled = image::imageops::resize(
&bordered,
bordered.width() * OCR_SCALE_FACTOR,
bordered.height() * OCR_SCALE_FACTOR,
image::imageops::FilterType::Lanczos3,
);
let Some(words) = run_tesseract_tsv_words(&scaled, "6") else {
fill_cells_with_per_cell_ocr(gray, table, &empty_cells);
return;
};
if words.is_empty() {
fill_cells_with_per_cell_ocr(gray, table, &empty_cells);
return;
}
let chart_like = looks_like_chart_label_ocr(&words);
if chart_like {
return;
}
let mut buckets: Vec<Vec<(u32, u32, String)>> = vec![Vec::new(); empty_cells.len()];
let scale = f64::from(OCR_SCALE_FACTOR);
let border = f64::from(TABLE_RASTER_OCR_BORDER_PX);
for word in &words {
let cx_scaled = f64::from(word.left) + f64::from(word.width) / 2.0;
let cy_scaled = f64::from(word.top) + f64::from(word.height) / 2.0;
let cx_crop = cx_scaled / scale - border;
let cy_crop = cy_scaled / scale - border;
if cx_crop < 0.0 || cy_crop < 0.0 {
continue;
}
let cx_page = match u32::try_from(cx_crop.round() as i64) {
Ok(v) => crop_left.saturating_add(v),
Err(_) => continue,
};
let cy_page = match u32::try_from(cy_crop.round() as i64) {
Ok(v) => crop_top.saturating_add(v),
Err(_) => continue,
};
for (idx, cell) in empty_cells.iter().enumerate() {
if cx_page >= cell.x1 && cx_page < cell.x2 && cy_page >= cell.y1 && cy_page < cell.y2 {
buckets[idx].push((cy_page, cx_page, word.text.clone()));
break;
}
}
}
for (idx, cell) in empty_cells.iter().enumerate() {
let Some(row) = table.rows.get_mut(cell.row_idx) else {
continue;
};
let Some(target) = row.cells.get_mut(cell.cell_idx) else {
continue;
};
if target
.content
.iter()
.any(|token| matches!(token.token_type, TableTokenType::Text))
{
continue;
}
let mut parts = std::mem::take(&mut buckets[idx]);
if parts.is_empty() {
continue;
}
parts.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
let raw = parts
.into_iter()
.map(|(_, _, t)| t)
.collect::<Vec<_>>()
.join(" ");
let text = normalize_page_raster_cell_text(&target.bbox, raw);
if text.is_empty() {
continue;
}
target.content.push(TableToken {
base: TextChunk {
value: text,
bbox: target.bbox.clone(),
font_name: "OCR".to_string(),
font_size: target.bbox.height().max(6.0),
font_weight: 400.0,
italic_angle: 0.0,
font_color: "#000000".to_string(),
contrast_ratio: 21.0,
symbol_ends: Vec::new(),
text_format: TextFormat::Normal,
text_type: TextType::Regular,
pdf_layer: PdfLayer::Content,
ocg_visible: true,
index: None,
page_number: target.bbox.page_number,
level: None,
mcid: None,
},
token_type: TableTokenType::Text,
});
}
}
fn fill_cells_with_per_cell_ocr(
gray: &GrayImage,
table: &mut TableBorder,
empty_cells: &[EmptyCellRaster],
) {
for cell in empty_cells {
let Some(row) = table.rows.get_mut(cell.row_idx) else {
continue;
};
let Some(target) = row.cells.get_mut(cell.cell_idx) else {
continue;
};
if target
.content
.iter()
.any(|token| matches!(token.token_type, TableTokenType::Text))
{
continue;
}
let Some(text) =
extract_page_raster_cell_text(gray, &target.bbox, cell.x1, cell.y1, cell.x2, cell.y2)
else {
continue;
};
if text.is_empty() {
continue;
}
target.content.push(TableToken {
base: TextChunk {
value: text,
bbox: target.bbox.clone(),
font_name: "OCR".to_string(),
font_size: target.bbox.height().max(6.0),
font_weight: 400.0,
italic_angle: 0.0,
font_color: "#000000".to_string(),
contrast_ratio: 21.0,
symbol_ends: Vec::new(),
text_format: TextFormat::Normal,
text_type: TextType::Regular,
pdf_layer: PdfLayer::Content,
ocg_visible: true,
index: None,
page_number: target.bbox.page_number,
level: None,
mcid: None,
},
token_type: TableTokenType::Text,
});
}
}
fn page_bbox_to_raster_box(
gray: &GrayImage,
page_bbox: &BoundingBox,
bbox: &BoundingBox,
) -> Option<(u32, u32, u32, u32)> {
if page_bbox.width() <= 0.0 || page_bbox.height() <= 0.0 {
return None;
}
let left = ((bbox.left_x - page_bbox.left_x) / page_bbox.width() * f64::from(gray.width()))
.clamp(0.0, f64::from(gray.width()));
let right = ((bbox.right_x - page_bbox.left_x) / page_bbox.width() * f64::from(gray.width()))
.clamp(0.0, f64::from(gray.width()));
let top = ((page_bbox.top_y - bbox.top_y) / page_bbox.height() * f64::from(gray.height()))
.clamp(0.0, f64::from(gray.height()));
let bottom = ((page_bbox.top_y - bbox.bottom_y) / page_bbox.height()
* f64::from(gray.height()))
.clamp(0.0, f64::from(gray.height()));
let x1 = left.floor() as u32;
let x2 = right.ceil() as u32;
let y1 = top.floor() as u32;
let y2 = bottom.ceil() as u32;
(x2 > x1 && y2 > y1).then_some((x1, y1, x2, y2))
}