//! A lab report's pages, read: its header (who, when, which order, partial//! or final) and every result row of its tables, with the lines that read as//! nothing counted by number. PURE: text lines in, a [`Parsed`] out.//!//! The table is found by its head (`Test Name | Result | Unit | Bio. Ref.//! Interval | Method`, or any head the generic layout knows); the head's//! cells set the columns, page by page, since the head repeats per page.//! Under it a line is//!//! - a **result**: a name and a result, with its unit, interval, method;//! - a **continuation**: only the interval (or method) column, right under a//! result: the interval goes on over several lines (bands by category);//! - a **name's second line**: a name-column line opening with `(` or a//! lower-case word, right under a result;//! - a **panel title**: a name-column line alone, short, that a result follows;//! - **prose**: a line crossing the columns, or opening with `Interpretation`,//! `Note` and the like, and every line after it until the next result//! row: an interpretive paragraph, never a result;//! - **furniture**: page numbers, end of report, signatures;//! - **small print**: a line set clearly smaller than the table's head (a//! comment's own table of bands, a footnote) is never a result;//! - anything else is **unparsed**, kept by its line number for review.use std::collections::BTreeMap;use serde::Serialize;usesuper::layout::{Layout, Layouts};usesuper::text::{TextCell, TextLine, TextPage};/// One result row, as printed.#[derive(Debug, Clone, PartialEq, Serialize)]pubstructRow {/// 1-based page, and line on the whole report (both for review, never a value).pub page: usize,pub line: usize,/// The panel title it stands under, as printed.pub panel: String,pub name: String,pub result: String,pub unit: String,/// The interval, lines joined by `\n`.pub range: String,pub method: String,pub flag: String,pub specimen: String,}/// What a report says of itself and its rows.#[derive(Debug, Clone, PartialEq, Default, Serialize)]pubstructParsed {/// The layout whose table head was found; `None` when none was.pub layout: Option<String>,/// Header fields by the reader's key (`name`, `order_id`…), as printed.pub fields: BTreeMap<String, String>,pub rows: Vec<Row>,/// Lines under a table head that read as nothing: (page, line).pub unparsed: Vec<(usize, usize)>,/// Lines read as interpretive prose and left out.pub prose: usize,/// Rows printed again with the same name, result, unit and interval (a/// section a lab printed twice): kept once.pub repeated: usize,}/// A table head found on a line: each column and where it starts.#[derive(Debug, Clone)]structHead {/// (column, left edge) from left to right. columns: Vec<(String, f32)>,/// Where each column's head itself starts and ends. heads: Vec<(f32, f32)>,/// The head line's font size, and where it stands. size: f32, y: f32,/// The layout's values stand well left of their heads. left_of_heads: bool,}/// A line under the head set smaller than this share of the head's size is small print.const SMALL_PRINT: f32 = 0.85;fn find_head(line: &TextLine, layout: &Layout) -> Option<Head> {letmut columns: Vec<(String, f32, f32)> = Vec::new();for cell in &line.cells {if layout.is_head_word(&cell.text) {continue; }let column = layout.column_of(&cell.text)?;if columns.iter().any(|(known, _, _)| known == column) && !layout.split.iter().any(|split| split == column) {returnNone; } columns.push((column.to_string(), cell.x0, cell.x1)); }let has = |column: &str| columns.iter().any(|(known, _, _)| known == column);if !layout.needs.iter().all(|need| has(need)) {returnNone; }if !layout.needs_one_of.is_empty() && !layout.needs_one_of.iter().any(|need| has(need)) {returnNone; } columns.sort_by(|a, b| a.1.total_cmp(&b.1));// A column starts halfway between the head before it and its own: a lab// prints its values a little left of the head as often as under it.letmut out = Vec::new();for (at, (column, x0, _)) in columns.iter().enumerate() {let left = if at == 0 { f32::NEG_INFINITY } else {let gap = (x0 - columns[at - 1].2).max(0.0); x0 - gap * 0.5 }; out.push((column.clone(), left)); }Some(Head { columns: out, heads: columns.iter().map(|(_, x0, x1)| (*x0, *x1)).collect(), size: line.size, y: line.y, left_of_heads: layout.left_of_heads })}implHead {fn column_at(&self, x0: f32) -> usize {self.columns.iter().rposition(|(_, left)| *left <= x0).unwrap_or(0) }/// The column a cell is printed in: the one its left edge falls in, or, in/// a layout whose values stand left of their heads, the next when it starts/// past the end of this column's head and nearer the next head (a unit/// printed well left of `Units`).fn column_for(&self, cell: &TextCell) -> usize {let at = self.column_at(cell.x0);if !self.left_of_heads {return at; }match (self.heads.get(at), self.heads.get(at + 1)) { (Some((x0, x1)), Some((next, _))) if cell.x0 > *x1 && (next - cell.x0).abs() < (cell.x0 - x0).abs() => at + 1, _ => at, } }/// A title centred over the columns: one cell reaching over two heads or/// more, its middle near the table's, worded as a title (no `:`, no full stop).fn centred_title(&self, line: &TextLine) -> bool {let [cell] = line.cells.as_slice() else { returnfalse };let (Some((left, _)), Some((_, right))) = (self.heads.first(), self.heads.last()) else { returnfalse };let reaches = self.heads.iter().filter(|(x0, x1)| cell.x0 < *x1 && cell.x1 > *x0).count();let middle = (cell.x0 + cell.x1) / 2.0;let text = cell.text.trim(); reaches >= 2 && (middle - (left + right) / 2.0).abs() <= 0.12 * (right - left) && !text.contains(':') && !text.ends_with('.') }/// Does a name-column cell ending at `x1` run on across the table? A/// long test title may reach over the result's head; a paragraph runs/// past the column after it.fn crosses(&self, x1: f32) -> bool {match (self.heads.get(2), self.heads.get(1)) { (Some((start, _)), _) => x1 > *start + 2.0, (None, Some((_, end))) => x1 > *end + 2.0, _ => false, } }/// Every place a column stands: one, or two for a split column.fn indices<'a>(&'a self, column: &'a str) -> implIterator<Item = usize> + 'a {self.columns.iter().enumerate().filter(move |(_, (known, _))| known == column).map(|(at, _)| at) }/// The head's own second line (`Biological Reference` / `Interval`): right/// under it, each word within a head's own width, no figure.fn goes_on_in(&self, line: &TextLine) -> bool { line.y > self.y && line.y - self.y <= 1.6 * self.size.max(1.0) && !line.cells.is_empty() && line.cells.iter().all(|cell| !cell.text.chars().any(|c| c.is_ascii_digit()) && self.heads.iter().any(|(x0, x1)| cell.x0 >= *x0 - 3.0 && cell.x1 <= *x1 + 3.0)) }}/// A panel under a centred section title: both, the section first.fn within(section: &str, panel: &str) -> String {match (section.is_empty(), panel.is_empty()) { (true, _) => panel.to_string(), (false, true) => section.to_string(), (false, false) => format!("{section} · {panel}"), }}/// A name with a bracket left open (`Platelet Count (Impedance or`): its next line goes on with it.fn bracket_open(name: &str) -> bool { name.matches('(').count() > name.matches(')').count()}/// A line's cells by column, and whether any crossed into the next.fn split(line: &TextLine, head: &Head) -> (Vec<String>, bool) {letmut out = vec![String::new(); head.columns.len()];letmut crossed = false;for cell in &line.cells {let at = head.column_for(cell);// Prose opens at the left margin and runs on across the columns; a// wide interval or method only runs over its neighbour.if at == 0 && head.crosses(cell.x1) { crossed = true; }if !out[at].is_empty() { out[at].push(' '); } out[at].push_str(&cell.text); } (out, crossed)}/// A label printed with its value on the next line: the field, the label's edges and its line.#[derive(Debug, Clone)]structOpen { field: String, x0: f32, x1: f32, y: f32, size: f32,}/// `label : value` pairs on a header line; the labels left with no value are said back.fn header_pairs(line: &TextLine, layouts: &Layouts, fields: &mut BTreeMap<String, String>) -> Vec<Open> {letmut open = Vec::new();let cells: Vec<&str> = line.cells.iter().map(|cell| cell.text.as_str()).collect();letmut at = 0;while at < cells.len() {let cell = cells[at];let (label, mut value, mut used) = match cell.split_once(':') {Some((label, value)) => (label.trim(), value.trim().to_string(), 1),None => (cell.trim(), String::new(), 1), };ifletSome(field) = layouts.field_of(label) {if value.is_empty() {ifletSome(next) = cells.get(at + 1) {let next = next.trim();// The next cell is the value unless it is itself a label.let bare = next.trim_start_matches(':').trim();if !bare.is_empty() && layouts.field_of(bare.split(':').next().unwrap_or(bare)).is_none() { value = bare.to_string(); used = 2; } } }if !value.is_empty() { fields.entry(field.to_string()).or_insert(value); } else {let cell = &line.cells[at]; open.push(Open { field: field.to_string(), x0: cell.x0, x1: cell.x1, y: line.y, size: line.size }); } } at += used; } open}/// Values for labels the line above left open: the cell right below a label/// (`PATIENT INFORMATION` over the name), or a `: value` a little lower to its/// right (`COLLECTED ON` and `:12-Jul-2015 09:10` drawn a few points apart).fn values_below(line: &TextLine, open: &[Open], layouts: &Layouts, fields: &mut BTreeMap<String, String>) {for label in open {let gap = line.y - label.y;if gap <= 0.0 || gap > 1.6 * label.size.max(1.0) {continue; }let found = line.cells.iter().find_map(|cell| {let text = cell.text.trim();let bare = text.trim_start_matches(':').trim();if bare.is_empty() || layouts.field_of(bare.split(':').next().unwrap_or(bare)).is_some() {returnNone; }let below = (cell.x0 - label.x0).abs() <= 3.0;let beside = text.starts_with(':') && cell.x0 > label.x1 && gap <= 0.6 * label.size.max(1.0); (below || beside).then(|| bare.to_string()) });ifletSome(value) = found { fields.entry(label.field.clone()).or_insert(value); } }}/// A result cell that can be a result: a number, or a few words (`Non Reactive`, `Pale Yellow`).fn reads_as_value(text: &str) -> bool {super::interval::read_value(text).number.is_some() || (words(text) <= 3 && text.chars().count() <= 24)}/// A name column a lab fills with the word `Result` under the test's own title.fn is_generic_name(name: &str) -> bool { matches!(super::catalogue::fold_name(name).as_str(), "result" | "results" | "value" | "observed value" | "test result")}/// A name that opens with a figure or a bound (`<= 5.6`, `1st trimester`, `G1 >= 90`): a row of a table of bands, never a test.pubfn names_a_band(name: &str) -> bool {let first = name.trim().chars().next().unwrap_or(' ');if"<>≤≥=±".contains(first) {returntrue; }letmut tokens = name.split_whitespace();let (lead, next) = (tokens.next().unwrap_or_default(), tokens.next().unwrap_or_default().to_lowercase());// A bare figure (`99 or below`), not a test named by its hours (`24 Hrs Urine Protein`) or its chemistry (`25-OH Vitamin D`).let figure = lead.chars().all(|c| c.is_ascii_digit() || ".-–,".contains(c)) && !matches!(next.trim_end_matches('.'), "hr" | "hrs" | "hour" | "hours" | "h");let ordinal = lead.len() <= 4 && ["st", "nd", "rd", "th"].iter().any(|end| lead.to_lowercase().strip_suffix(end).is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit())));if first.is_ascii_digit() && (figure || ordinal) {returntrue; }// A short code then a bound: `G1 >= 90`, `A2 30 - 299`.letmut words = name.split_whitespace();let code = words.next().unwrap_or_default();let second = words.next().unwrap_or_default(); code.len() <= 2 && code.chars().any(|c| c.is_ascii_digit()) && second.chars().next().is_some_and(|c| c.is_ascii_digit() || "<>≤≥=".contains(c))}/// A unit cell that holds a figure or a bound is a band's column, not a unit.fn unit_is_a_figure(unit: &str) -> bool {let unit = unit.trim();let bound = unit.chars().next().is_some_and(|c| "<>≤≥=(".contains(c));let figure = !unit.is_empty() && unit.chars().all(|c| c.is_ascii_digit() || " .-–,".contains(c)); bound || figure}/// A unit cell with the interval run into it (`10^6/cu.mm 4.5 - 5.5`): the unit and the interval.fn split_unit(unit: &str) -> Option<(String, String)> {let (first, rest) = unit.trim().split_once(' ')?;let rest = rest.trim();let opens = rest.chars().next()?; (opens.is_ascii_digit() || "<>≤≥".contains(opens)).then(|| (first.to_string(), rest.to_string()))}/// `(Method: CHOD/PAP)` printed under a test's name: the method alone.fn method_note(name: &str) -> Option<String> {let inner = name.trim().strip_prefix('(')?.trim_end_matches(')').trim();let rest = inner.strip_prefix("Method").or_else(|| inner.strip_prefix("METHOD")).or_else(|| inner.strip_prefix("method"))?;let rest = rest.trim_start_matches([':', ' ', '-']).trim(); (!rest.is_empty()).then(|| rest.to_string())}/// A qualitative result a test prints on its own (`Non-Reactive`, `Not Detected`).fn is_outcome(result: &str) -> bool {const OUTCOMES: &[&str] = &["reactive", "non reactive", "nonreactive", "negative", "positive", "detected", "not detected", "present", "absent", "nil", "normal", "abnormal", "weakly reactive", "weak positive", "equivocal", "indeterminate", "trace"];let folded = super::catalogue::fold_name(result); OUTCOMES.contains(&folded.as_str())}fn words(text: &str) -> usize { text.split_whitespace().count()}fn opens_lower(text: &str) -> bool { text.starts_with('(') || text.chars().next().is_some_and(char::is_lowercase)}/// Read a report's pages with the shipped layouts.pubfn parse(pages: &[TextPage]) -> Parsed { parse_with(pages, Layouts::shipped())}pubfn parse_with(pages: &[TextPage], layouts: &Layouts) -> Parsed {// The layout: the first whose head any page carries.let layout = layouts.layouts.iter().find(|layout| pages.iter().any(|page| page.lines.iter().any(|line| find_head(line, layout).is_some())));letmut parsed = Parsed { layout: layout.map(|layout| layout.id.clone()), ..Parsed::default() };letmut number = 0usize;letmut panel = String::new();// A title centred over the columns (`Complete Urine Examination`): the panels under it are its.letmut section = String::new();// A panel title printed last on a page names the rows on the next.letmut carried: Option<String> = None;let ignored = |field: &str| layout.is_some_and(|layout| layout.ignore_fields.iter().any(|ignored| ignored == field));// A row's interval or method may run on over the page break, under the next page's head.letmut continuing = false;for (page_at, page) in pages.iter().enumerate() {let page_no = page_at + 1;letmut head: Option<Head> = None;// State under the head.letmut prose = false;letmut pending: Option<String> = None;letmut first_head = true;letmut last_y: Option<f32> = None;// The header block of this page (its own sample type: a urine page says so).letmut page_fields: BTreeMap<String, String> = BTreeMap::new();letmut open: Vec<Open> = Vec::new();for line in &page.lines { number += 1;let text = line.text();ifletSome(layout) = layout {ifletSome(found) = find_head(line, layout) {for cell in line.cells.iter().filter(|cell| layout.is_head_word(&cell.text)) {ifletSome(status) = layouts.status_of(&cell.text) { parsed.fields.entry("status".into()).or_insert_with(|| status.to_string()); } } head = Some(found); prose = false; pending = if first_head { carried.take() } else { None }; first_head = false; last_y = Some(line.y);continue; } }letSome(head) = head.as_ref() else { values_below(line, &open, layouts, &mut parsed.fields); values_below(line, &open, layouts, &mut page_fields); open = header_pairs(line, layouts, &mut parsed.fields); header_pairs(line, layouts, &mut page_fields);ifletSome(status) = layouts.status_of(&text) { parsed.fields.entry("status".into()).or_insert_with(|| status.to_string()); }continue; };if layouts.is_furniture(&text) {continue; }if last_y == Some(head.y) && head.goes_on_in(line) { last_y = Some(line.y);continue; }if line.size < SMALL_PRINT * head.size {// Small print: a comment's table of bands, a footnote. It changes nothing above it. parsed.prose += 1;continue; }// A header block repeated low on a page (a second report stapled on) is read too.// A band of an interval may sit a blank line below the one before it.let close = last_y.is_none_or(|y| line.y - y <= 3.0 * line.size.max(1.0)); last_y = Some(line.y);let (cols, crossed) = split(line, head);if layout.is_some_and(|layout| line.cells.iter().all(|cell| layout.column_of(&cell.text).is_some())) {// Column heads alone (`Biological Ref. Interval`): a small table of its own follows. prose = true; pending = None; continuing = false; parsed.prose += 1;continue; }let get = |column: &str| head.indices(column).map(|at| cols[at].trim()).filter(|text| !text.is_empty()).collect::<Vec<_>>().join(" ");let (mut name, mut result) = (get("name"), get("result"));if result.is_empty() && ["unit", "range"].iter().any(|column| !get(column).is_empty()) {// The value run into the name's cell (`… - ULTRA 2.15`).ifletSome((rest, last)) = name.rsplit_once(' ') {ifsuper::interval::read_value(last).number.is_some() && !rest.trim().is_empty() && !names_a_band(&name) { result = last.to_string(); name = rest.trim().to_string(); } } }if result.is_empty() && continuing && close && !prose {ifletSome(method) = method_note(&name) {// `(Method: …)` under its row's name: the row's method.let last = parsed.rows.last_mut().expect("continuing follows a row");if last.method.is_empty() { last.method = method; } else { last.method = format!("{} {method}", last.method); } name.clear(); } }let page_specimen = if ignored("sample_type") { String::new() } else { page_fields.get("sample_type").cloned().unwrap_or_default() };let others = ["unit", "range", "method", "flag", "specimen"].iter().any(|column| !get(column).is_empty());if name.is_empty() && result.is_empty() && !others {continue; }if crossed && result.is_empty() { prose = true; pending = None; continuing = false; parsed.prose += 1;continue; }if !name.is_empty() && result.is_empty() && !others && layouts.opens_prose(&name) { prose = true; pending = None; continuing = false; parsed.prose += 1;continue; }let numeric = super::interval::read_value(&result).number.is_some();let bare_word = !numeric && !is_outcome(&result) && ["unit", "range", "method"].iter().all(|column| get(column).is_empty());let sentence = name.ends_with('.') && words(&name) > 4;// Inside a paragraph, a figure beside a line of words (`2.` and a// numbered condition in two columns) is the paragraph going on.let wordy = |column: &str| {let text = get(column); words(&text) >= 6 && !text.chars().any(|c| c.is_ascii_digit()) };if prose && !name.is_empty() && !result.is_empty() && (wordy("range") || wordy("method") || wordy("unit")) { parsed.prose += 1;continue; }if !name.is_empty() && !result.is_empty() && (names_a_band(&name) || unit_is_a_figure(&get("unit")) || bare_word || sentence || (layouts.prose_word(&name) && !numeric)) {// A table of bands, a title with a word beside it, or a// test's own interpretation line: never a result.if names_a_band(&name) || unit_is_a_figure(&get("unit")) || sentence || bare_word || layouts.prose_word(&name) {if bare_word {// `COLOR YELLOWISH` under a title: the title still names the rows after it.ifletSome(title) = pending.take() { panel = title; } } prose = true; pending = None; continuing = false; } parsed.prose += 1;continue; }if !name.is_empty() && !result.is_empty() && reads_as_value(&result) {letmut name = name;ifletSome(title) = pending.take() {if opens_lower(&name) { name = format!("{title} {name}"); } else { panel = title; } }if is_generic_name(&name) && !panel.is_empty() {// `Result` under the test's own title: the title names it. name = panel.clone(); } prose = false; continuing = true;let (mut unit, mut range) = (get("unit"), get("range"));if range.is_empty() {ifletSome((alone, interval)) = split_unit(&unit) { unit = alone; range = interval; } }let specimen = Some(get("specimen")).filter(|specimen| !specimen.is_empty()).unwrap_or_else(|| page_specimen.clone()); parsed.rows.push(Row { page: page_no, line: number, panel: within(§ion, &panel), name, result, unit, range, method: get("method"), flag: get("flag"), specimen });continue; }if !name.is_empty() && !result.is_empty() {// A result cell holding a sentence: a paragraph laid out wide. prose = true; pending = None; continuing = false; parsed.prose += 1;continue; }if name.is_empty() && !result.is_empty() && head.centred_title(line) && super::interval::read_value(&result).number.is_none() {// A title centred over the columns. section = result; panel.clear(); pending = None; prose = false; continuing = false;continue; }if name.is_empty() && !result.is_empty() && prose { parsed.prose += 1;continue; }if name.is_empty() && !result.is_empty() {// The value on the line under its name.let word_goes_on = continuing && close && !prose && pending.is_none() && !others && parsed.rows.last().is_some_and(|last| super::interval::read_value(&last.result).number.is_none());if word_goes_on {// A word result wrapped onto the next line (`SLIGHTLY` / `TURBID`).let last = parsed.rows.last_mut().expect("continuing follows a row"); last.result = format!("{} {result}", last.result); } elseifletSome(title) = pending.take() { prose = false; continuing = true;let specimen = Some(get("specimen")).filter(|specimen| !specimen.is_empty()).unwrap_or_else(|| page_specimen.clone()); parsed.rows.push(Row { page: page_no, line: number, panel: within(§ion, &panel), name: title, result, unit: get("unit"), range: get("range"), method: get("method"), flag: get("flag"), specimen }); } else { parsed.unparsed.push((page_no, number)); continuing = false; }continue; }if name.is_empty() && others {// An interval or a method goes on over lines; a unit or specimen is said once.let said_twice = parsed.rows.last().is_some_and(|last| (!get("unit").is_empty() && !last.unit.is_empty()) || (!get("specimen").is_empty() && !last.specimen.is_empty()));if continuing && close && !prose && !said_twice {let last = parsed.rows.last_mut().expect("continuing follows a row");for (column, into) in [("range", &mut last.range), ("method", &mut last.method), ("unit", &mut last.unit), ("specimen", &mut last.specimen)] {let more = get(column);if more.is_empty() {continue; }if into.is_empty() { *into = more; } else { into.push(if column == "range" { '\n' } else { ' ' }); into.push_str(&more); } } } elseif said_twice && ["range", "method", "specimen"].iter().all(|column| get(column).is_empty()) && get("unit").chars().all(|c| c.is_alphabetic() || c == ' ') {// The unit's own second word (`mg/g` / `creatinine`). } elseif !prose { parsed.unparsed.push((page_no, number)); }continue; }if !name.is_empty() && !others {if prose { parsed.prose += 1;// A short title after a paragraph (`MAGNESIUM, SERUM`) names the row that may follow. pending = (words(&name) <= 6 && !name.ends_with('.') && !name.contains(':') && !opens_lower(&name)).then(|| name.clone());continue; }if continuing && close && !(name.ends_with('.') && words(&name) > 3) && (opens_lower(&name) || parsed.rows.last().is_some_and(|last| last.name.ends_with('-') || bracket_open(&last.name))) {let last = parsed.rows.last_mut().expect("continuing follows a row"); last.name = format!("{} {name}", last.name);continue; } continuing = false;if words(&name) > 8 || (name.ends_with('.') && words(&name) > 3) { prose = true; pending = None; parsed.prose += 1;continue; } pending = Some(name);continue; }// A name with a unit or an interval and no result: a row that reads as nothing.if !prose { parsed.unparsed.push((page_no, number)); } continuing = false; } carried = pending; }for field in layout.map(|layout| layout.ignore_fields.as_slice()).unwrap_or_default() { parsed.fields.remove(field); }letmut seen = std::collections::HashSet::new();let before = parsed.rows.len(); parsed.rows.retain(|row| seen.insert((super::catalogue::fold_name(&row.name), row.result.clone(), row.unit.clone(), row.range.clone()))); parsed.repeated = before - parsed.rows.len(); parsed}