use crate::pdfium_backend::TextCell;
fn touches(a: &TextCell, b: &TextCell) -> bool {
a.l <= b.r && b.l <= a.r && a.t <= b.b && b.t <= a.b
}
pub(crate) fn uncovered<'a>(
cells: impl IntoIterator<Item = &'a TextCell>,
covers: &[TextCell],
) -> Vec<TextCell> {
cells
.into_iter()
.filter(|c| !covers.iter().any(|v| touches(c, v)))
.cloned()
.collect()
}
pub(crate) fn words_and_ocr_cells(
native_words: &[TextCell],
ocr_words: &[TextCell],
ocr_lines: &[TextCell],
) -> Vec<TextCell> {
let native = uncovered(native_words, ocr_lines);
let words = uncovered(ocr_words, &native);
let lines = uncovered(ocr_lines, &words);
native.into_iter().chain(words).chain(lines).collect()
}
#[cfg(test)]
mod tests {
use super::*;
fn cell(l: f32, t: f32, r: f32, b: f32, text: &str) -> TextCell {
TextCell {
text: text.into(),
l,
t,
r,
b,
}
}
const HEADER: (f32, f32, f32, f32) = (0.0, 0.0, 50.0, 10.0);
const VALUE: (f32, f32, f32, f32) = (60.0, 20.0, 90.0, 30.0);
fn at(b: (f32, f32, f32, f32), text: &str) -> TextCell {
cell(b.0, b.1, b.2, b.3, text)
}
fn texts(cells: &[TextCell]) -> Vec<&str> {
cells.iter().map(|c| c.text.as_str()).collect()
}
#[test]
fn table_tokens_keep_ocr_lines_next_to_native_words() {
let header = at(HEADER, "Week Begin");
let filled_value = at(VALUE, "5000");
let hidden_word = cell(5.0, 2.0, 20.0, 8.0, "Week");
let tokens = words_and_ocr_cells(&[filled_value, hidden_word], &[], &[header]);
assert_eq!(texts(&tokens), ["5000", "Week Begin"]);
}
#[test]
fn table_tokens_prefer_ocr_words_over_their_line() {
let header = at(HEADER, "Week Begin");
let ocr_words = [
cell(0.0, 0.0, 22.0, 10.0, "Week"),
cell(26.0, 0.0, 50.0, 10.0, "Begin"),
at(VALUE, "5000"),
];
let native = [at(VALUE, "5000")];
let tokens = words_and_ocr_cells(&native, &ocr_words, &[header]);
assert_eq!(texts(&tokens), ["5000", "Week", "Begin"]);
}
}