diff --git a/COMPARING.md b/COMPARING.md index a04cb7e7..a09e5f74 100644 --- a/COMPARING.md +++ b/COMPARING.md @@ -176,7 +176,36 @@ case — see the divergence table below. | **XLSX** | **9 / 9** ✅ | 9 / 9 | | **PPTX** | **7 / 7** ✅ | 7 / 7 | | **DOCX** | **25 / 26** | 25 / 26 | -| **HTML** | **28 / 32** | 29 / 32 | +| **HTML** | **28 / 33** | 28 / 33 | +| **PDF** | **4 / 14** † | 5 / 14 | + +> † The pure-parse backends above are scored against **live** docling. **PDF** is a +> discriminative ML reconstruction pipeline (not a deterministic parse), so it is +> scored against a committed groundtruth corpus (`tests/data/pdf/groundtruth`) that +> is **regenerated from live docling** and therefore matches `scripts/conformance.sh +> pdf` (padded GitHub tables, current docling text). Within-one adds +> `right_to_left_01` (a 2-line diff). + +**PDF** (`*.pdf`) ports docling's *standard* (discriminative) PDF pipeline. pdfium +extracts the text layer (glyph cells + bounding boxes) and renders each page to a +bitmap; an ONNX model stack then interprets it — **layout detection** (the +`heron`/RT-DETR region model), **TableFormer** table-structure recognition (a full +port: image encoder + autoregressive OTSL structure decoder + cell-bbox decoder, +exported to ONNX — see `tableformer.rs`, with cv2-exact `INTER_AREA`/`INTER_LINEAR` +preprocessing in `resample.rs`), and **PaddleOCR** recognition for scanned / +image-only pages — and regions are assembled in reading order into a +`DoclingDocument`. Text reconstruction ports **docling-parse's line sanitizer** +(`dp_lines.rs`, from `cells.h`): the 3-pass corner-distance contraction with +`merge_with` space insertion, `enforce_same_font`, ligature recomposition, and +loose-box geometry — fed by pdfium glyphs. This closed the text-run-boundary gap +that previously capped conformance (inter-run spacing like `LABEL :`, justified +double-spacing, lam-alef ordering). Byte-exact today: `picture_classification`, +`code_and_formula`, `2305.03393v1-pg9` (**including its TableFormer-reconstructed +table, cell for cell**), and `multi_page`. The rest are structurally correct but +not yet byte-exact; the remaining gaps are model-level — TableFormer multi-row +header/span structure on dense papers, layout classification (a TOC read as a +picture, a survey read as tables), title-page reading order, and justified RTL +double-spaces (`right_to_left_01`, within one line). **DOCX** (`*.docx`) is a core port of `MsWordDocumentBackend` (`roxmltree` over the `ooxml` helper): paragraphs, headings (by style, incl. Title), **numbered @@ -218,9 +247,10 @@ the drawing parts via the shared `ooxml` zip/rels helper). The one miss all-empty table. CSV, Markdown, AsciiDoc, and the DeepSeek-OCR Markdown variant are fully -one-to-one. HTML's 4 remaining misses all require docling-internal subsystems -that depend on **headless-browser rendering** or are otherwise impractical to -port — see below. 28/32 is effectively the ceiling for a pure-parse port. +one-to-one. HTML's 5 remaining misses are a tail of docling-internal behaviours — +some requiring **headless-browser rendering**, others (a large Wikipedia page, +key-value form extraction) needing substantial structural work — see below. 28/33 +is roughly the ceiling for a pure-parse port. **AsciiDoc** (`*.asciidoc`/`*.adoc`) ports docling's line-oriented `AsciiDocBackend`: titles/sections, nested bullet/numbered lists (all rendered diff --git a/MIGRATION.md b/MIGRATION.md index e5e27f85..c726dc09 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -10,8 +10,11 @@ phased plan is kept at the end as history.) > (legacy + a Rust-only *strict* mode), docling-native **JSON** output, and > **image extraction**. The declarative formats are pure-Rust and checked > byte-for-byte against *live* docling; the PDF/image/METS ML path lives in -> `fleischwolf-pdf` and is checked against a deterministic snapshot baseline. -> `cargo test` is green (unit tests + a 131-source output-regression suite). +> `fleischwolf-pdf` (pdfium + ONNX layout/TableFormer/OCR + a port of +> docling-parse's line sanitizer) and is also measured byte-for-byte against live +> docling — **4 / 14 PDF fixtures exact** (see `PDF_CONFORMANCE.md`), with a +> snapshot baseline guarding against regressions. `cargo test` is green (unit +> tests + a 131-source output-regression suite). --- @@ -79,15 +82,17 @@ PyPI; run via `scripts/conformance.sh `), not the committed groundtruth Shared OOXML infrastructure (`ooxml.rs`): a `zip` reader, `.rels` parsing, part content-type resolution, and image extraction — reused by DOCX/PPTX/XLSX/EPUB. -### ML formats — `fleischwolf-pdf`, snapshot baseline +### ML formats — `fleischwolf-pdf` -These run docling's *discriminative* PDF pipeline ported to ONNX. Output is **not -byte-for-byte** with docling (different OCR/table models — §4); it is pinned by a -deterministic snapshot (`scripts/pdf_conformance.sh`, **76/76 exact**). +These run docling's *discriminative* PDF pipeline ported to ONNX. They are now +measured **byte-for-byte against live docling** (the committed PDF groundtruth is +regenerated from it): **4 / 14 exact**, the rest close — see `PDF_CONFORMANCE.md`. +A deterministic snapshot baseline (`scripts/pdf_conformance.sh`) still guards +against regressions. | Format | How | |---|---| -| PDF | pdfium text cells + page render → RT-DETR layout (ONNX) → PP-OCRv3 OCR for scanned pages → geometric table reconstruction → reading-order assembly | +| PDF | pdfium glyph cells + page render → RT-DETR layout (ONNX) → **TableFormer** table structure (ONNX) → PP-OCRv3 OCR for scanned pages → **docling-parse line sanitizer** (`dp_lines.rs`) + reading-order assembly | | Images (tiff/webp/png/jpeg) | the same pipeline, image as a single page | | METS / Google Books | `.tar.gz` of per-page hOCR + TIFF → cells from hOCR → the same layout+assembly path (no OCR needed) | @@ -135,22 +140,33 @@ These are deliberate or unavoidable divergences, not bugs. entity re-escaping); `strict` produces cleaner Markdown. docling has no such switch. All conformance numbers are measured in **legacy** mode. -4. **Tables match *current* docling, not the committed fixtures.** docling-core's - Markdown table serializer emits padded GitHub tables today; the repo's - committed groundtruth `.md` corpus predates that and uses a minimal `| - |` - format. `fleischwolf` matches the **current/live** output — so table-bearing - formats look correct against live docling and "wrong" against the stale `.md`. +4. **Tables use docling-core's padded GitHub format.** All backends emit the + width-padded `tabulate(tablefmt="github")` tables that current published + docling produces (columns padded to header-width+2 or the widest data cell, + numeric columns right-aligned). The PDF groundtruth was regenerated from live + docling to match. (An earlier compact `| - |` variant — to match a stale + committed corpus — was reverted; the `compact_tables` option still exists but + no backend sets it.) -5. **The PDF pipeline is discriminative and partial.** Ported from docling's - standard pipeline, with substitutions: +5. **The PDF pipeline is discriminative and byte-measured.** Ported from + docling's standard pipeline: - **Layout** — RT-DETR (`docling-layout-heron`) exported to ONNX, run via `ort`. Same model family as docling. - **OCR** — PP-OCRv3 recognition (RapidOCR) via ONNX, *not* docling's default EasyOCR; different recognizer → different scanned text. - - **Tables** — *geometric* grid reconstruction (cluster cells into rows/cols), - **not TableFormer** (docling's autoregressive table-structure model). Table - structure is approximate; complex spans are not recovered. - - Output is therefore a **snapshot baseline**, never byte-for-byte with docling. + - **Tables** — **TableFormer** (image encoder + autoregressive OTSL structure + decoder + cell-bbox decoder, ported to ONNX), on a cv2-exact preprocessed + crop. Reproduces docling's padded GitHub tables — `2305-pg9` is cell-for-cell + exact; multi-row headers / spans on the dense papers still differ. + - **Text assembly** — a port of docling-parse's line sanitizer (`dp_lines.rs`): + 3-pass corner-distance contraction with gap-proportional space insertion, + `enforce_same_font`, ligature recomposition, loose-box geometry. Plus + docling's markdown escaping, wrap dehyphenation, paragraph-continuation + merging, and band-aware two-column reading order. Default; set + `DOCLING_LEGACY_LINES` for the old gap-heuristic join. + - Output is measured **byte-for-byte against live docling** (PDF_CONFORMANCE.md): + **4 / 14 exact**, the rest close. The remaining gaps are model-level + (TableFormer structure on complex tables, layout classification, RTL). 6. **Extracted image bytes are real but not byte-identical.** Cropped/embedded pixels are correct, but the PNG re-encoding differs from docling's, so the @@ -175,7 +191,10 @@ Explicitly **not done**, with the reason: - **VLM pipelines** (SmolDocling / remote VLM) and **enrichment models** (picture classification, formula understanding, code understanding). Model-bound; out of scope for the discriminative port. -- **TableFormer.** Replaced by geometric table reconstruction (§4.5). + +(**TableFormer is now done** — ported to ONNX and run on every table region; see +§5 and `PDF_CONFORMANCE.md`. Geometric reconstruction remains only as the fallback +when the TableFormer graphs aren't present.) - **XML DocLang / DocTags** input backend — no `.dclg` sources in the corpus to verify against, and not in the requested scope. - **Older patent schemas.** USPTO covers the modern `v4x` XML only; the diff --git a/PDF_CONFORMANCE.md b/PDF_CONFORMANCE.md new file mode 100644 index 00000000..dde82e90 --- /dev/null +++ b/PDF_CONFORMANCE.md @@ -0,0 +1,83 @@ +# PDF conformance + +How close the Rust PDF pipeline gets to docling's **default** Markdown, measured +byte-for-byte against the committed groundtruth (`tests/data/pdf/groundtruth/*.md`). +The groundtruth is regenerated from **live published docling**, so it agrees with +`scripts/conformance.sh pdf`. + +> Measure locally with `scripts/pdf_groundtruth.sh` (diffs the checked-in +> reference; no docling install needed) or `scripts/conformance.sh pdf` (installs +> docling and diffs against it). Diff = changed lines vs the groundtruth (one +> changed line counts as 2). + +## Current state + +**4 / 14 groundtruth PDFs are byte-for-byte exact.** + +| PDF | diff | dominant remaining blocker | +|---|---:|---| +| picture_classification | **exact** | — | +| code_and_formula | **exact** | — | +| multi_page | **exact** | — | +| 2305.03393v1-pg9 | **exact** | — (TableFormer table, cell-for-cell) | +| right_to_left_01 | 2 | RTL justified double-space | +| right_to_left_02 | 8 | RTL bidi spacing | +| amt_handbook_sample | 14 | justified spacing + figure captions | +| 2305.03393v1 | 40 | title-page reading order + author-ID run spacing | +| right_to_left_03 | 66 | RTL bidi | +| normal_4pages | 74 | reading order | +| table_mislabeled_as_picture | 110 | layout over-detects tables (survey rendered as tables) | +| 2206.01062 | 234 | TableFormer multi-row headers + title-page reading order | +| 2203.01017v2 | 247 | TableFormer structure + reading order | +| redp5110_sampled | 271 | TOC mis-classified as a picture; cover-page ordering | + +The close ones (`right_to_left_01/02`, `amt_handbook`) are 1–2 fixes from exact — +the realistic path to 50% (7/14). + +## How the pipeline works + +pdfium extracts the glyph layer and renders each page to a bitmap; an ONNX stack +(layout detection, TableFormer, PaddleOCR) interprets it; regions are assembled in +reading order into a `DoclingDocument`. Tables use **TableFormer** (image encoder ++ autoregressive OTSL structure decoder + cell-bbox decoder, ported and exported +to ONNX in `tableformer.rs`) on a cv2-exact preprocessed crop (`resample.rs`); the +structure + matched cell text reproduce docling's padded GitHub tables (2305-pg9 +is cell-for-cell exact). + +### Text reconstruction: docling-parse line sanitizer (ported) + +The byte-exact ceiling used to be the **text extractor** — pdfium differs from +docling's own `docling-parse` C++ parser at text-run boundaries. We closed it by +porting docling-parse's line sanitizer (`src/parse/page_item_sanitators/cells.h` +→ `dp_lines.rs`): a 3-pass corner-distance contraction (LTR → RTL → LTR-reverse) +with `merge_with` space insertion (one space when the gap exceeds +0.33×avg-char-width, plus literal space glyphs), `enforce_same_font`, ligature +recomposition (same-loose-box glyphs become one cell), and loose-box geometry +(uniform font ascent/descent), fed by pdfium glyph cells. It is the **default** +(set `DOCLING_LEGACY_LINES` to fall back to the old gap heuristic). This fixed +justified double-spacing, the space before `:`, lam-alef ordering, and fi/ffi +ligatures — and got `multi_page` to byte-exact. + +Other text/serializer fixes matching docling: markdown escaping (`_`→`\_`, then +HTML-escape `&`/`<`/`>`), U+2212→`-`, `@`-glue (`mAP @0.5`), wrap dehyphenation, +paragraph-continuation merging across column/page breaks, and band-aware +two-column reading order (full-width regions break the columns into bands). + +## Remaining blockers (model-level) + +These yield smaller or uncertain gains than the text-layer work already shipped. + +1. **TableFormer structure on complex tables.** Multi-row headers / spans on the + big papers (2206, 2203) differ from docling's OTSL prediction; one cell- + structure diff cascades through the padded columns into many row diffs + (2206's ~92 table-row diffs trace to ~4 structure diffs). +2. **Layout classification.** The layout ONNX classifies redp5110's + table-of-contents as a *picture* (docling renders it as a table) and + table_mislabeled's survey as *tables* (docling renders lists/text) — opposite + classifications, not a text problem. +3. **Complex title-page reading order.** Author-block / abstract interleaving on + the academic papers (band reading-order handles the full-width title; the + in-column author/abstract order is still off). +4. **RTL justified double-spaces.** pdfium emits zero-width space boxes, losing + the literal space that, with the inserted one, forms a justified double + (`right_to_left_01`). Needs space-box reconstruction that estimates width. diff --git a/README.md b/README.md index 28e9bdd2..75262858 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,40 @@ The comparison scripts install the latest published Python `docling` from PyPI into `.venv-compare` automatically on first run. See [`COMPARING.md`](./COMPARING.md). +## Performance + +`scripts/performance.sh` runs the **largest fixture of each supported type** through +both engines (published Python `docling` vs the Rust release binary) and reports +peak RSS, CPU utilization, and conversion time. Ratios below are docling ÷ +fleischwolf — bigger means Rust wins by more. + +| File | Size | Peak-memory ratio | CPU ratio | Warm-conversion speedup | +|---|---:|---:|---:|---:| +| `2203.01017v2.pdf` (PDF, 47 pp) | 6.9 MB | **2.2× less** | 1.3× | 1.2× | +| `docx_rich_tables_01.docx` (DOCX) | 3.1 MB | **41× less** | 2.7× | 21× | +| `wiki_duck.html` (HTML) | 240 KB | **57× less** | 3.2× | 46× | +| `elife-56337.nxml` (JATS XML) | 180 KB | **61× less** | 2.9× | 10× | +| `xlsx_04_inflated.xlsx` (XLSX) | 168 KB | **59× less** | 2.9× | 12× | +| `powerpoint_with_image.pptx` (PPTX) | 80 KB | **57× less** | 2.8× | 4.4× | +| `wiki.md` (Markdown) | 8 KB | **58× less** | 2.9× | 1.3× | +| `csv-comma.csv` (CSV) | 4 KB | **66× less** | 2.9× | 0.6× † | + +- **Peak memory** is where Rust wins decisively: a declarative conversion holds a + few MB versus docling's ~750 MB (it imports torch even for non-ML formats). The + PDF runs the full ML pipeline in both engines (torch vs ONNX), so the gap there + is 2.2× rather than 50×+, but Rust still peaks at 1.4 GB vs docling's 3.1 GB. +- **CPU**: docling spreads across 2.7–3.2 cores for declarative work that Rust does + on a single core (~100%); on the PDF both go multi-core (Rust 525% vs docling + 674%). +- **Warm-conversion speedup** isolates the parse/convert work — it times docling + *in-process* (excluding its ~3 s interpreter + import startup) against the Rust + whole-process figure. Rust wins on substantial inputs (HTML 46×, DOCX 21×); the + end-to-end figure, which re-pays docling's startup every invocation, is **377– + 1190× faster** for the declarative formats. +- † For trivial inputs (a 4 KB CSV) the conversion itself is microseconds, so Rust's + own process startup dominates its number while warm-Python excludes startup — the + warm metric understates Rust there. End-to-end, the CSV is **1190× faster** in Rust. + ## Layout | Crate | Role | Python analogue | diff --git a/crates/fleischwolf-core/src/document.rs b/crates/fleischwolf-core/src/document.rs index 03bd9895..25ea2be5 100644 --- a/crates/fleischwolf-core/src/document.rs +++ b/crates/fleischwolf-core/src/document.rs @@ -19,6 +19,11 @@ pub struct DoclingDocument { /// (the default) reproduces docling's legacy output byte-for-byte; `true` /// emits cleaner, more conformant Markdown. Set by `DocumentConverter`. pub strict_markdown: bool, + /// Emit tables in the compact `| a | b |` / `| - | - |` form rather than + /// docling-core's width-padded GitHub serializer. The PDF backend sets this + /// (its committed groundtruth corpus predates the padded serializer); DOCX/HTML + /// leave it `false` to match current published docling. + pub compact_tables: bool, } /// A single piece of document content. @@ -92,6 +97,7 @@ impl DoclingDocument { name: name.into(), nodes: Vec::new(), strict_markdown: false, + compact_tables: false, } } diff --git a/crates/fleischwolf-core/src/markdown.rs b/crates/fleischwolf-core/src/markdown.rs index 21024d34..35fa4b89 100644 --- a/crates/fleischwolf-core/src/markdown.rs +++ b/crates/fleischwolf-core/src/markdown.rs @@ -18,6 +18,8 @@ pub enum ImageMode { /// Serializer state threaded through the render walk. struct Ctx { strict: bool, + /// Emit compact `| a | b |` tables instead of the padded GitHub serializer. + compact_tables: bool, images: ImageMode, artifacts_dir: String, /// (relative path, bytes) for each referenced image — written by the caller. @@ -45,6 +47,7 @@ pub fn to_markdown_images( ) -> (String, Vec<(String, Vec)>) { let mut ctx = Ctx { strict, + compact_tables: doc.compact_tables, images, artifacts_dir: artifacts_dir.to_string(), artifacts: Vec::new(), @@ -61,16 +64,25 @@ pub fn to_markdown_images( (md, ctx.artifacts) } -/// In `strict` mode, undo the legacy `\_` underscore escaping the backends bake -/// into inline text. Legacy output keeps `\_` (byte-for-byte with docling, which -/// escapes underscores); strict prefers literal `_` for readability. Only inline -/// text nodes are escaped — code blocks and table cells are left alone. +/// In `strict` mode, rewrite inline text for readability rather than byte-for-byte +/// docling fidelity: undo the legacy `\_` underscore escaping, and tighten stray +/// spaces around punctuation (`[ 37 , 36 ]` → `[37, 36]`, `( x )` → `(x)`). This +/// cleans up both the PDF backend's glyph-split spacing and the space the legacy +/// emphasis serialization leaves before punctuation (`*a* ,` → `*a*,`). +/// Legacy/default output keeps docling's spacing untouched. Only inline text +/// nodes pass through here — code blocks and table cells are left alone. fn strict_text(text: &str, strict: bool) -> String { - if strict { - text.replace("\\_", "_") - } else { - text.to_string() + if !strict { + return text.to_string(); } + text.replace("\\_", "_") + .replace(" ,", ",") + .replace(" .", ".") + .replace(" ;", ";") + .replace(" )", ")") + .replace("( ", "(") + .replace(" ]", "]") + .replace("[ ", "[") } fn render(nodes: &[Node], blocks: &mut Vec, ctx: &mut Ctx) { @@ -163,7 +175,7 @@ fn render_one(node: &Node, blocks: &mut Vec, ctx: &mut Ctx) { blocks.push(format!("```{lang}\n{text}\n```")); } Node::Table(table) => { - let rendered = render_table(table); + let rendered = render_table(table, ctx.compact_tables); if !rendered.is_empty() { blocks.push(rendered); } @@ -214,15 +226,20 @@ fn ext_for(mimetype: &str) -> &str { } } -/// Render a table the way docling-core does: `tabulate(tablefmt="github")`. +/// Render a table. `compact` selects between two serializers: +/// +/// - **padded** (default) — docling-core's `tabulate(tablefmt="github")`: columns +/// are padded to a fixed width (header width + a minimum padding of 2, or the +/// widest data cell); numeric columns (every data cell parses as a number) are +/// right-aligned, others left-aligned; separators are plain dashes of +/// `width + 2`. Matches current published docling (DOCX/HTML conformance). +/// - **compact** — `| a | b |` cells with single-dash `| - | - |` separators, no +/// width padding. Matches the committed PDF groundtruth corpus, which predates +/// the padded serializer. /// -/// Each cell is first escaped (`\n` → space, `|` → `|`) so it can't break -/// the table. Columns are padded to a fixed width; the header contributes its -/// width plus a minimum padding of 2; numeric columns (every data cell parses -/// as a number) are right-aligned, others left-aligned; the separator is plain -/// dashes of `width + 2` (github tablefmt emits no alignment colons here). Row 0 -/// is the header. -fn render_table(table: &Table) -> String { +/// Each cell is first escaped (`\n` → space, `|` → `|`) so it can't break the +/// table. Row 0 is the header. +fn render_table(table: &Table, compact: bool) -> String { if table.rows.is_empty() { return String::new(); } @@ -251,6 +268,19 @@ fn render_table(table: &Table) -> String { }) .collect(); + if compact { + // Compact: cells joined by " | ", no padding, single-dash separators. + let render_row = |r: usize| -> String { format!("| {} |", grid[r].join(" | ")) }; + let mut lines = Vec::with_capacity(grid.len() + 1); + lines.push(render_row(0)); + let sep: Vec<&str> = (0..num_cols).map(|_| "-").collect(); + lines.push(format!("| {} |", sep.join(" | "))); + for r in 1..grid.len() { + lines.push(render_row(r)); + } + return lines.join("\n"); + } + // Display width (Unicode scalar count — good enough for now). let dw = |s: &str| s.chars().count(); let data_rows = 1..grid.len(); @@ -335,14 +365,26 @@ mod tests { } #[test] - fn renders_github_table() { + fn renders_compact_table() { let mut doc = DoclingDocument::new("t"); + // The compact form is opt-in (the PDF backend sets it); default output uses + // the padded GitHub serializer (covered by the regression fixtures). + doc.compact_tables = true; doc.push(Node::Table(Table { rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]], })); let md = doc.export_to_markdown(); - // Matches tabulate(tablefmt="github"): padded columns, numeric cells - // right-aligned, separator of width+2 dashes. + assert_eq!(md, "| a | b |\n| - | - |\n| 1 | 2 |\n"); + } + + #[test] + fn renders_padded_github_table_by_default() { + let mut doc = DoclingDocument::new("t"); + doc.push(Node::Table(Table { + rows: vec![vec!["a".into(), "b".into()], vec!["1".into(), "2".into()]], + })); + let md = doc.export_to_markdown(); + // Numeric data columns are right-aligned; columns padded to header+2. assert_eq!(md, "| a | b |\n|-----|-----|\n| 1 | 2 |\n"); } @@ -363,4 +405,14 @@ mod tests { // Strict prefers literal underscores (Rust-only readability mode). assert_eq!(doc.export_to_markdown_with(true), "# a_b\n\nx_y\n\n- i_j\n"); } + + #[test] + fn strict_tightens_punctuation_spacing_legacy_keeps_it() { + let mut doc = DoclingDocument::new("t"); + doc.add_paragraph("see [ 37 , 36 ] and ( x ) ."); + // Legacy keeps docling's spacing byte-for-byte. + assert_eq!(doc.export_to_markdown(), "see [ 37 , 36 ] and ( x ) .\n"); + // Strict tightens punctuation for readable Markdown. + assert_eq!(doc.export_to_markdown_with(true), "see [37, 36] and (x).\n"); + } } diff --git a/crates/fleischwolf-pdf/examples/dump_chars.rs b/crates/fleischwolf-pdf/examples/dump_chars.rs new file mode 100644 index 00000000..ecc81b41 --- /dev/null +++ b/crates/fleischwolf-pdf/examples/dump_chars.rs @@ -0,0 +1,24 @@ +//! Dump pdfium's raw char stream (codepoint + loose left/right) for a page, +//! optionally filtered to a substring window. Usage: +//! ... --example dump_chars -- file.pdf [needle] +fn main() { + let path = std::env::args() + .nth(1) + .expect("usage: dump_chars [needle]"); + let needle = std::env::args().nth(2); + let bytes = std::fs::read(&path).expect("read"); + let glyphs = fleischwolf_pdf::pdfium_backend::debug_glyphs(&bytes, 0); + let text: String = glyphs.iter().map(|(c, _, _)| *c).collect(); + let start = needle + .as_deref() + .and_then(|n| text.find(n)) + .map(|b| text[..b].chars().count()) + .unwrap_or(0); + println!("pdfium chars (ch / loose-left / loose-right / gap-to-prev):"); + let mut prev_r = f32::NAN; + for (ch, l, r) in glyphs.iter().skip(start).take(20) { + let gap = l - prev_r; + println!(" {:?} l={:7.2} r={:7.2} gap={:+.2}", ch, l, r, gap); + prev_r = *r; + } +} diff --git a/crates/fleischwolf-pdf/examples/dump_regions.rs b/crates/fleischwolf-pdf/examples/dump_regions.rs new file mode 100644 index 00000000..b9160054 --- /dev/null +++ b/crates/fleischwolf-pdf/examples/dump_regions.rs @@ -0,0 +1,54 @@ +//! Dump layout regions (label, bbox, text) for debugging reading order. +use fleischwolf_pdf::layout::LayoutModel; +use fleischwolf_pdf::PdfDocument; + +fn main() { + let path = std::env::args().nth(1).expect("pdf"); + let bytes = std::fs::read(&path).expect("read"); + let doc = PdfDocument::open(&bytes, None).expect("open"); + let mut layout = LayoutModel::load().expect("layout"); + for (pi, page) in doc.pages.iter().enumerate() { + let regions = layout + .predict(&page.image, page.width, page.height) + .expect("layout"); + for r in ®ions { + // crude text: cells whose center is inside the region + let txt: String = page + .cells + .iter() + .filter(|c| { + let (cx, cy) = ((c.l + c.r) / 2.0, (c.t + c.b) / 2.0); + cx >= r.l && cx <= r.r && cy >= r.t && cy <= r.b + }) + .map(|c| c.text.trim()) + .collect::>() + .join(" "); + let tail: String = txt + .chars() + .rev() + .take(40) + .collect::>() + .into_iter() + .rev() + .collect(); + println!( + "p{} {:>14} t={:6.1} b={:6.1} | …{}", + pi + 1, + r.label, + r.t, + r.b, + tail + ); + } + // raw line cells in extraction order (to inspect RTL ordering) + if std::env::var("DUMP_CELLS").is_ok() { + for (ci, c) in page.cells.iter().enumerate() { + let snip: String = c.text.chars().take(300).collect(); + println!( + " CELL[{ci}] t={:6.1} l={:6.1} r={:6.1} | {}", + c.t, c.l, c.r, snip + ); + } + } + } +} diff --git a/crates/fleischwolf-pdf/examples/dump_stages.rs b/crates/fleischwolf-pdf/examples/dump_stages.rs new file mode 100644 index 00000000..f12f8e70 --- /dev/null +++ b/crates/fleischwolf-pdf/examples/dump_stages.rs @@ -0,0 +1,20 @@ +//! Dump preprocessing stages for render-parity debugging against docling. +//! Usage: `... --example dump_stages -- file.pdf ` +use fleischwolf_pdf::PdfDocument; +use image::imageops; + +fn main() { + let path = std::env::args().nth(1).expect("pdf"); + let out = std::env::args().nth(2).expect("out_dir"); + let bytes = std::fs::read(&path).expect("read"); + let doc = PdfDocument::open(&bytes, None).expect("open"); + let page = &doc.pages[0]; + page.image.save(format!("{out}/my_page.png")).unwrap(); + println!("my_page: {}x{}", page.image.width(), page.image.height()); + + let sf = 1024.0 / page.image.height() as f32; + let pw = (page.image.width() as f32 * sf).round() as u32; + let p1024 = imageops::thumbnail(&page.image, pw, 1024); + p1024.save(format!("{out}/my_p1024.png")).unwrap(); + println!("my_p1024: {}x{}", p1024.width(), p1024.height()); +} diff --git a/crates/fleischwolf-pdf/examples/tf_otsl.rs b/crates/fleischwolf-pdf/examples/tf_otsl.rs new file mode 100644 index 00000000..b64c97aa --- /dev/null +++ b/crates/fleischwolf-pdf/examples/tf_otsl.rs @@ -0,0 +1,73 @@ +//! Verify TableFormer inference: run it on every table region of a PDF and print +//! the predicted OTSL structure. Usage: `... --example tf_otsl -- file.pdf` + +use fleischwolf_pdf::layout::LayoutModel; +use fleischwolf_pdf::tableformer::TableFormer; +use fleischwolf_pdf::PdfDocument; +use image::imageops; + +fn name(t: i64) -> &'static str { + match t { + 4 => "ecel", + 5 => "fcel", + 6 => "lcel", + 7 => "ucel", + 8 => "xcel", + 9 => "nl", + 10 => "ched", + 11 => "rhed", + 12 => "srow", + _ => "?", + } +} + +fn main() { + let path = std::env::args().nth(1).expect("usage: tf_otsl "); + let bytes = std::fs::read(&path).expect("read"); + let doc = PdfDocument::open(&bytes, None).expect("open"); + let mut layout = LayoutModel::load().expect("layout"); + let mut tf = TableFormer::load().expect("tableformer models missing"); + for (pi, page) in doc.pages.iter().enumerate() { + let regions = layout + .predict(&page.image, page.width, page.height) + .expect("layout"); + // docling resizes the whole page to 1024px height (cv2.INTER_AREA), then + // crops the table bbox out of *that*. Replicate exactly. + let sf = 1024.0 / page.image.height() as f32; + let pw1024 = (page.image.width() as f32 * sf) as u32; // docling: int(w*r) + let page1024 = fleischwolf_pdf::resample::inter_area(&page.image, pw1024, 1024); + for r in regions.iter().filter(|r| r.label == "table") { + // bbox (points) → 1024px-page coords: scale*sf = 1024/page_h_pt; + // docling rounds the crop edges. + let k = 1024.0 / page.height; + let x = (r.l * k).round().max(0.0) as u32; + let y = (r.t * k).round().max(0.0) as u32; + let x2 = (r.r * k).round() as u32; + let y2 = (r.b * k).round() as u32; + let (w, h) = (x2 - x, y2 - y); + let crop = imageops::crop_imm(&page1024, x, y, w, h).to_image(); + let cells = tf.predict_table_structure(&crop).expect("predict"); + println!( + "page {} table {}x{}px -> {} cells", + pi + 1, + w, + h, + cells.len() + ); + for c in &cells { + println!( + " r{} c{} {}x{} {} | cxcywh {:.4} {:.4} {:.4} {:.4}", + c.row, + c.col, + c.colspan, + c.rowspan, + name(c.tag), + c.cx, + c.cy, + c.w, + c.h + ); + } + } + } +} diff --git a/crates/fleischwolf-pdf/src/assemble.rs b/crates/fleischwolf-pdf/src/assemble.rs index 516f9482..9144852f 100644 --- a/crates/fleischwolf-pdf/src/assemble.rs +++ b/crates/fleischwolf-pdf/src/assemble.rs @@ -58,30 +58,172 @@ fn is_skipped(label: &str) -> bool { } /// Reading-order sort of regions, with two-column detection on the page. -fn order_regions(regions: &mut [Region], page_w: f32) { +fn order_regions(items: &mut [T], page_w: f32, reg: impl Fn(&T) -> &Region) { let cx = page_w / 2.0; let band = page_w * 0.08; - let crossing = regions + let crossing = items .iter() - .filter(|r| r.l < cx - band && r.r > cx + band) + .filter(|t| { + let r = reg(t); + r.l < cx - band && r.r > cx + band + }) .count(); - let two_col = !regions.is_empty() - && (crossing as f32) / (regions.len() as f32) < 0.25 - && regions.iter().any(|r| r.r <= cx) - && regions.iter().any(|r| r.l >= cx); + let two_col = !items.is_empty() + && (crossing as f32) / (items.len() as f32) < 0.25 + && items.iter().any(|t| reg(t).r <= cx) + && items.iter().any(|t| reg(t).l >= cx); if two_col { - regions.sort_by(|a, b| { - let ca = ((a.l + a.r) / 2.0) >= cx; - let cb = ((b.l + b.r) / 2.0) >= cx; - ca.cmp(&cb) + // Full-width regions (title, figures, wide tables spanning both columns) + // break the two-column flow into horizontal bands: within a band the left + // column reads fully then the right, and a full-width region reads after + // the band above it and before the band below. Band index = number of + // full-width regions above a region's top; column 1=left, 2=right, + // 3=full-width (so it sorts after that band's columns). + // Only a region spanning *most* of the page width is a band break (a + // title, a full-width figure/table) — a merely wide column region is not. + let full_band = page_w * 0.2; + let is_full = |r: &Region| r.l < cx - full_band && r.r > cx + full_band; + let full_tops: Vec = items + .iter() + .map(®) + .filter(|r| is_full(r)) + .map(|r| r.t) + .collect(); + let key = |r: &Region| -> (usize, u8) { + let bnd = full_tops.iter().filter(|&&ft| ft < r.t - 1.0).count(); + let col = if is_full(r) { + 3 + } else if (r.l + r.r) / 2.0 >= cx { + 2 + } else { + 1 + }; + (bnd, col) + }; + items.sort_by(|a, b| { + let (a, b) = (reg(a), reg(b)); + key(a) + .cmp(&key(b)) .then(a.t.total_cmp(&b.t)) .then(a.l.total_cmp(&b.l)) }); } else { - regions.sort_by(|a, b| a.t.total_cmp(&b.t).then(a.l.total_cmp(&b.l))); + items.sort_by(|a, b| { + let (a, b) = (reg(a), reg(b)); + a.t.total_cmp(&b.t).then(a.l.total_cmp(&b.l)) + }); } } +/// Clean a region's assembled text: undo soft-hyphen line wraps, map curly +/// quotes and the ellipsis to ASCII (matching docling), and collapse runs of +/// whitespace. pdfium emits the line-wrap hyphen as U+0002 in this corpus +/// (U+00AD elsewhere), so `word\u{2} continuation` is one hyphenated word — +/// drop the hyphen + the joining space and merge (`com\u{2} pact` → `compact`, +/// `end-to\u{2} end` → `end-toend`), exactly as docling does. +/// +/// Token spacing is otherwise left as the geometric join produced it. We do not +/// tighten punctuation spacing: docling preserves the PDF's own spaces (it keeps +/// `{ ahn }`, `Name 1 .`, `[ 9 ]`), and a geometric gap heuristic diverges from +/// it more than a plain single-space join does. +/// An ordered-list enumeration marker at the start of a list item: leading ASCII +/// digits followed by `.`, e.g. `1. Undo/Redo` → `(1, "Undo/Redo")`. Returns +/// `None` when the text doesn't start with `digits.`. +fn parse_ordered_marker(s: &str) -> Option<(u64, String)> { + let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect(); + if digits.is_empty() { + return None; + } + let rest = s[digits.len()..].strip_prefix('.')?; + let number = digits.parse().ok()?; + Some((number, rest.trim_start().to_string())) +} + +/// Escape markdown special characters the way docling-core's markdown serializer +/// does (`markdown.py` post_process): `_` → `\_`, then HTML-escape `&`, `<`, `>` +/// (quote=False, so quotes are left). Applied to prose (headings, list items, +/// paragraphs); code blocks, the formula placeholder, and table cells are left raw. +fn md_escape(text: &str) -> String { + text.replace('_', "\\_") + .replace('&', "&") + .replace('<', "<") + .replace('>', ">") +} + +fn clean_text(text: &str) -> String { + let replaced = text + .replace("\u{2} ", "") + .replace("\u{ad} ", "") + .replace(['\u{2}', '\u{ad}'], "") // any stray wrap hyphens not at a join + .replace(['\u{2018}', '\u{2019}'], "'") // ‘ ’ → ' + .replace(['\u{201c}', '\u{201d}'], "\"") // “ ” → " + .replace(['\u{2013}', '\u{2014}', '\u{2212}'], "-") // – — − → - + .replace('\u{2044}', "/") // ⁄ fraction slash → / + .replace('\u{2026}', "..."); // … → ... + let out = if crate::pdfium_backend::use_dp_lines() { + // The docling-parse sanitizer already placed the correct spacing (e.g. + // justified double spaces); preserve internal runs of spaces, only + // normalizing line breaks/tabs and trimming the ends. + replaced.replace(['\n', '\r', '\t'], " ").trim().to_string() + } else { + // Legacy: collapse all whitespace runs to single spaces. + replaced.split_whitespace().collect::>().join(" ") + }; + fix_arabic_lam_alef(&out) +} + +/// pdfium decomposes the Arabic lam-alef ligature (لا / لإ / لأ / لآ) into its +/// glyph constituents in *visual* order — `alef-variant, lam` — but docling keeps +/// logical order, `lam, alef-variant`. Swap a mid-word `alef-variant + lam` back +/// to `lam + alef-variant`. "Mid-word" (the previous char is an Arabic letter) +/// distinguishes the ligature from the definite article `ال` (word-initial +/// `alef + lam`), which must stay. No-op for non-Arabic text. +fn fix_arabic_lam_alef(s: &str) -> String { + let is_arabic_letter = |c: char| ('\u{0620}'..='\u{064A}').contains(&c); + let chars: Vec = s.chars().collect(); + if !chars.iter().any(|&c| is_arabic_letter(c)) { + return s.to_string(); // no-op for non-Arabic text + } + // Pass 1: swap mid-word `alef-variant + lam` → `lam + alef-variant`. Only the + // hamza/madda alef variants (إ أ آ) are safe: the definite article is always + // plain `ا + ل`, so plain `alef + lam` is ambiguous (a legitimate `فعالة` vs a + // reversed `لا` ligature look identical) — leaving plain alef alone avoids + // corrupting legitimate words. + let mut a: Vec = Vec::with_capacity(chars.len()); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + if matches!(c, '\u{0622}' | '\u{0623}' | '\u{0625}') + && chars.get(i + 1) == Some(&'\u{0644}') + && i > 0 + && is_arabic_letter(chars[i - 1]) + { + a.push('\u{0644}'); + a.push(c); + i += 2; + continue; + } + a.push(c); + i += 1; + } + // Pass 2: insert a space at Arabic↔Latin boundaries (bidi script switch) that + // pdfium runs together — docling separates the embedded Latin run (`وPython` + // → `و Python`). + let mut out: Vec = Vec::with_capacity(a.len()); + for (j, &c) in a.iter().enumerate() { + if j > 0 { + let p = a[j - 1]; + if (is_arabic_letter(p) && c.is_ascii_alphabetic()) + || (p.is_ascii_alphabetic() && is_arabic_letter(c)) + { + out.push(' '); + } + } + out.push(c); + } + out.into_iter().collect() +} + /// Cells assigned to a region (best container), in reading order, joined. fn region_text(region: &Region, cells: &[TextCell]) -> String { let mut inside: Vec<&TextCell> = cells @@ -92,22 +234,76 @@ fn region_text(region: &Region, cells: &[TextCell]) -> String { }) .collect(); // Quantize the top coordinate into ~line bands so cells on the same line - // sort left-to-right; this is a strict total order (a raw fuzzy comparator - // is not transitive and makes Rust's sort panic). + // sort in reading order; this is a strict total order (a raw fuzzy comparator + // is not transitive and makes Rust's sort panic). For a right-to-left + // (Arabic-majority) region, cells on a line read right→left, so sort the band + // by descending left edge. let band = inside .iter() .map(|c| (c.b - c.t).abs()) .fold(0.0f32, f32::max) .max(1.0); - inside.sort_by_key(|c| ((c.t / band).round() as i64, (c.l * 10.0) as i64)); - inside + let arabic = inside .iter() - .map(|c| c.text.trim()) - .collect::>() - .join(" ") - .split_whitespace() - .collect::>() - .join(" ") + .flat_map(|c| c.text.chars()) + .filter(|&c| ('\u{0600}'..='\u{06FF}').contains(&c)) + .count(); + let latin = inside + .iter() + .flat_map(|c| c.text.chars()) + .filter(|c| c.is_ascii_alphabetic()) + .count(); + let rtl = arabic > latin; + inside.sort_by_key(|c| { + let x = (c.l * 10.0) as i64; + ((c.t / band).round() as i64, if rtl { -x } else { x }) + }); + // Join cells in reading order. With the docling-parse sanitizer the cells are + // already correctly spaced words/lines, so adjacent cells join with a single + // space (docling joins its line cells with a space) — matching e.g. a bold + // label and its value, `LABEL` | `: value` → `LABEL : value`. The legacy + // reconstruction instead joins same-band cells with a space only across a real + // gap, because it can split a word into abutting segments (`الت`|`ي` → `التي`). + let dp = crate::pdfium_backend::use_dp_lines(); + let mut joined = String::new(); + let mut prev: Option<&&TextCell> = None; + for c in &inside { + let t = c.text.trim(); + // Skip whitespace-only cells (e.g. a justified line's trailing space glyph + // at a wrap): the join already inserts a separator, so an empty cell would + // double it (`all-metal construction`). + if t.is_empty() { + continue; + } + if let Some(p) = prev { + let same_band = ((p.t / band).round() as i64) == ((c.t / band).round() as i64); + let h = (c.b - c.t).abs().max((p.b - p.t).abs()).max(1.0); + let gap = if rtl { p.l - c.r } else { c.l - p.r }; + // Dehyphenate a wrapped word: a line ending in a hyphen/dash followed + // by a lowercase continuation joins without the dash or a space + // (`platforms—` + `reflects` → `platformsreflects`). The dash is still + // raw here (clean_text normalizes em/en dashes later), so match them all. + let ends_dash = matches!( + joined.chars().last(), + Some('-' | '\u{2010}' | '\u{2013}' | '\u{2014}') + ); + let dehyph = dp + && ends_dash + && joined + .chars() + .nth_back(1) + .is_some_and(|c| c.is_alphabetic()) + && t.chars().next().is_some_and(|c| c.is_lowercase()); + if dehyph { + joined.pop(); + } else if dp || !same_band || gap > h * 0.25 { + joined.push(' '); + } + } + joined.push_str(t); + prev = Some(c); + } + clean_text(&joined) } /// Reconstruct a table's grid geometrically from the text cells inside its @@ -171,12 +367,13 @@ fn reconstruct_table(region: &Region, cells: &[TextCell]) -> Vec> { let mut cols = vec![String::new(); ncols]; for c in row { let ci = col_of(c.l); - let t = c.text.trim(); + // Strip the wrap-hyphen control char so it never lands in a cell. + let t = c.text.trim().replace(['\u{2}', '\u{ad}'], ""); if cols[ci].is_empty() { - cols[ci] = t.to_string(); + cols[ci] = t; } else { cols[ci].push(' '); - cols[ci].push_str(t); + cols[ci].push_str(&t); } } grid.push(cols); @@ -211,20 +408,115 @@ fn crop_region(page: &PdfPage, region: &Region) -> Option { }) } +/// For each `picture` region, find the `caption` region closest below it (and +/// horizontally overlapping); docling pairs them and emits the caption first. +/// Each caption is claimed by at most one picture. +fn pair_captions(regions: &[Region]) -> Vec> { + let mut pairs = vec![None; regions.len()]; + let mut taken = vec![false; regions.len()]; + for (pi, p) in regions.iter().enumerate() { + if p.label != "picture" { + continue; + } + let mut best: Option<(usize, f32)> = None; + for (ci, c) in regions.iter().enumerate() { + if c.label != "caption" || taken[ci] { + continue; + } + let line_h = (c.b - c.t).abs().max(1.0); + let gap = c.t - p.b; // caption sits below the picture + let h_overlap = (p.r.min(c.r) - p.l.max(c.l)).max(0.0); + if gap > -line_h && gap < line_h * 3.0 && h_overlap > 0.0 { + let dist = gap.abs(); + if best.is_none_or(|(_, bd)| dist < bd) { + best = Some((ci, dist)); + } + } + } + if let Some((ci, _)) = best { + pairs[pi] = Some(ci); + taken[ci] = true; + } + } + pairs +} + +/// Pair each `code` region with the `caption` region just **above** it (a +/// `Listing N:` label). docling renders the code block first, then its caption, +/// so the caption is consumed from its own (earlier) reading-order slot and +/// re-emitted after the code. +fn pair_code_captions(regions: &[Region]) -> Vec> { + let mut pairs = vec![None; regions.len()]; + let mut taken = vec![false; regions.len()]; + for (pi, p) in regions.iter().enumerate() { + if p.label != "code" { + continue; + } + let mut best: Option<(usize, f32)> = None; + for (ci, c) in regions.iter().enumerate() { + if c.label != "caption" || taken[ci] { + continue; + } + let line_h = (c.b - c.t).abs().max(1.0); + let gap = p.t - c.b; // caption sits above the code + let h_overlap = (p.r.min(c.r) - p.l.max(c.l)).max(0.0); + if gap > -line_h && gap < line_h * 3.0 && h_overlap > 0.0 { + let dist = gap.abs(); + if best.is_none_or(|(_, bd)| dist < bd) { + best = Some((ci, dist)); + } + } + } + if let Some((ci, _)) = best { + pairs[pi] = Some(ci); + taken[ci] = true; + } + } + pairs +} + /// Assemble one page from its (already overlap-resolved) layout regions and /// text cells. -pub fn assemble_page(page: &PdfPage, mut regions: Vec, doc: &mut DoclingDocument) { - order_regions(&mut regions, page.width); +pub fn assemble_page( + page: &PdfPage, + regions: Vec, + table_rows: &[Option>>], + doc: &mut DoclingDocument, +) { + // Pair each region with its precomputed TableFormer grid (indexed by original + // order) and order by reading order together, so they stay aligned. + let mut items: Vec<(Region, Option>>)> = regions + .into_iter() + .enumerate() + .map(|(i, r)| (r, table_rows.get(i).cloned().flatten())) + .collect(); + order_regions(&mut items, page.width, |it| &it.0); + let table_rows: Vec>>> = items.iter().map(|(_, t)| t.clone()).collect(); + let regions: Vec = items.into_iter().map(|(r, _)| r).collect(); + // docling emits a figure's caption *before* the image marker. Pair each + // picture with the caption region nearest below it and consume that caption, + // so it isn't also emitted in its own (lower) reading-order position. + let caption_for = pair_captions(®ions); + let code_caption_for = pair_code_captions(®ions); + let mut consumed = vec![false; regions.len()]; + for ci in caption_for.iter().flatten() { + consumed[*ci] = true; + } + for ci in code_caption_for.iter().flatten() { + consumed[*ci] = true; + } - for region in ®ions { - if is_skipped(region.label) { + for (i, region) in regions.iter().enumerate() { + if is_skipped(region.label) || consumed[i] { continue; } if region.label == "picture" { - // Caption text, if any, is emitted by its own `caption` region. // The figure pixels are cropped from the page render for image export. + let caption = caption_for[i] + .map(|ci| region_text(®ions[ci], &page.cells)) + .filter(|t| !t.is_empty()); doc.push(Node::Picture { - caption: None, + caption, image: crop_region(page, region), }); continue; @@ -234,28 +526,142 @@ pub fn assemble_page(page: &PdfPage, mut regions: Vec, doc: &mut Docling continue; } match region.label { - "title" => doc.push(Node::Heading { level: 1, text }), - "section_header" => doc.push(Node::Heading { level: 2, text }), - "list_item" => doc.push(Node::ListItem { - ordered: false, - number: 0, - first_in_list: false, - text, - level: 0, + // docling renders both the document title and section headers as + // `##` (it never emits a top-level `#` for PDFs), so match that. + "title" | "section_header" => doc.push(Node::Heading { + level: 2, + text: md_escape(&text), }), - // Geometric grid reconstruction from the text layer (TableFormer - // would refine structure / spans). Falls back to a single cell. - "table" => { - let rows = reconstruct_table(region, &page.cells); - let rows = if rows.iter().any(|r| r.len() > 1) { - rows + // docling drops the rendered bullet glyph; the Markdown serializer + // adds its own `- ` marker. An item whose text opens with an `N.` + // enumeration marker is an ordered item (rendered `N. text`). + "list_item" => { + let stripped = text + .trim_start_matches(['•', '◦', '▪', '·', '*', '-']) + .trim_start() + .to_string(); + if let Some((number, rest)) = parse_ordered_marker(&stripped) { + doc.push(Node::ListItem { + ordered: true, + number, + first_in_list: false, + text: md_escape(&rest), + level: 0, + }); } else { - vec![vec![text]] - }; + doc.push(Node::ListItem { + ordered: false, + number: 0, + first_in_list: false, + text: md_escape(&stripped), + level: 0, + }); + } + } + // TableFormer structure (cells + spans, text matched from word cells) + // when available; otherwise geometric grid reconstruction; finally a + // single cell. + "table" => { + let rows = table_rows[i].clone().unwrap_or_else(|| { + let rows = reconstruct_table(region, &page.cells); + if rows.iter().any(|r| r.len() > 1) { + rows + } else { + vec![vec![text.clone()]] + } + }); doc.push(Node::Table(Table { rows })); } - // text, caption, footnote, formula, code → paragraph - _ => doc.push(Node::Paragraph { text }), + // docling does not decode formulas in the standard pipeline; it emits + // a placeholder comment rather than the (garbled) raw glyph text. + "formula" => doc.push(Node::Paragraph { + text: "".into(), + }), + // Code blocks: use the space-glyph-only grouping (monospace keeps its + // source spacing) and emit a fenced block. pdfium still inserts spaces + // around tight punctuation (`console .log`, `add (3 , 5)`); tighten + // them to match docling-parse's source spacing. + "code" => { + let code = region_text(region, &page.code_cells); + let code = if code.is_empty() { text } else { code }; + let code = code + .replace(" .", ".") + .replace(" ,", ",") + .replace(" ;", ";") + .replace(" )", ")") + .replace(" (", "("); + doc.push(Node::Code { + language: None, + text: code, + }); + // docling emits the `Listing N:` caption after the code block. + if let Some(ci) = code_caption_for[i] { + let cap = region_text(®ions[ci], &page.cells); + if !cap.is_empty() { + doc.push(Node::Paragraph { text: cap }); + } + } + } + // text, caption, footnote → paragraph + _ => doc.push(Node::Paragraph { + text: md_escape(&text), + }), } } } + +/// Merge paragraph fragments split across a column or page break. docling joins a +/// paragraph whose previous fragment ends mid-sentence (a letter, not sentence +/// punctuation) with a lowercase continuation: `…definition of` + `lists in…` → +/// `…definition of lists in…`. Only consecutive top-level paragraphs merge — a +/// heading/table/figure between them ends the paragraph. +pub(crate) fn merge_continuations(nodes: &mut Vec) { + let mut i = 0; + while i + 1 < nodes.len() { + let merged = match (&nodes[i], &nodes[i + 1]) { + (Node::Paragraph { text: a }, Node::Paragraph { text: b }) => { + // Open if the fragment ends mid-word (a letter) or with a wrap + // hyphen/dash — docling joins `vocab-` + `ulary` → `vocab- ulary`. + let a_open = a.trim_end().chars().next_back().is_some_and(|c| { + c.is_alphabetic() || matches!(c, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}') + }); + let b_cont = b + .trim_start() + .chars() + .next() + .is_some_and(|c| c.is_lowercase()); + (a_open && b_cont).then(|| format!("{} {}", a.trim_end(), b.trim_start())) + } + _ => None, + }; + if let Some(text) = merged { + nodes[i] = Node::Paragraph { text }; + nodes.remove(i + 1); + } else { + i += 1; + } + } +} + +#[cfg(test)] +mod tests { + use super::clean_text; + + #[test] + fn clean_text_dehyphenates_and_normalizes_typography() { + // U+0002 line-wrap hyphen + the join space → merged word (like docling). + assert_eq!(clean_text("com\u{2} pact"), "compact"); + assert_eq!(clean_text("end-to\u{2} end deep"), "end-toend deep"); + // A stray wrap hyphen (no following join) is dropped. + assert_eq!(clean_text("word\u{2}"), "word"); + // Typographic punctuation → ASCII. + assert_eq!( + clean_text("Graph\u{2019}s \u{201c}x\u{201d}"), + "Graph's \"x\"" + ); + assert_eq!(clean_text("a\u{2026}"), "a..."); + // The dp default (the docling-parse sanitizer) preserves internal spacing + // it placed deliberately; line breaks/tabs normalize to a space, ends trim. + assert_eq!(clean_text("a b\nc"), "a b c"); + } +} diff --git a/crates/fleischwolf-pdf/src/dp_lines.rs b/crates/fleischwolf-pdf/src/dp_lines.rs new file mode 100644 index 00000000..394e9028 --- /dev/null +++ b/crates/fleischwolf-pdf/src/dp_lines.rs @@ -0,0 +1,340 @@ +//! Port of docling-parse's line-cell sanitizer +//! (`src/parse/page_item_sanitators/cells.h` → `create_line_cells` / +//! `contract_cells_into_lines_v1`). It merges per-glyph char cells into line +//! cells via a 3-pass contraction — left-to-right, right-to-left, then +//! left-to-right with reverse — using corner-distance adjacency and inserting at +//! most one space per merge. This reproduces docling-parse's inter-word spacing +//! (justified double spaces, the space before a `:`, and RTL ordering) that the +//! ad-hoc `lines_from_glyphs` reconstruction can't. +//! +//! Geometry uses native PDF coordinates (y increases upward); each cell carries +//! its four transformed corners r0=bottom-left, r1=bottom-right, r2=top-right, +//! r3=top-left, exactly like `page_cell.h`. + +use crate::pdfium_backend::{Glyph, TextCell}; + +// config.h: the factors that actually bind for line cells. +const MERGE: f64 = 1.0; // line_space_width_factor_for_merge (adjacency gate) +const MERGE_WITH_SPACE: f64 = 0.33; // line_space_width_factor_for_merge_with_space +const H_TOL: f64 = 1.0; // horizontal_cell_tolerance (ligature eps_d1 relaxation) + +#[derive(Clone)] +struct Cell { + text: String, + rx0: f64, + ry0: f64, // bottom-left + rx1: f64, + ry1: f64, // bottom-right + rx2: f64, + ry2: f64, // top-right + rx3: f64, + ry3: f64, // top-left + ltr: bool, + active: bool, + lig_carry: bool, // last_merged_cell_was_ligature + font: u64, // hash of the PDF font name+flags (for enforce_same_font) +} + +impl Cell { + /// Length of the bottom edge (baseline advance) — `page_cell.h::length`. + fn length(&self) -> f64 { + ((self.rx1 - self.rx0).powi(2) + (self.ry1 - self.ry0).powi(2)).sqrt() + } + + /// Running mean glyph advance over the whole accumulated cell. + fn avg_char_width(&self) -> f64 { + let n = self.text.chars().count(); + if n > 0 { + self.length() / n as f64 + } else { + 0.0 + } + } + + /// Distance from this cell's bottom-right corner to `other`'s bottom-left. + fn gap(&self, other: &Cell) -> f64 { + ((self.rx1 - other.rx0).powi(2) + (self.ry1 - other.ry0).powi(2)).sqrt() + } + + /// `is_adjacent_to`: both the bottom-corner gap (`< eps0`) and the top-corner + /// gap (`< eps1`) must be small. The vertical component keeps different + /// baselines/lines from merging. + fn adjacent(&self, other: &Cell, eps0: f64, eps1: f64) -> bool { + let d0 = self.gap(other); + let d1 = ((self.rx2 - other.rx3).powi(2) + (self.ry2 - other.ry3).powi(2)).sqrt(); + d0 < eps0 && d1 < eps1 + } + + /// Punctuation/space cells are bidi-neutral bridges. + fn same_orientation(&self, other: &Cell) -> bool { + self.ltr == other.ltr || is_punct_or_space(&self.text) || is_punct_or_space(&other.text) + } + + /// `merge_with`: absorb `other` (which lies to this cell's right). Insert at + /// most one separator space when the gap exceeds `delta`. RTL prepends. + fn merge_with(&mut self, other: &Cell, delta: f64) { + // Signed horizontal gap, not the Euclidean corner distance used for + // adjacency: pdfium's loose boxes for overhanging glyphs (`f`, etc.) extend + // left and overlap the previous glyph, which a Euclidean distance reads as a + // positive gap and over-inserts a space (`Self` → `Sel f`, `specify` → + // `specif y`). An overlap is a negative gap → no space; a real (justified) + // gap is positive → space. + let h_gap = other.rx0 - self.rx1; + if !self.ltr || !other.ltr { + if delta < h_gap { + self.text.insert(0, ' '); + } + self.text = format!("{}{}", other.text, self.text); + self.ltr = false; + } else { + if delta < h_gap { + self.text.push(' '); + } + self.text.push_str(&other.text); + self.ltr = true; + } + // Extend the right edge to `other`. + self.rx1 = other.rx1; + self.ry1 = other.ry1; + self.rx2 = other.rx2; + self.ry2 = other.ry2; + } +} + +/// `applicable_for_merge`: both active, same font (ligatures bridge fonts), and +/// same reading orientation. +fn applicable(a: &Cell, b: &Cell) -> bool { + if !a.active || !b.active { + return false; + } + // font 0 = unknown/space (font-neutral); ligatures bridge fonts too. + if a.font != 0 + && b.font != 0 + && a.font != b.font + && !is_ligature(&a.text) + && !is_ligature(&b.text) + { + return false; + } + a.same_orientation(b) +} + +/// Left-to-right pass: `i` ascending accumulates cells to its right. +fn pass_ltr(cells: &mut [Cell], allow_reverse: bool) { + for i in 0..cells.len() { + if !cells[i].active { + continue; + } + let mut j = i + 1; + while j < cells.len() { + if !applicable(&cells[i], &cells[j]) { + break; + } + let i_lig = is_ligature(&cells[i].text) || cells[i].lig_carry; + let j_lig = is_ligature(&cells[j].text) || cells[j].lig_carry; + let d0 = cells[i].avg_char_width() * MERGE; + let d1 = cells[i].avg_char_width() * MERGE_WITH_SPACE; + let adj_d1 = d0 + if i_lig || j_lig { H_TOL } else { 0.0 }; + if cells[i].adjacent(&cells[j], d0, adj_d1) { + let other = cells[j].clone(); + cells[i].merge_with(&other, d1); + cells[i].lig_carry = is_ligature(&other.text); + cells[j].active = false; + j += 1; // i keeps absorbing the next cell to its right + } else if allow_reverse && cells[j].adjacent(&cells[i], d0, adj_d1) { + let other = cells[i].clone(); + cells[j].merge_with(&other, d1); + cells[j].lig_carry = is_ligature(&other.text); + cells[i].active = false; + break; // i is consumed + } else { + break; + } + } + } +} + +/// Right-to-left pass: `i` descending; its immediate left neighbour `i-1` +/// absorbs it (then the outer loop continues leftward through the absorber). +fn pass_rtl(cells: &mut [Cell]) { + let n = cells.len(); + for k in 0..n { + let i = n - 1 - k; + if !cells[i].active || i == 0 { + continue; + } + let j = i - 1; + if !applicable(&cells[i], &cells[j]) { + continue; + } + let i_lig = is_ligature(&cells[i].text) || cells[i].lig_carry; + let j_lig = is_ligature(&cells[j].text) || cells[j].lig_carry; + let d0 = cells[i].avg_char_width() * MERGE; + let d1 = cells[i].avg_char_width() * MERGE_WITH_SPACE; + let adj_d1 = d0 + if i_lig || j_lig { H_TOL } else { 0.0 }; + if cells[j].adjacent(&cells[i], d0, adj_d1) { + let other = cells[i].clone(); + cells[j].merge_with(&other, d1); + cells[j].lig_carry = is_ligature(&other.text); + cells[i].active = false; + } + } +} + +fn contract(cells: &mut Vec) { + pass_ltr(cells, false); + cells.retain(|c| c.active); + pass_rtl(cells); + cells.retain(|c| c.active); + pass_ltr(cells, true); + cells.retain(|c| c.active); +} + +/// Build line cells from a page's glyph stream via the docling-parse contraction. +pub(crate) fn line_cells(glyphs: &[Glyph], page_h: f32) -> Vec { + let mut cells: Vec = Vec::new(); + for g in glyphs { + // Use the loose box (uniform font ascent/descent + advance) so adjacent + // glyphs share a top edge, matching docling-parse's `compute_rect`. + if !g.ll.is_finite() { + continue; + } + // Drop *degenerate* space glyphs (zero-width loose box): pdfium's generated + // spaces get a zero-width box at the wrong baseline that breaks the + // corner-distance adjacency. Without them the inter-word gap drives + // `merge_with`'s space insertion. Spaces with a real width are kept (they + // carry justified double-space information). + if g.ch == ' ' && (g.lr - g.ll).abs() < 0.5 { + continue; + } + // Recompose a ligature: pdfium decomposes one font glyph (Latin fi/ffi, + // Arabic lam-alef) into several chars at the *same* loose box. Append them + // into one cell so the contraction never inserts a space inside it. + if let Some(last) = cells.last_mut() { + if (last.rx0 - g.ll as f64).abs() < 0.5 && (last.rx1 - g.lr as f64).abs() < 0.5 { + last.text.push(g.ch); + last.ltr = !is_right_to_left(&last.text); + continue; + } + } + let text = g.ch.to_string(); + let ltr = !is_right_to_left(&text); + cells.push(Cell { + text, + rx0: g.ll as f64, + ry0: g.lb as f64, + rx1: g.lr as f64, + ry1: g.lb as f64, + rx2: g.lr as f64, + ry2: g.lt as f64, + rx3: g.ll as f64, + ry3: g.lt as f64, + ltr, + active: true, + lig_carry: false, + font: g.font, + }); + } + contract(&mut cells); + cells + .into_iter() + .map(|c| { + let l = c.rx0.min(c.rx1).min(c.rx2).min(c.rx3) as f32; + let r = c.rx0.max(c.rx1).max(c.rx2).max(c.rx3) as f32; + let top = c.ry0.max(c.ry1).max(c.ry2).max(c.ry3) as f32; + let bot = c.ry0.min(c.ry1).min(c.ry2).min(c.ry3) as f32; + TextCell { + text: c.text, + l, + t: page_h - top, + r, + b: page_h - bot, + } + }) + .collect() +} + +fn is_rtl_char(c: char) -> bool { + let ch = c as u32; + (0x0600..=0x06FF).contains(&ch) + || (0x0750..=0x077F).contains(&ch) + || (0x08A0..=0x08FF).contains(&ch) + || (0xFB50..=0xFDFF).contains(&ch) + || (0xFE70..=0xFEFF).contains(&ch) + || (0x0590..=0x05FF).contains(&ch) + || (0xFB1D..=0xFB4F).contains(&ch) + || (0x0700..=0x074F).contains(&ch) + || (0x0780..=0x07BF).contains(&ch) + || (0x07C0..=0x07FF).contains(&ch) +} + +/// All codepoints are RTL-script (matches `string.h::is_right_to_left`). +fn is_right_to_left(s: &str) -> bool { + !s.is_empty() && s.chars().all(is_rtl_char) +} + +/// A single-codepoint punctuation/space cell (matches `string.h`). +fn is_punct_or_space(s: &str) -> bool { + let mut chars = s.chars(); + let (Some(c), None) = (chars.next(), chars.next()) else { + return false; + }; + if matches!( + c, + ' ' | '\t' + | '\n' + | '\r' + | '\u{0c}' + | '\u{0b}' + | '.' + | ',' + | ';' + | ':' + | '!' + | '?' + | '(' + | ')' + | '[' + | ']' + | '{' + | '}' + | '\'' + | '"' + | '`' + | '\u{2018}' + | '\u{2019}' + | '\u{201c}' + | '\u{201d}' + | '-' + | '\u{2013}' + | '\u{2014}' + | '_' + | '/' + | '\\' + | '|' + | '@' + | '#' + | '%' + | '&' + | '*' + | '+' + | '=' + | '<' + | '>' + ) { + return true; + } + let ch = c as u32; + (0x2000..=0x206F).contains(&ch) + || (0x3000..=0x303F).contains(&ch) + || (0xFE50..=0xFE6F).contains(&ch) + || (0xFF00..=0xFF0F).contains(&ch) + || (0xFF1A..=0xFF1F).contains(&ch) + || (0xFF3B..=0xFF5E).contains(&ch) +} + +/// Ligature glyph or its ASCII spelling (matches `string.h::is_ligature`). +fn is_ligature(s: &str) -> bool { + matches!(s, "ff" | "fi" | "fl" | "ffi" | "ffl") + || s.chars().any(|c| (0xFB00..=0xFB06).contains(&(c as u32))) +} diff --git a/crates/fleischwolf-pdf/src/lib.rs b/crates/fleischwolf-pdf/src/lib.rs index 845a5a6b..233e4e1a 100644 --- a/crates/fleischwolf-pdf/src/lib.rs +++ b/crates/fleischwolf-pdf/src/lib.rs @@ -10,10 +10,13 @@ //! table-structure and OCR ONNX stages land behind [`Pipeline`] next. mod assemble; +mod dp_lines; pub mod layout; mod mets; mod ocr; -mod pdfium_backend; +pub mod pdfium_backend; +pub mod resample; +pub mod tableformer; use std::fmt; @@ -71,14 +74,20 @@ pub(crate) fn intra_threads() -> usize { pub struct Pipeline { layout: layout::LayoutModel, ocr: Option, + /// TableFormer structure model; `None` when its ONNX graphs aren't present + /// (the assembler then falls back to geometric table reconstruction). + tables: Option, } impl Pipeline { - /// Load the layout model (the only always-required model). + /// Load the layout model (the only always-required model). TableFormer loads + /// if its exported graphs are present, else table regions use the geometric + /// fallback. pub fn new() -> Result { Ok(Self { layout: layout::LayoutModel::load().map_err(PdfError::Layout)?, ocr: None, + tables: tableformer::TableFormer::load(), }) } @@ -99,6 +108,7 @@ impl Pipeline { pdfium_backend::for_each_page(bytes, password, |n, _total, mut page| { self.process_one_page(n, &mut page, &mut doc) })?; + assemble::merge_continuations(&mut doc.nodes); Ok(doc) } @@ -116,6 +126,8 @@ impl Pipeline { height: h as f32, scale: 1.0, cells: Vec::new(), + code_cells: Vec::new(), + word_cells: Vec::new(), image, }; self.process_pages(vec![page], name) @@ -147,7 +159,21 @@ impl Pipeline { .map_err(|e| PdfError::Ocr(format!("page {}: {e}", n + 1)))?; page.cells = cells; } - assemble::assemble_page(page, regions, doc); + // TableFormer structure per table region (else geometric fallback). + let mut table_rows: Vec>>> = vec![None; regions.len()]; + if let Some(tf) = self.tables.as_mut() { + for (i, r) in regions.iter().enumerate() { + if r.label == "table" { + table_rows[i] = tf.predict_table_rows( + &page.image, + page.height, + [r.l, r.t, r.r, r.b], + &page.word_cells, + ); + } + } + } + assemble::assemble_page(page, regions, &table_rows, doc); Ok(()) } @@ -162,6 +188,7 @@ impl Pipeline { for (n, page) in pages.iter_mut().enumerate() { self.process_one_page(n, page, &mut doc)?; } + assemble::merge_continuations(&mut doc.nodes); Ok(doc) } } diff --git a/crates/fleischwolf-pdf/src/mets.rs b/crates/fleischwolf-pdf/src/mets.rs index f4e1d336..8d4c603e 100644 --- a/crates/fleischwolf-pdf/src/mets.rs +++ b/crates/fleischwolf-pdf/src/mets.rs @@ -69,6 +69,8 @@ pub fn convert_mets_gbs(bytes: &[u8], name: &str) -> Result, + /// Same text grouped for code regions: split only at pdfium space glyphs, so + /// monospace runs keep their source spacing instead of the prose heuristic's. + pub code_cells: Vec, + /// Per-word cells (one per word, not joined into lines) for TableFormer cell + /// matching. + pub word_cells: Vec, pub image: RgbImage, } @@ -41,6 +55,13 @@ pub struct PdfDocument { /// Bind to the pdfium dynamic library. Honors `PDFIUM_DYNAMIC_LIB_PATH` (a /// directory or file), else the directory of the current exe, else the system /// library — mirroring how a deployment ships `libpdfium` alongside the binary. +/// Whether to use the docling-parse line sanitizer ([`crate::dp_lines`]) for prose +/// reconstruction — the default. Set `DOCLING_LEGACY_LINES` to fall back to the +/// older gap-heuristic `lines_from_glyphs`. +pub(crate) fn use_dp_lines() -> bool { + std::env::var("DOCLING_LEGACY_LINES").is_err() +} + fn bind() -> Result { if let Ok(path) = std::env::var("PDFIUM_DYNAMIC_LIB_PATH") { let name = Pdfium::pdfium_platform_library_name_at_path(&path); @@ -61,10 +82,11 @@ impl PdfDocument { /// once. For large documents prefer [`for_each_page`], which streams. pub fn open(bytes: &[u8], password: Option<&str>) -> Result { let pdfium = bind()?; + let ffi = FfiText::load(pdfium.bindings(), bytes, password); let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?; let mut pages = Vec::new(); - for page in doc.pages().iter() { - pages.push(extract_page(&page)?); + for (i, page) in doc.pages().iter().enumerate() { + pages.push(extract_page(&page, &ffi, i as i32)?); } Ok(PdfDocument { pages }) } @@ -82,51 +104,555 @@ where F: FnMut(usize, usize, PdfPage) -> Result<(), E>, { let pdfium = bind()?; + let ffi = FfiText::load(pdfium.bindings(), bytes, password); let doc = pdfium.load_pdf_from_byte_slice(bytes, password)?; let pages = doc.pages(); let total = pages.len() as usize; for (i, page) in pages.iter().enumerate() { - let extracted = extract_page(&page)?; + let extracted = extract_page(&page, &ffi, i as i32)?; f(i, total, extracted)?; } Ok(()) } -fn extract_page(page: &pdfium_render::prelude::PdfPage<'_>) -> Result { +fn extract_page( + page: &pdfium_render::prelude::PdfPage<'_>, + ffi: &FfiText<'_>, + index: i32, +) -> Result { let width = page.width().value; let height = page.height().value; - let text = page.text()?; - let mut cells = Vec::new(); - for segment in text.segments().iter() { - let rect = segment.bounds(); - let s = segment.text(); - if s.trim().is_empty() { - continue; - } - // Flip Y to a top-left origin. - cells.push(TextCell { - text: s, - l: rect.left().value, - t: height - rect.top().value, - r: rect.right().value, - b: height - rect.bottom().value, - }); + let (mut cells, code_cells, word_cells) = ffi.page_cells(index, height); + if cells.is_empty() { + cells = segment_cells(&page.text()?, height); } - let tw = (width * RENDER_SCALE).round().max(1.0) as i32; - let th = (height * RENDER_SCALE).round().max(1.0) as i32; + // docling renders at 1.5× the target scale and downsamples "to make it + // sharper" (pypdfium2 → PIL BICUBIC). Replicate exactly: the TableFormer + // model is pixel-sensitive, so the page bitmap must match byte-for-byte. + // `CatmullRom` is the same a=-0.5 cubic kernel as PIL's BICUBIC. + const SUPERSAMPLE: f32 = 1.5; + let tw = (width * RENDER_SCALE * SUPERSAMPLE).round().max(1.0) as i32; + let th = (height * RENDER_SCALE * SUPERSAMPLE).round().max(1.0) as i32; let cfg = PdfRenderConfig::new() .set_target_width(tw) .set_target_height(th); let bitmap = page.render_with_config(&cfg)?; - let image = bitmap.as_image().into_rgb8(); + let big = bitmap.as_image().into_rgb8(); + let dw = (width * RENDER_SCALE).round().max(1.0) as u32; + let dh = (height * RENDER_SCALE).round().max(1.0) as u32; + let image = image::imageops::resize(&big, dw, dh, image::imageops::FilterType::CatmullRom); Ok(PdfPage { width, height, scale: RENDER_SCALE, cells, + code_cells, + word_cells, image, }) } + +/// Fallback line cells from pdfium-render's style segments (one cell per +/// segment). Used only when the raw-FFI text page can't be loaded. +fn segment_cells(text: &PdfPageText, page_h: f32) -> Vec { + text.segments() + .iter() + .filter_map(|seg| { + let s = seg.text(); + if s.trim().is_empty() { + return None; + } + let r = seg.bounds(); + Some(TextCell { + text: s, + l: r.left().value, + t: page_h - r.top().value, + r: r.right().value, + b: page_h - r.bottom().value, + }) + }) + .collect() +} + +/// A second, raw-FFI handle on the same PDF used to drive the character loop +/// (`FPDFText_GetUnicode`/`GetCharBox`) that pdfium-render's safe API doesn't +/// expose. Closes the document on drop. +struct FfiText<'a> { + bindings: &'a dyn PdfiumLibraryBindings, + doc: FPDF_DOCUMENT, +} + +/// One glyph: codepoint + native (y-up) box edges. `l/b/r/t` is pdfium's *tight* +/// ink box (used by the legacy `lines_from_glyphs`); `ll/lb/lr/lt` is the *loose* +/// box (font ascent/descent + advance — uniform per font/size), which the +/// docling-parse-style sanitizer needs so adjacent glyphs share a top edge. +pub(crate) struct Glyph { + pub(crate) ch: char, + pub(crate) l: f32, + pub(crate) b: f32, + pub(crate) r: f32, + pub(crate) t: f32, + pub(crate) ll: f32, + pub(crate) lb: f32, + pub(crate) lr: f32, + pub(crate) lt: f32, + /// Hash of the PDF font name + flags (0 when not fetched). The sanitizer uses + /// it for docling-parse's `enforce_same_font` (keeps a bold label and regular + /// value as separate line cells, e.g. `LABEL : value`). + pub(crate) font: u64, +} + +impl<'a> FfiText<'a> { + fn load(bindings: &'a dyn PdfiumLibraryBindings, bytes: &[u8], password: Option<&str>) -> Self { + let doc = bindings.FPDF_LoadMemDocument(bytes, password); + FfiText { bindings, doc } + } + + /// Reconstruct line cells for page `index` (zero-based) via the + /// chars→words→lines grouping. Returns `(prose_cells, code_cells)` — the same + /// glyphs grouped two ways (gap-heuristic for prose, space-glyph-only for + /// code). Both empty on any failure (caller falls back). + fn page_cells(&self, index: i32, page_h: f32) -> (Vec, Vec, Vec) { + let empty = || (Vec::new(), Vec::new(), Vec::new()); + if self.doc.is_null() { + return empty(); + } + let b = self.bindings; + let page = b.FPDF_LoadPage(self.doc, index); + if page.is_null() { + return empty(); + } + let tp = b.FPDFText_LoadPage(page); + let out = if tp.is_null() { + empty() + } else { + let dp = use_dp_lines(); + let g = glyphs(b, tp, dp); + b.FPDFText_ClosePage(tp); + // Prose line cells: the docling-parse-style sanitizer (behind a flag + // while it's validated) or the legacy gap-heuristic reconstruction. + let prose = if dp { + crate::dp_lines::line_cells(&g, page_h) + } else { + lines_from_glyphs(&g, page_h, false) + }; + ( + prose, + lines_from_glyphs(&g, page_h, true), + words_from_glyphs(&g, page_h), + ) + }; + b.FPDF_ClosePage(page); + out + } +} + +impl Drop for FfiText<'_> { + fn drop(&mut self) { + if !self.doc.is_null() { + self.bindings.FPDF_CloseDocument(self.doc); + } + } +} + +/// Read every glyph (codepoint + native box) from the text page, in document +/// order. A space glyph is kept as a word-boundary marker (NaN box, char `' '`); +/// pdfium emits these on most lines and they pin word splits exactly. Hard line +/// breaks are dropped (line structure comes from geometry); the gap heuristic in +/// [`lines_from_glyphs`] is the fallback for the lines pdfium leaves space-less. +/// Debug helper: the raw pdfium glyph stream (codepoint + native bottom-left +/// box) for a page, in pdfium's character order. For comparing against +/// docling-parse's char cells. +pub fn debug_glyphs(bytes: &[u8], index: i32) -> Vec<(char, f32, f32)> { + let Ok(pdfium) = bind() else { + return Vec::new(); + }; + let ffi = FfiText::load(pdfium.bindings(), bytes, None); + if ffi.doc.is_null() { + return Vec::new(); + } + let b = ffi.bindings; + let page = b.FPDF_LoadPage(ffi.doc, index); + if page.is_null() { + return Vec::new(); + } + let tp = b.FPDFText_LoadPage(page); + let mut out = Vec::new(); + if !tp.is_null() { + for g in glyphs(b, tp, true) { + out.push((g.ch, g.ll, g.lr)); + } + b.FPDFText_ClosePage(tp); + } + b.FPDF_ClosePage(page); + out +} + +/// Hash a glyph's PDF font name + flags, for `enforce_same_font`. 0 if unavailable. +fn font_hash(b: &dyn PdfiumLibraryBindings, tp: FPDF_TEXTPAGE, i: i32) -> u64 { + use std::hash::{Hash, Hasher}; + let mut flags: std::os::raw::c_int = 0; + let len = b.FPDFText_GetFontInfo(tp, i, std::ptr::null_mut(), 0, &mut flags); + if len == 0 { + return 0; + } + let mut buf = vec![0u8; len as usize]; + b.FPDFText_GetFontInfo( + tp, + i, + buf.as_mut_ptr() as *mut std::os::raw::c_void, + len, + &mut flags, + ); + let mut h = std::collections::hash_map::DefaultHasher::new(); + buf.hash(&mut h); + flags.hash(&mut h); + h.finish() +} + +fn glyphs(b: &dyn PdfiumLibraryBindings, tp: FPDF_TEXTPAGE, fetch_font: bool) -> Vec { + let n = b.FPDFText_CountChars(tp); + let mut out = Vec::with_capacity(n.max(0) as usize); + for i in 0..n { + let ch = match char::from_u32(b.FPDFText_GetUnicode(tp, i)) { + Some(c) => c, + None => continue, + }; + if ch == '\r' || ch == '\n' { + continue; + } + // Spaces are font-neutral (0): pdfium's generated spaces carry a default + // font that would otherwise block every word↔space merge under + // enforce_same_font; docling-parse's spaces inherit the run's font. + let font = if fetch_font && !ch.is_whitespace() { + font_hash(b, tp, i) + } else { + 0 + }; + let (mut l, mut r, mut bot, mut top) = (0f64, 0f64, 0f64, 0f64); + let has_box = b.FPDFText_GetCharBox(tp, i, &mut l, &mut r, &mut bot, &mut top) != 0; + // Loose box: font ascent/descent + glyph advance, uniform per font/size. + let mut lr = FS_RECTF { + left: 0.0, + top: 0.0, + right: 0.0, + bottom: 0.0, + }; + let (ll, lb, lrt, ltop) = if b.FPDFText_GetLooseCharBox(tp, i, &mut lr) != 0 { + (lr.left, lr.bottom, lr.right, lr.top) + } else if has_box { + (l as f32, bot as f32, r as f32, top as f32) + } else { + (f32::NAN, 0.0, 0.0, 0.0) + }; + if ch.is_whitespace() { + // Keep the space *with its box* (the docling-parse-style line sanitizer + // needs literal space glyphs); NaN `l` if pdfium reports no box (the + // legacy `lines_from_glyphs` ignores the box and only flags a space). + out.push(Glyph { + ch: ' ', + l: if has_box { l as f32 } else { f32::NAN }, + b: if has_box { bot as f32 } else { 0.0 }, + r: if has_box { r as f32 } else { 0.0 }, + t: if has_box { top as f32 } else { 0.0 }, + ll, + lb, + lr: lrt, + lt: ltop, + font, + }); + continue; + } + if !has_box { + continue; + } + out.push(Glyph { + ch, + l: l as f32, + b: bot as f32, + r: r as f32, + t: top as f32, + ll, + lb, + lr: lrt, + lt: ltop, + font, + }); + } + // pdfium splits the Arabic lam-alef ligature into two chars at the *same* x + // (it's one glyph) in visual order — `alef-variant, lam`. docling-parse and + // logical order are `lam, alef-variant`. Detect the ligature by the shared x + // and swap. The shared-x test reliably distinguishes a true ligature from a + // genuine `alef + lam` sequence (the article `ال`, or `فعالة`), whose two + // glyphs sit at different x and must NOT be reordered. + for i in 0..out.len().saturating_sub(1) { + let same_x = out[i].l.is_finite() + && out[i + 1].l.is_finite() + && (out[i].l - out[i + 1].l).abs() < 1.0; + if same_x + && matches!(out[i].ch, '\u{0622}' | '\u{0623}' | '\u{0625}' | '\u{0627}') + && out[i + 1].ch == '\u{0644}' + { + out.swap(i, i + 1); + } + } + // Reconstruct degenerate (zero-width) loose space boxes by spanning the gap to + // the next glyph on the same line, so the sanitizer keeps them as word + // separators rather than dropping them (which would merge `Information systems` + // → `Informationsystems`). pdfium gives generated spaces a zero-width box at a + // wrong baseline; a wrap (different baseline) or a touching gap is left alone. + for i in 0..out.len() { + if out[i].ch != ' ' || (out[i].lr - out[i].ll).abs() >= 0.5 { + continue; + } + let prev = out[..i] + .iter() + .rev() + .find(|g| g.ch != ' ' && g.ll.is_finite()) + .map(|g| (g.lr, g.lb, g.lt)); + let next = out[i + 1..] + .iter() + .find(|g| g.ch != ' ' && g.ll.is_finite()) + .map(|g| (g.ll, g.lb)); + if let (Some((plr, plb, plt)), Some((nll, nlb))) = (prev, next) { + let line_h = (plt - plb).abs().max(1.0); + if (plb - nlb).abs() < line_h * 0.5 && nll > plr + 0.5 { + out[i].ll = plr; + out[i].lr = nll; + out[i].lb = plb; + out[i].lt = plt; + } + } + } + out +} + +/// Group glyphs (document order) into words then lines, the way docling-parse +/// does: a new **word** starts where the horizontal gap to the previous glyph +/// exceeds ~0.2 × the font height (a real space is ~0.3 × height; letter +/// tracking is smaller, so titles don't shatter); a new **line** starts where +/// the baseline drops by ~half the font height (a superscript rises without +/// dropping, so it stays on its line). Coordinates are flipped to top-left. +/// `code` mode splits words **only** at pdfium's own space glyphs and never glues +/// punctuation — monospace code has wide inter-glyph advances that the prose +/// gap heuristic mistakes for spaces (`f un c t i o n`), but pdfium emits a real +/// space glyph at every true gap, so honoring just those reproduces the source +/// spacing (`function add(a, b)`). +fn lines_from_glyphs(gs: &[Glyph], page_h: f32, code: bool) -> Vec { + let mut cells: Vec = Vec::new(); + let mut words: Vec = Vec::new(); // words on the current line + let mut word = String::new(); + // current line bounding box, native + let (mut ll, mut lb, mut lr, mut lt) = ( + f32::INFINITY, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NEG_INFINITY, + ); + // Tallest glyph seen on the current line: the word-gap threshold is relative + // to it, so a small-font run on the line (a superscript citation) isn't split + // at its tight digit gaps, while a big display title isn't split at its wider + // letter tracking. A real inter-word space is ~0.3× the font height. + let mut line_h: f32 = 0.0; + let mut prev: Option<&Glyph> = None; + // A space glyph between non-space glyphs pins a word split the gap heuristic + // can miss (tight justified spacing); it carries no geometry. + let mut pending_space = false; + + for g in gs { + if g.ch == ' ' { + pending_space = true; + continue; + } + let h = (g.t - g.b).abs().max(1.0); + let (mut new_word, mut new_line) = (false, false); + if let Some(p) = prev { + // A new line drops the baseline *and* resets x leftward; requiring the + // x-reset avoids a descending comma/semicolon faking a line break. A + // *large* drop (≥1.5× the line height — a skipped line, e.g. a centered + // page-number footer below a short last word) is always a new line, + // even without the x-reset. + // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset + // rightward (the new line begins at the far right). A large drop + // (≥1.5× line height) is a new line regardless of x. + let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) { + g.l > p.r + } else { + g.l < p.r + }; + new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5); + // Don't split before closing punctuation, after opening punctuation, or + // after a period that runs into a digit/lowercase letter — docling + // keeps `engines,` / `[37` / `i.e.` / `98.5` together even across a + // space or gap. + let glued = is_close_punct(g.ch) + || is_open_punct(p.ch) + || (p.ch.is_ascii_digit() && g.ch.is_ascii_digit()) + || (p.ch == '.' + && !pending_space + && (g.ch.is_ascii_digit() || g.ch.is_ascii_lowercase())); + let word_gap = line_h.max(h) * 0.25; + new_word = if code { + new_line || pending_space + } else if is_arabic(g.ch) || is_arabic(p.ch) { + // RTL runs right-to-left, so the inter-word gap is `p.l - g.r`. A + // real word space has a gap; pdfium also emits spurious zero-gap + // space glyphs inside words (`التي`), so require the gap rather + // than trusting a bare space glyph. + new_line || (p.l - g.r > word_gap && !glued) + } else { + new_line || ((pending_space || g.l - p.r > word_gap) && !glued) + }; + } + pending_space = false; + if new_line { + push_word(&mut word, &mut words); + push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells); + (ll, lb, lr, lt) = ( + f32::INFINITY, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NEG_INFINITY, + ); + line_h = 0.0; + } else if new_word { + push_word(&mut word, &mut words); + } + word.push(g.ch); + ll = ll.min(g.l); + lb = lb.min(g.b); + lr = lr.max(g.r); + lt = lt.max(g.t); + line_h = line_h.max(h); + prev = Some(g); + } + push_word(&mut word, &mut words); + push_line(&mut words, (ll, lb, lr, lt), page_h, &mut cells); + cells +} + +/// Per-word cells (each word's text + top-left bbox), using the same word/line +/// splitting as [`lines_from_glyphs`] but emitting one cell per word instead of +/// joining into lines — the TableFormer matcher places individual words into +/// grid cells (a table line spans many cells, so line cells can't be matched). +fn words_from_glyphs(gs: &[Glyph], page_h: f32) -> Vec { + let mut cells = Vec::new(); + let mut word = String::new(); + let inf = ( + f32::INFINITY, + f32::INFINITY, + f32::NEG_INFINITY, + f32::NEG_INFINITY, + ); + let (mut wl, mut wb, mut wr, mut wt) = inf; + let mut line_h: f32 = 0.0; + let mut prev: Option<&Glyph> = None; + let mut pending_space = false; + for g in gs { + if g.ch == ' ' { + pending_space = true; + continue; + } + let h = (g.t - g.b).abs().max(1.0); + let mut new_line = false; + let mut new_word = false; + if let Some(p) = prev { + // LTR wraps reset x leftward (`g.l < p.r`); RTL (Arabic) wraps reset + // rightward (the new line begins at the far right). A large drop + // (≥1.5× line height) is a new line regardless of x. + let x_reset = if is_arabic(g.ch) || is_arabic(p.ch) { + g.l > p.r + } else { + g.l < p.r + }; + new_line = (p.b - g.b > h * 0.5 && x_reset) || (p.b - g.b > line_h.max(h) * 1.5); + // No digit-digit glue here (unlike the prose grouping): table cells in + // adjacent columns are numeric and a column gap must still split them + // (`0.965` `0.934`, not `0.9650.934`). Intra-number digits have no gap + // so they stay together regardless. + let glued = is_close_punct(g.ch) + || is_open_punct(p.ch) + || (p.ch == '.' + && !pending_space + && (g.ch.is_ascii_digit() || g.ch.is_ascii_lowercase())); + let word_gap = line_h.max(h) * 0.25; + new_word = new_line || ((pending_space || g.l - p.r > word_gap) && !glued); + } + pending_space = false; + if new_word && !word.is_empty() { + cells.push(TextCell { + text: std::mem::take(&mut word), + l: wl, + t: page_h - wt, + r: wr, + b: page_h - wb, + }); + (wl, wb, wr, wt) = inf; + } + if new_line { + line_h = 0.0; + } + word.push(g.ch); + wl = wl.min(g.l); + wb = wb.min(g.b); + wr = wr.max(g.r); + wt = wt.max(g.t); + line_h = line_h.max(h); + prev = Some(g); + } + if !word.is_empty() { + cells.push(TextCell { + text: word, + l: wl, + t: page_h - wt, + r: wr, + b: page_h - wb, + }); + } + cells +} + +fn is_arabic(c: char) -> bool { + ('\u{0600}'..='\u{06FF}').contains(&c) +} + +fn is_close_punct(c: char) -> bool { + matches!( + c, + ',' | '.' | ';' | '!' | '?' | ')' | ']' | '}' | '%' | '\'' | '\u{2019}' | '\u{2018}' + ) +} + +fn is_open_punct(c: char) -> bool { + // `@` glues to what follows (`mAP @0.5`, `bpf@zurich`, `@decorator`). + matches!(c, '(' | '[' | '{' | '@') +} + +fn push_word(word: &mut String, words: &mut Vec) { + if !word.is_empty() { + words.push(std::mem::take(word)); + } +} + +fn push_line( + words: &mut Vec, + bbox: (f32, f32, f32, f32), + page_h: f32, + cells: &mut Vec, +) { + if words.is_empty() { + return; + } + let text = std::mem::take(words).join(" "); + let (l, b, r, t) = bbox; + cells.push(TextCell { + text, + l, + t: page_h - t, + r, + b: page_h - b, + }); +} diff --git a/crates/fleischwolf-pdf/src/resample.rs b/crates/fleischwolf-pdf/src/resample.rs new file mode 100644 index 00000000..a88c849b --- /dev/null +++ b/crates/fleischwolf-pdf/src/resample.rs @@ -0,0 +1,70 @@ +//! Pixel-exact reimplementations of the OpenCV resize kernels docling uses for +//! TableFormer preprocessing, so the model sees byte-identical input. Verified +//! against cv2 on docling's own bitmaps (INTER_AREA max diff 1/255, INTER_LINEAR +//! < 1e-4 in float). + +use image::{Rgb, RgbImage}; + +/// Per-output-pixel source spans + overlap weights for area resampling. +fn area_weights(src: usize, dst: usize, scale: f64) -> Vec> { + (0..dst) + .map(|d| { + let f1 = d as f64 * scale; + let f2 = (d + 1) as f64 * scale; + let s1 = f1.floor() as usize; + let s2 = (f2.ceil() as usize).min(src); + (s1..s2) + .map(|si| { + let w = (((si + 1) as f64).min(f2) - (si as f64).max(f1)) / scale; + (si, w) + }) + .collect() + }) + .collect() +} + +/// `cv2.resize(..., interpolation=INTER_AREA)` for shrinking — area-weighted +/// averaging, separable (horizontal then vertical), f64 accumulation. +pub fn inter_area(src: &RgbImage, dw: u32, dh: u32) -> RgbImage { + let (sw, sh) = (src.width() as usize, src.height() as usize); + let (dwu, dhu) = (dw as usize, dh as usize); + let hw = area_weights(sw, dwu, sw as f64 / dw as f64); + let vw = area_weights(sh, dhu, sh as f64 / dh as f64); + + let mut tmp = vec![[0f64; 3]; sh * dwu]; // (sh × dw) + for y in 0..sh { + let row = y * dwu; + for (dx, ws) in hw.iter().enumerate() { + let mut acc = [0f64; 3]; + for &(si, w) in ws { + let p = src.get_pixel(si as u32, y as u32); + acc[0] += p[0] as f64 * w; + acc[1] += p[1] as f64 * w; + acc[2] += p[2] as f64 * w; + } + tmp[row + dx] = acc; + } + } + let mut out = RgbImage::new(dw, dh); + for (dy, ws) in vw.iter().enumerate() { + for dx in 0..dwu { + let mut acc = [0f64; 3]; + for &(si, w) in ws { + let t = tmp[si * dwu + dx]; + acc[0] += t[0] * w; + acc[1] += t[1] * w; + acc[2] += t[2] * w; + } + out.put_pixel( + dx as u32, + dy as u32, + Rgb([round_u8(acc[0]), round_u8(acc[1]), round_u8(acc[2])]), + ); + } + } + out +} + +fn round_u8(v: f64) -> u8 { + v.round().clamp(0.0, 255.0) as u8 +} diff --git a/crates/fleischwolf-pdf/src/tableformer.rs b/crates/fleischwolf-pdf/src/tableformer.rs new file mode 100644 index 00000000..26c3560b --- /dev/null +++ b/crates/fleischwolf-pdf/src/tableformer.rs @@ -0,0 +1,460 @@ +//! TableFormer: table-structure recovery via docling-ibm-models, exported to +//! ONNX by `scripts/export_tableformer.py`. The image encoder + tag-transformer +//! encoder run once to a memory tensor; the decoder is then stepped +//! autoregressively to emit an OTSL structure-token sequence (the same model +//! docling runs). See PDF_CONFORMANCE.md. + +use crate::pdfium_backend::TextCell; +use image::RgbImage; +use ort::session::Session; +use ort::value::Tensor; + +const SIDE: u32 = 448; +// Verbatim from docling's tm_config.json image_normalization (more digits than +// f32 holds; kept exact for provenance). +#[allow(clippy::excessive_precision)] +const MEAN: [f32; 3] = [0.94247851, 0.94254675, 0.94292611]; +#[allow(clippy::excessive_precision)] +const STD: [f32; 3] = [0.17910956, 0.17940403, 0.17931663]; +const MAX_STEPS: usize = 1024; + +/// OTSL structure tokens (TableModel04_rs wordmap indices). +pub const START: i64 = 2; +pub const END: i64 = 3; +pub const ECEL: i64 = 4; // empty cell +pub const FCEL: i64 = 5; // full (content) cell +pub const LCEL: i64 = 6; // left-looking: extends the cell to its left (colspan) +pub const UCEL: i64 = 7; // up-looking: extends the cell above (rowspan) +pub const XCEL: i64 = 8; // cross: spans both ways +pub const NL: i64 = 9; // new row +pub const CHED: i64 = 10; // column header +pub const RHED: i64 = 11; // row header +pub const SROW: i64 = 12; // section row + +/// A predicted table cell: an OTSL grid position (with spans) + its box in the +/// 448 image normalized cxcywh, and the OTSL tag. +#[derive(Debug, Clone)] +pub struct TableCell { + pub row: usize, + pub col: usize, + pub colspan: usize, + pub rowspan: usize, + pub tag: i64, + pub cx: f32, + pub cy: f32, + pub w: f32, + pub h: f32, +} + +pub struct TableFormer { + encoder: Session, + decoder: Session, + bbox: Session, +} + +impl TableFormer { + /// Load the exported encoder/decoder/bbox ONNX graphs (env overrides, else + /// `models/tableformer/{encoder,decoder,bbox}.onnx`). Returns `None` if any is + /// absent, so the pipeline falls back to geometric reconstruction. + pub fn load() -> Option { + let enc = std::env::var("DOCLING_TABLEFORMER_ENCODER") + .unwrap_or_else(|_| "models/tableformer/encoder.onnx".to_string()); + let dec = std::env::var("DOCLING_TABLEFORMER_DECODER") + .unwrap_or_else(|_| "models/tableformer/decoder.onnx".to_string()); + let bbx = std::env::var("DOCLING_TABLEFORMER_BBOX") + .unwrap_or_else(|_| "models/tableformer/bbox.onnx".to_string()); + if [&enc, &dec, &bbx] + .iter() + .any(|p| !std::path::Path::new(p).exists()) + { + return None; + } + let build = |path: &str| -> Result { + Session::builder() + .map_err(|e| e.to_string())? + .with_intra_threads(crate::intra_threads()) + .map_err(|e| e.to_string())? + .commit_from_file(path) + .map_err(|e| format!("tableformer load {path}: {e}")) + }; + match (build(&enc), build(&dec), build(&bbx)) { + (Ok(encoder), Ok(decoder), Ok(bbox)) => Some(Self { + encoder, + decoder, + bbox, + }), + _ => None, + } + } + + /// Predict the OTSL structure-token sequence for a table-region image. + pub fn predict_otsl(&mut self, img: &RgbImage) -> Result, String> { + let input = preprocess(img)?; + let enc_out = self + .encoder + .run(ort::inputs!["image" => input]) + .map_err(|e| format!("tableformer: encode: {e}"))?; + let (mshape, mem) = enc_out["memory"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: memory: {e}"))?; + let mshape: Vec = mshape.iter().map(|&x| x as usize).collect(); + let mem: Vec = mem.to_vec(); + + // Autoregressive decode: the decoder graph re-applies the layers to the + // whole prefix under a causal mask (statelessly reproducing the model's + // per-layer cache), so we just feed the growing token list back in. The + // two structure corrections mirror docling's `predict` exactly — note its + // `line_num` is never incremented, so `xcel→lcel` applies on every row. + let mut tags: Vec = vec![START]; + let mut out: Vec = Vec::new(); + let mut prev_ucel = false; + while out.len() < MAX_STEPS { + let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.clone())) + .map_err(|e| format!("tableformer: tags: {e}"))?; + let mem_t = Tensor::from_array((mshape.clone(), mem.clone())) + .map_err(|e| format!("tableformer: mem: {e}"))?; + let dout = self + .decoder + .run(ort::inputs!["tags" => tags_t, "memory" => mem_t]) + .map_err(|e| format!("tableformer: decode: {e}"))?; + let (_, logits) = dout["logits"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: logits: {e}"))?; + let mut tag = argmax(logits) as i64; + if tag == XCEL { + tag = LCEL; + } + if prev_ucel && tag == LCEL { + tag = FCEL; + } + if tag == END { + break; + } + out.push(tag); + tags.push(tag); + prev_ucel = tag == UCEL; + } + Ok(out) + } + + /// Full structure prediction: OTSL grid cells with per-cell boxes (in the 448 + /// image, normalized cxcywh). Collects per-cell decoder hidden states using + /// docling's exact bbox bookkeeping (skip-after-row-break, first-lcel of a + /// horizontal span), runs the bbox decoder, merges span boxes, then lays the + /// cells onto the OTSL grid with row/col spans. + pub fn predict_table_structure(&mut self, img: &RgbImage) -> Result, String> { + let input = preprocess(img)?; + let enc_out = self + .encoder + .run(ort::inputs!["image" => input]) + .map_err(|e| format!("tableformer: encode: {e}"))?; + let (mshape, mem) = enc_out["memory"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: memory: {e}"))?; + let mshape: Vec = mshape.iter().map(|&x| x as usize).collect(); + let mem: Vec = mem.to_vec(); + let (eshape, eo) = enc_out["enc_out"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: enc_out: {e}"))?; + let eshape: Vec = eshape.iter().map(|&x| x as usize).collect(); + let eo: Vec = eo.to_vec(); + + let mut tags: Vec = vec![START]; + let mut otsl: Vec = Vec::new(); + let mut hiddens: Vec = Vec::new(); // flattened [n, 512] + let mut n = 0usize; + let mut prev_ucel = false; + let mut skip = true; // first tag after is skipped + let mut first_lcel = true; + let mut bbox_ind = 0usize; + let mut cur_bbox_ind = 0usize; + let mut merge: std::collections::HashMap = std::collections::HashMap::new(); + while otsl.len() < MAX_STEPS { + let tags_t = Tensor::from_array(([tags.len(), 1usize], tags.clone())) + .map_err(|e| format!("tableformer: tags: {e}"))?; + let mem_t = Tensor::from_array((mshape.clone(), mem.clone())) + .map_err(|e| format!("tableformer: mem: {e}"))?; + let dout = self + .decoder + .run(ort::inputs!["tags" => tags_t, "memory" => mem_t]) + .map_err(|e| format!("tableformer: decode: {e}"))?; + let (_, logits) = dout["logits"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: logits: {e}"))?; + let mut tag = argmax(logits) as i64; + if tag == XCEL { + tag = LCEL; + } + if prev_ucel && tag == LCEL { + tag = FCEL; + } + if tag == END { + break; + } + let (_, hidden) = dout["hidden"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: hidden: {e}"))?; + // docling's tag_H_buf / bboxes_to_merge bookkeeping. + if !skip && matches!(tag, FCEL | ECEL | CHED | RHED | SROW | NL | UCEL) { + hiddens.extend_from_slice(hidden); + n += 1; + if !first_lcel { + merge.insert(cur_bbox_ind, bbox_ind as i64); + } + bbox_ind += 1; + } + if tag != LCEL { + first_lcel = true; + } else if first_lcel { + hiddens.extend_from_slice(hidden); + n += 1; + first_lcel = false; + cur_bbox_ind = bbox_ind; + merge.insert(cur_bbox_ind, -1); + bbox_ind += 1; + } + skip = matches!(tag, NL | UCEL | XCEL); + prev_ucel = tag == UCEL; + otsl.push(tag); + tags.push(tag); + } + if n == 0 { + return Ok(Vec::new()); + } + let tag_h = Tensor::from_array(([n, 512usize], hiddens)) + .map_err(|e| format!("tableformer: tag_h: {e}"))?; + let eo_t = Tensor::from_array((eshape, eo)).map_err(|e| format!("tableformer: eo: {e}"))?; + let bout = self + .bbox + .run(ort::inputs!["enc_out" => eo_t, "tag_h" => tag_h]) + .map_err(|e| format!("tableformer: bbox: {e}"))?; + let (_, raw) = bout["boxes"] + .try_extract_tensor::() + .map_err(|e| format!("tableformer: boxes: {e}"))?; + let boxes: Vec<[f32; 4]> = raw + .chunks_exact(4) + .map(|c| [c[0], c[1], c[2], c[3]]) + .collect(); + let merged = merge_spans(&boxes, &merge); + Ok(build_table_cells(&otsl, &merged)) + } + + /// Predict a table region's Markdown grid: crop the region (docling's + /// page→1024px box-average then bbox crop), run the structure model, map each + /// cell box back to page points, match the page's word cells into cells by + /// intersection-over-word-area, and expand spans into a dense `rows × cols` + /// grid. `region` is `(l, t, r, b)` in page points (top-left). Returns `None` + /// if no structure is predicted. + pub fn predict_table_rows( + &mut self, + page_image: &RgbImage, + page_h: f32, + region: [f32; 4], + words: &[TextCell], + ) -> Option>> { + // page → 1024px height (cv2.INTER_AREA), then crop the table bbox. + let sf = 1024.0 / page_image.height() as f32; + let pw = (page_image.width() as f32 * sf) as u32; + let page1024 = crate::resample::inter_area(page_image, pw, 1024); + let k = 1024.0 / page_h; + let x = (region[0] * k).round().max(0.0) as u32; + let y = (region[1] * k).round().max(0.0) as u32; + let x2 = ((region[2] * k).round() as u32).min(page1024.width()); + let y2 = ((region[3] * k).round() as u32).min(page1024.height()); + if x2 <= x || y2 <= y { + return None; + } + let crop = image::imageops::crop_imm(&page1024, x, y, x2 - x, y2 - y).to_image(); + let cells = self.predict_table_structure(&crop).ok()?; + if cells.is_empty() { + return None; + } + let (rw, rh) = (region[2] - region[0], region[3] - region[1]); + + // Cell boxes in page points (top-left), aligned with `cells`. + let boxes: Vec<[f32; 4]> = cells + .iter() + .map(|c| { + [ + region[0] + (c.cx - c.w / 2.0) * rw, + region[1] + (c.cy - c.h / 2.0) * rh, + region[0] + (c.cx + c.w / 2.0) * rw, + region[1] + (c.cy + c.h / 2.0) * rh, + ] + }) + .collect(); + + // Assign each word to the cell it overlaps most (intersection / word area). + let mut cell_words: Vec> = vec![Vec::new(); cells.len()]; + for (wi, w) in words.iter().enumerate() { + let wa = ((w.r - w.l) * (w.b - w.t)).max(1.0); + let mut best: Option<(f32, usize)> = None; + for (ci, b) in boxes.iter().enumerate() { + let ix = (w.r.min(b[2]) - w.l.max(b[0])).max(0.0); + let iy = (w.b.min(b[3]) - w.t.max(b[1])).max(0.0); + let io = ix * iy / wa; + if io > 0.0 && best.is_none_or(|(bo, _)| io > bo) { + best = Some((io, ci)); + } + } + if let Some((_, ci)) = best { + cell_words[ci].push(wi); + } + } + + let num_rows = cells.iter().map(|c| c.row + c.rowspan).max().unwrap_or(0); + let num_cols = cells.iter().map(|c| c.col + c.colspan).max().unwrap_or(0); + if num_rows == 0 || num_cols == 0 { + return None; + } + let mut grid = vec![vec![String::new(); num_cols]; num_rows]; + for (ci, c) in cells.iter().enumerate() { + // Keep words in text-stream order (the order they were collected = + // their word index), matching docling's cell text assembly — geometric + // re-sorting scrambles wrapped cells (`Inference time (secs)`). + let wis = std::mem::take(&mut cell_words[ci]); + let text = wis + .iter() + .map(|&i| words[i].text.trim()) + .collect::>() + .join(" "); + // Spanned cells repeat their text across the covered grid positions. + for row in grid.iter_mut().skip(c.row).take(c.rowspan) { + for cell in row.iter_mut().skip(c.col).take(c.colspan) { + *cell = text.clone(); + } + } + } + Some(grid) + } +} + +/// docling's preprocessing: bilinear (cv2.INTER_LINEAR) resize the crop to 448², +/// normalize `(x/255 − mean)/std`, laid out as (C, W, H) — docling transposes +/// (2,1,0), so width is the major spatial axis. The page→1024px box-average +/// (cv2.INTER_AREA) is the caller's job. +fn preprocess(img: &RgbImage) -> Result, String> { + let nn = (SIDE * SIDE) as usize; + let side = SIDE as usize; + let (sw, sh) = (img.width() as i32, img.height() as i32); + let sxr = sw as f32 / SIDE as f32; + let syr = sh as f32 / SIDE as f32; + let mut data = vec![0f32; 3 * nn]; + for h in 0..side { + let fy = (h as f32 + 0.5) * syr - 0.5; + let wy = fy - fy.floor(); + let y0c = (fy.floor() as i32).clamp(0, sh - 1) as u32; + let y1c = (fy.floor() as i32 + 1).clamp(0, sh - 1) as u32; + for w in 0..side { + let fx = (w as f32 + 0.5) * sxr - 0.5; + let wx = fx - fx.floor(); + let x0c = (fx.floor() as i32).clamp(0, sw - 1) as u32; + let x1c = (fx.floor() as i32 + 1).clamp(0, sw - 1) as u32; + let p00 = img.get_pixel(x0c, y0c); + let p01 = img.get_pixel(x1c, y0c); + let p10 = img.get_pixel(x0c, y1c); + let p11 = img.get_pixel(x1c, y1c); + let idx = w * side + h; // (C, W, H): c*n + w*H + h + for c in 0..3 { + let top = p00[c] as f32 * (1.0 - wx) + p01[c] as f32 * wx; + let bot = p10[c] as f32 * (1.0 - wx) + p11[c] as f32 * wx; + let v = top * (1.0 - wy) + bot * wy; + data[c * nn + idx] = (v / 255.0 - MEAN[c]) / STD[c]; + } + } + } + Tensor::from_array(([1usize, 3, side, side], data)) + .map_err(|e| format!("tableformer: input: {e}")) +} + +/// docling's `mergebboxes` (cxcywh): the union box of a horizontal span's first +/// and last cell. +fn mergebboxes(b1: [f32; 4], b2: [f32; 4]) -> [f32; 4] { + let new_w = (b2[0] + b2[2] / 2.0) - (b1[0] - b1[2] / 2.0); + let new_h = (b2[1] + b2[3] / 2.0) - (b1[1] - b1[3] / 2.0); + let new_left = b1[0] - b1[2] / 2.0; + let new_top = (b2[1] - b2[3] / 2.0).min(b1[1] - b1[3] / 2.0); + [new_left + new_w / 2.0, new_top + new_h / 2.0, new_w, new_h] +} + +/// Apply docling's span merges: each merge key combines its box with the partner +/// (`-1` → the last box); partners are dropped. +fn merge_spans(boxes: &[[f32; 4]], merge: &std::collections::HashMap) -> Vec<[f32; 4]> { + let skip: std::collections::HashSet = merge + .values() + .filter(|&&v| v >= 0) + .map(|&v| v as usize) + .collect(); + let mut out = Vec::new(); + for (i, &b) in boxes.iter().enumerate() { + if let Some(&j) = merge.get(&i) { + let partner = if j < 0 { boxes.len() - 1 } else { j as usize }; + out.push(mergebboxes(b, boxes[partner.min(boxes.len() - 1)])); + } else if !skip.contains(&i) { + out.push(b); + } + } + out +} + +const CELL_TAGS: [i64; 6] = [FCEL, ECEL, XCEL, CHED, RHED, SROW]; + +/// Lay the OTSL tag stream onto a grid (docling's `_build_table_cells`, OTSL +/// mode): cell tags create cells at (row, col); `lcel`/`ucel`/`xcel` are spans +/// (counted toward the column index but not cells). Colspan/rowspan are read off +/// the grid (consecutive `lcel`/`ucel` to the right/below). `boxes` are indexed +/// by cell order and aligned with the cells. +fn build_table_cells(otsl: &[i64], boxes: &[[f32; 4]]) -> Vec { + // 2D grid of tags (rows split on NL) for span lookups. + let mut grid: Vec> = vec![Vec::new()]; + for &t in otsl { + if t == NL { + grid.push(Vec::new()); + } else { + grid.last_mut().unwrap().push(t); + } + } + let mut cells = Vec::new(); + let mut cell_id = 0usize; + for (r, row) in grid.iter().enumerate() { + for (c, &tag) in row.iter().enumerate() { + if !CELL_TAGS.contains(&tag) { + continue; + } + let mut colspan = 1; + while c + colspan < row.len() && matches!(row[c + colspan], LCEL | XCEL) { + colspan += 1; + } + let mut rowspan = 1; + while r + rowspan < grid.len() + && grid[r + rowspan] + .get(c) + .is_some_and(|&t| matches!(t, UCEL | XCEL)) + { + rowspan += 1; + } + let b = boxes.get(cell_id).copied().unwrap_or([0.0; 4]); + cells.push(TableCell { + row: r, + col: c, + colspan, + rowspan, + tag, + cx: b[0], + cy: b[1], + w: b[2], + h: b[3], + }); + cell_id += 1; + } + } + cells +} + +fn argmax(v: &[f32]) -> usize { + v.iter() + .enumerate() + .max_by(|a, b| a.1.total_cmp(b.1)) + .map(|(i, _)| i) + .unwrap_or(0) +} diff --git a/crates/fleischwolf/tests/data/docx/expected/docx_checkboxes.docx.strict.md b/crates/fleischwolf/tests/data/docx/expected/docx_checkboxes.docx.strict.md index 1b8b2196..fc903c1a 100644 --- a/crates/fleischwolf/tests/data/docx/expected/docx_checkboxes.docx.strict.md +++ b/crates/fleischwolf/tests/data/docx/expected/docx_checkboxes.docx.strict.md @@ -14,4 +14,4 @@ Tasks before release: - [x] Implementation -- [ ] Documentation of the task with a very long text that goes beyond the maximum length of a single line. +- [] Documentation of the task with a very long text that goes beyond the maximum length of a single line. diff --git a/crates/fleischwolf/tests/data/docx/expected/docx_rich_cells.docx.strict.md b/crates/fleischwolf/tests/data/docx/expected/docx_rich_cells.docx.strict.md index ea17fcd1..41456194 100644 --- a/crates/fleischwolf/tests/data/docx/expected/docx_rich_cells.docx.strict.md +++ b/crates/fleischwolf/tests/data/docx/expected/docx_rich_cells.docx.strict.md @@ -15,7 +15,7 @@ Before table | Simple cell upper left | Simple cell with **bold** and *italic* text | | A B C Cell 1 Cell 2 Cell 3 | Rich cell A nested table A B C Cell 1 Cell 2 Cell 3 | -After table with **bold** , underline , ~~strikethrough~~ , and *italic* formatting +After table with **bold**, underline, ~~strikethrough~~, and *italic* formatting ### Table with pictures diff --git a/crates/fleischwolf/tests/data/docx/expected/equations.docx.strict.md b/crates/fleischwolf/tests/data/docx/expected/equations.docx.strict.md index bb8602c5..404e021f 100644 --- a/crates/fleischwolf/tests/data/docx/expected/equations.docx.strict.md +++ b/crates/fleischwolf/tests/data/docx/expected/equations.docx.strict.md @@ -1,4 +1,4 @@ -This is a word document and this is an inline equation: $A= \pi r^{2}$ . +This is a word document and this is an inline equation: $A= \pi r^{2}$. First item with inline equation: $A= \pi r^{2}$ is the area formula. @@ -18,7 +18,7 @@ $$f\left(x\right)=a_{0}+\sum_{n=1}^{ \infty }\left(a_{n}\cos(\frac{n \pi x}{L})+ This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. -This is a word document and this is an inline equation: $A= \pi r^{2}$ . If instead, I want an equation by line, I can do this: +This is a word document and this is an inline equation: $A= \pi r^{2}$. If instead, I want an equation by line, I can do this: $$\left(x+a\right)^{n}=\sum_{k=0}^{n}\left(\genfrac{}{}{0pt}{}{n}{k}\right)x^{k}a^{n-k}$$ @@ -32,7 +32,7 @@ This is text. This is text. This is text. This is text. This is text. This is te This is a word document and these are inline equations: $N_{s}^{H}$ / $N_{s}^{P}$ ​. If instead, I want an equation by line, I can do this: -$$e^{x}=1+\frac{x}{1!}+\frac{x^{2}}{2!}+\frac{x^{3}}{3!}+ \text{ \textellipsis } , - \infty @@ -10,13 +10,13 @@ The Standard Ebooks logo. -This ebook is the product of many hours of hard work by volunteers for [Standard Ebooks](https://standardebooks.org/) , and builds on the hard work of other literature lovers made possible by the public domain. +This ebook is the product of many hours of hard work by volunteers for [Standard Ebooks](https://standardebooks.org/), and builds on the hard work of other literature lovers made possible by the public domain. -This particular ebook is based on digital scans from the [Internet Archive](https://standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry#page-scans) . +This particular ebook is based on digital scans from the [Internet Archive](https://standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry#page-scans). -The source text and artwork in this ebook are believed to be in the United States public domain; that is, they are believed to be free of copyright restrictions in the United States. They may still be copyrighted in other countries, so users located outside of the United States must check their local laws before using this ebook. The creators of, and contributors to, this ebook dedicate their contributions to the worldwide public domain via the terms in the [CC0 1.0 Universal Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/) . For full license information, see the [Uncopyright](uncopyright.xhtml) at the end of this ebook. +The source text and artwork in this ebook are believed to be in the United States public domain; that is, they are believed to be free of copyright restrictions in the United States. They may still be copyrighted in other countries, so users located outside of the United States must check their local laws before using this ebook. The creators of, and contributors to, this ebook dedicate their contributions to the worldwide public domain via the terms in the [CC0 1.0 Universal Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/). For full license information, see the [Uncopyright](uncopyright.xhtml) at the end of this ebook. -Standard Ebooks is a volunteer-driven project that produces ebook editions of public domain literature using modern typography, technology, and editorial standards, and distributes them free of cost. You can download this and other ebooks carefully produced for true book lovers at [standardebooks.org](https://standardebooks.org/) . +Standard Ebooks is a volunteer-driven project that produces ebook editions of public domain literature using modern typography, technology, and editorial standards, and distributes them free of cost. You can download this and other ebooks carefully produced for true book lovers at [standardebooks.org](https://standardebooks.org/). ## The Grave of the Slave @@ -200,7 +200,7 @@ This bursting heart relief? There's nothing left for me to love This earth holds nothing dear, -Since *he* , my sweet-my gentle one, +Since *he*, my sweet-my gentle one, Is now no longer here. My poor fond heart had counted on @@ -465,34 +465,34 @@ The Standard Ebooks logo. *Poetry* was compiled from poems published between 1831 and 1836 by -[Sarah Louisa Forten Purvis](https://en.wikipedia.org/wiki/Sarah_Louisa_Forten_Purvis) . +[Sarah Louisa Forten Purvis](https://en.wikipedia.org/wiki/Sarah_Louisa_Forten_Purvis). This ebook was transcribed and produced for [Standard Ebooks](https://standardebooks.org/) by -[Weijia Cheng](https://weijiarhymeswith.asia/) , +[Weijia Cheng](https://weijiarhymeswith.asia/), and is based on digital scans from the -[Internet Archive](https://standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry#page-scans) . +[Internet Archive](https://standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry#page-scans). The cover page is adapted from -*Sunday Morning* , +*Sunday Morning*, a painting completed in 1877 by -[Thomas Waterman Wood](https://en.wikipedia.org/wiki/Thomas_Waterman_Wood) . +[Thomas Waterman Wood](https://en.wikipedia.org/wiki/Thomas_Waterman_Wood). The cover and title pages feature the **League Spartan** and **Sorts Mill Goudy** typefaces created in 2014 and 2009 by -[The League of Moveable Type](https://www.theleagueofmoveabletype.com/) . +[The League of Moveable Type](https://www.theleagueofmoveabletype.com/). This edition was released on **May 21, 2026, 6:29** **p.m.** and is based on -**revision 936122b** . +**revision 936122b**. The first edition of this ebook was released on December 6, 2023, 8:52 p.m. You can check for updates to this ebook, view its revision history, or download it for different ereading systems at -[standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry](https://standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry) . +[standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry](https://standardebooks.org/ebooks/sarah-louisa-forten-purvis/poetry). -The volunteer-driven Standard Ebooks project relies on readers like you to submit typos, corrections, and other improvements. Anyone can contribute at [standardebooks.org](https://standardebooks.org/) . +The volunteer-driven Standard Ebooks project relies on readers like you to submit typos, corrections, and other improvements. Anyone can contribute at [standardebooks.org](https://standardebooks.org/). ## Uncopyright @@ -504,4 +504,4 @@ Copyright pages exist to tell you that you *can't* do something. Unlike them, th Copyright laws are different all over the world, and the source text or artwork in this ebook may still be copyrighted in other countries. If you're not located in the United States, you must check your local laws before using this ebook. Standard Ebooks makes no representations regarding the copyright status of the source text or artwork in this ebook in any country other than the United States. -Non-authorship activities performed on items that are in the public domain-so-called "sweat of the brow" work-don't create a new copyright. That means that nobody can claim a new copyright on an item that is in the public domain for, among other things, work like digitization, markup, or typography. Regardless, the contributors to this ebook release their contributions under the terms in the [CC0 1.0 Universal Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/) , thus dedicating to the worldwide public domain all of the work they've done on this ebook, including but not limited to metadata, the titlepage, imprint, colophon, this Uncopyright, and any changes or enhancements to, or markup on, the original text and artwork. This dedication doesn't change the copyright status of the source text or artwork. We make this dedication in the interest of enriching our global cultural heritage, to promote free and libre culture around the world, and to give back to the unrestricted culture that has given all of us so much. +Non-authorship activities performed on items that are in the public domain-so-called "sweat of the brow" work-don't create a new copyright. That means that nobody can claim a new copyright on an item that is in the public domain for, among other things, work like digitization, markup, or typography. Regardless, the contributors to this ebook release their contributions under the terms in the [CC0 1.0 Universal Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/), thus dedicating to the worldwide public domain all of the work they've done on this ebook, including but not limited to metadata, the titlepage, imprint, colophon, this Uncopyright, and any changes or enhancements to, or markup on, the original text and artwork. This dedication doesn't change the copyright status of the source text or artwork. We make this dedication in the interest of enriching our global cultural heritage, to promote free and libre culture around the world, and to give back to the unrestricted culture that has given all of us so much. diff --git a/crates/fleischwolf/tests/data/html/expected/formatting.html.strict.md b/crates/fleischwolf/tests/data/html/expected/formatting.html.strict.md index 2e292d5d..ecf0484b 100644 --- a/crates/fleischwolf/tests/data/html/expected/formatting.html.strict.md +++ b/crates/fleischwolf/tests/data/html/expected/formatting.html.strict.md @@ -1,13 +1,13 @@ # HTML Text Formatting Examples -This is a **bold (b)** example and right next to it we have a **strong emphasis (strong)** . Notice that **strong + bold mixed** looks similar but carries additional semantic meaning. +This is a **bold (b)** example and right next to it we have a **strong emphasis (strong)**. Notice that **strong + bold mixed** looks similar but carries additional semantic meaning. -Here is an *italic (i)* word and an *emphasis (em)* example. Sometimes we combine them like *italic + emphasis together* . +Here is an *italic (i)* word and an *emphasis (em)* example. Sometimes we combine them like *italic + emphasis together*. -Now let's look at text that appears crossed out: ~~strikethrough with s~~ and ~~deleted with del~~ . You can also mix them: ~~double strikethrough (s + del)~~ . +Now let's look at text that appears crossed out: ~~strikethrough with s~~ and ~~deleted with del~~. You can also mix them: ~~double strikethrough (s + del)~~. -To highlight insertions or underlines: underlined with u , inserted with ins . A combination could be: underline + insertion together . +To highlight insertions or underlines: underlined with u, inserted with ins. A combination could be: underline + insertion together. -Subscript and superscript examples: Water is written as H 2 O using sub. The mathematical expression x 2 + y 3 uses sup. They can also be combined: CO 2 * . +Subscript and superscript examples: Water is written as H 2 O using sub. The mathematical expression x 2 + y 3 uses sup. They can also be combined: CO 2 *. -Mixing several: This sentence has ***strong + emphasis*** , some **bold + underline** , and a formula like a 2 + b 3 . +Mixing several: This sentence has ***strong + emphasis***, some **bold + underline**, and a formula like a 2 + b 3. diff --git a/crates/fleischwolf/tests/data/html/expected/html_code_snippets.html.strict.md b/crates/fleischwolf/tests/data/html/expected/html_code_snippets.html.strict.md index cd5b4347..2054b772 100644 --- a/crates/fleischwolf/tests/data/html/expected/html_code_snippets.html.strict.md +++ b/crates/fleischwolf/tests/data/html/expected/html_code_snippets.html.strict.md @@ -1,10 +1,10 @@ # Code snippets -The Pythagorean theorem can be written as an equation relating the lengths of the sides *a* , *b* and the hypotenuse *c* . +The Pythagorean theorem can be written as an equation relating the lengths of the sides *a*, *b* and the hypotenuse *c*. To use Docling, simply install `docling` from your package manager, e.g. pip: `pip install docling` -To convert individual documents with python, use `convert()` , for example: +To convert individual documents with python, use `convert()`, for example: ``` from docling.document_converter import DocumentConverter @@ -20,5 +20,5 @@ The program will output: `## Docling Technical Report[...]` Prefetch the models: - Use the `docling-tools models download` utility: -- Alternatively, models can be programmatically downloaded using `docling.utils.model_downloader.download_models()` . +- Alternatively, models can be programmatically downloaded using `docling.utils.model_downloader.download_models()`. - Also, you can use download-hf-repo parameter to download arbitrary models from HuggingFace by specifying repo id: `$ docling-tools models download-hf-repo ds4sd/SmolDocling-256M-preview Downloading ds4sd/SmolDocling-256M-preview model from HuggingFace...` diff --git a/crates/fleischwolf/tests/data/html/expected/hyperlink_01.html.strict.md b/crates/fleischwolf/tests/data/html/expected/hyperlink_01.html.strict.md index da30dbf7..e3386f4f 100644 --- a/crates/fleischwolf/tests/data/html/expected/hyperlink_01.html.strict.md +++ b/crates/fleischwolf/tests/data/html/expected/hyperlink_01.html.strict.md @@ -1,3 +1,3 @@ # Something -Please follow the link to: [This page](#) . +Please follow the link to: [This page](#). diff --git a/crates/fleischwolf/tests/data/html/expected/hyperlink_06.html.strict.md b/crates/fleischwolf/tests/data/html/expected/hyperlink_06.html.strict.md index dfec31f5..29dd67c0 100644 --- a/crates/fleischwolf/tests/data/html/expected/hyperlink_06.html.strict.md +++ b/crates/fleischwolf/tests/data/html/expected/hyperlink_06.html.strict.md @@ -1,7 +1,7 @@ # Anchor Links Test -Jump to [Section 2](#section-2) or visit [Example](https://example.com/) . +Jump to [Section 2](#section-2) or visit [Example](https://example.com/). ## Section 2 -Content for section 2 with a [top link](#) . +Content for section 2 with a [top link](#). diff --git a/crates/fleischwolf/tests/data/html/expected/wiki_duck.html.strict.md b/crates/fleischwolf/tests/data/html/expected/wiki_duck.html.strict.md index 9d69a560..9f95910a 100644 --- a/crates/fleischwolf/tests/data/html/expected/wiki_duck.html.strict.md +++ b/crates/fleischwolf/tests/data/html/expected/wiki_duck.html.strict.md @@ -270,13 +270,13 @@ Page semi-protected From Wikipedia, the free encyclopedia -(Redirected from [Duckling](/w/index.php?title=Duckling&redirect=no) ) +(Redirected from [Duckling](/w/index.php?title=Duckling&redirect=no)) Common name for many species of bird -This article is about the bird. For duck as a food, see [Duck as food](/wiki/Duck_as_food) . For other uses, see [Duck (disambiguation)](/wiki/Duck_(disambiguation)) . +This article is about the bird. For duck as a food, see [Duck as food](/wiki/Duck_as_food). For other uses, see [Duck (disambiguation)](/wiki/Duck_(disambiguation)). -"Duckling" redirects here. For other uses, see [Duckling (disambiguation)](/wiki/Duckling_(disambiguation)) . +"Duckling" redirects here. For other uses, see [Duckling (disambiguation)](/wiki/Duckling_(disambiguation)). | Duck | Duck | |-------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------| @@ -293,9 +293,9 @@ This article is about the bird. For duck as a food, see [Duck as food](/wiki/Duc | Subfamilies | Subfamilies | | See text | See text | -**Duck** is the common name for numerous species of [waterfowl](/wiki/Waterfowl) in the [family](/wiki/Family_(biology)) [Anatidae](/wiki/Anatidae) . Ducks are generally smaller and shorter-necked than [swans](/wiki/Swan) and [geese](/wiki/Goose) , which are members of the same family. Divided among several subfamilies, they are a [form taxon](/wiki/Form_taxon) ; they do not represent a [monophyletic group](/wiki/Monophyletic_group) (the group of all descendants of a single common ancestral species), since swans and geese are not considered ducks. Ducks are mostly [aquatic birds](/wiki/Aquatic_bird) , and may be found in both fresh water and sea water. +**Duck** is the common name for numerous species of [waterfowl](/wiki/Waterfowl) in the [family](/wiki/Family_(biology)) [Anatidae](/wiki/Anatidae). Ducks are generally smaller and shorter-necked than [swans](/wiki/Swan) and [geese](/wiki/Goose), which are members of the same family. Divided among several subfamilies, they are a [form taxon](/wiki/Form_taxon); they do not represent a [monophyletic group](/wiki/Monophyletic_group) (the group of all descendants of a single common ancestral species), since swans and geese are not considered ducks. Ducks are mostly [aquatic birds](/wiki/Aquatic_bird), and may be found in both fresh water and sea water. -Ducks are sometimes confused with several types of unrelated water birds with similar forms, such as [loons](/wiki/Loon) or divers, [grebes](/wiki/Grebe) , [gallinules](/wiki/Gallinule) and [coots](/wiki/Coot) . +Ducks are sometimes confused with several types of unrelated water birds with similar forms, such as [loons](/wiki/Loon) or divers, [grebes](/wiki/Grebe), [gallinules](/wiki/Gallinule) and [coots](/wiki/Coot). ## Etymology @@ -305,7 +305,7 @@ Pacific black duck displaying the characteristic upending "duck" -This word replaced Old English *ened* / *ænid* 'duck', possibly to avoid confusion with other words, such as *ende* 'end' with similar forms. Other Germanic languages still have similar words for *duck* , for example, Dutch *eend* , German *Ente* and [Norwegian](/wiki/Norwegian_language) *and* . The word *ened* / *ænid* was inherited from [Proto-Indo-European](/wiki/Proto-Indo-European_language) ; [cf.](/wiki/Cf.) [Latin](/wiki/Latin) *anas* "duck", [Lithuanian](/wiki/Lithuanian_language) *ántis* 'duck', [Ancient Greek](/wiki/Ancient_Greek_language) νῆσσα / νῆττα ( *nēssa* / *nētta* ) 'duck', and [Sanskrit](/wiki/Sanskrit) *ātí* 'water bird', among others. +This word replaced Old English *ened* / *ænid* 'duck', possibly to avoid confusion with other words, such as *ende* 'end' with similar forms. Other Germanic languages still have similar words for *duck*, for example, Dutch *eend*, German *Ente* and [Norwegian](/wiki/Norwegian_language) *and*. The word *ened* / *ænid* was inherited from [Proto-Indo-European](/wiki/Proto-Indo-European_language); [cf.](/wiki/Cf.) [Latin](/wiki/Latin) *anas* "duck", [Lithuanian](/wiki/Lithuanian_language) *ántis* 'duck', [Ancient Greek](/wiki/Ancient_Greek_language) νῆσσα / νῆττα (*nēssa* / *nētta*) 'duck', and [Sanskrit](/wiki/Sanskrit) *ātí* 'water bird', among others. A duckling is a young duck in downy plumage [[](#cite_note-1) [1](#cite_note-1) []](#cite_note-1) or baby duck, [[](#cite_note-2) [2](#cite_note-2) []](#cite_note-2) but in the food trade a young domestic duck which has just reached adult size and bulk and its meat is still fully tender, is sometimes labelled as a duckling. @@ -321,7 +321,7 @@ Wood ducks. ## Taxonomy -All ducks belong to the [biological order](/wiki/Order_(biology)) [Anseriformes](/wiki/Anseriformes) , a group that contains the ducks, geese and swans, as well as the [screamers](/wiki/Screamer) , and the [magpie goose](/wiki/Magpie_goose) . [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) All except the screamers belong to the [biological family](/wiki/Family_(biology)) [Anatidae](/wiki/Anatidae) . [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) Within the family, ducks are split into a variety of subfamilies and 'tribes'. The number and composition of these subfamilies and tribes is the cause of considerable disagreement among taxonomists. [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) Some base their decisions on [morphological characteristics](/wiki/Morphology_(biology)) , others on shared behaviours or genetic studies. [[](#cite_note-FOOTNOTELivezey1986737–738-6) [6](#cite_note-FOOTNOTELivezey1986737–738-6) []](#cite_note-FOOTNOTELivezey1986737–738-6) [[](#cite_note-FOOTNOTEMadsenMcHughde_Kloet1988452-7) [7](#cite_note-FOOTNOTEMadsenMcHughde_Kloet1988452-7) []](#cite_note-FOOTNOTEMadsenMcHughde_Kloet1988452-7) The number of suggested subfamilies containing ducks ranges from two to five. [[](#cite_note-FOOTNOTEDonne-GousséLaudetHänni2002353–354-8) [8](#cite_note-FOOTNOTEDonne-GousséLaudetHänni2002353–354-8) []](#cite_note-FOOTNOTEDonne-GousséLaudetHänni2002353–354-8) [[](#cite_note-FOOTNOTECarboneras1992540-9) [9](#cite_note-FOOTNOTECarboneras1992540-9) []](#cite_note-FOOTNOTECarboneras1992540-9) The significant level of [hybridisation](/wiki/Hybrid_(biology)) that occurs among wild ducks complicates efforts to tease apart the relationships between various species. [[](#cite_note-FOOTNOTECarboneras1992540-9) [9](#cite_note-FOOTNOTECarboneras1992540-9) []](#cite_note-FOOTNOTECarboneras1992540-9) +All ducks belong to the [biological order](/wiki/Order_(biology)) [Anseriformes](/wiki/Anseriformes), a group that contains the ducks, geese and swans, as well as the [screamers](/wiki/Screamer), and the [magpie goose](/wiki/Magpie_goose). [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) All except the screamers belong to the [biological family](/wiki/Family_(biology)) [Anatidae](/wiki/Anatidae). [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) Within the family, ducks are split into a variety of subfamilies and 'tribes'. The number and composition of these subfamilies and tribes is the cause of considerable disagreement among taxonomists. [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) Some base their decisions on [morphological characteristics](/wiki/Morphology_(biology)), others on shared behaviours or genetic studies. [[](#cite_note-FOOTNOTELivezey1986737–738-6) [6](#cite_note-FOOTNOTELivezey1986737–738-6) []](#cite_note-FOOTNOTELivezey1986737–738-6) [[](#cite_note-FOOTNOTEMadsenMcHughde_Kloet1988452-7) [7](#cite_note-FOOTNOTEMadsenMcHughde_Kloet1988452-7) []](#cite_note-FOOTNOTEMadsenMcHughde_Kloet1988452-7) The number of suggested subfamilies containing ducks ranges from two to five. [[](#cite_note-FOOTNOTEDonne-GousséLaudetHänni2002353–354-8) [8](#cite_note-FOOTNOTEDonne-GousséLaudetHänni2002353–354-8) []](#cite_note-FOOTNOTEDonne-GousséLaudetHänni2002353–354-8) [[](#cite_note-FOOTNOTECarboneras1992540-9) [9](#cite_note-FOOTNOTECarboneras1992540-9) []](#cite_note-FOOTNOTECarboneras1992540-9) The significant level of [hybridisation](/wiki/Hybrid_(biology)) that occurs among wild ducks complicates efforts to tease apart the relationships between various species. [[](#cite_note-FOOTNOTECarboneras1992540-9) [9](#cite_note-FOOTNOTECarboneras1992540-9) []](#cite_note-FOOTNOTECarboneras1992540-9) Mallard landing in approach @@ -337,9 +337,9 @@ Male Mandarin duck -The overall [body plan](/wiki/Body_plan) of ducks is elongated and broad, and they are also relatively long-necked, albeit not as long-necked as the geese and swans. The body shape of diving ducks varies somewhat from this in being more rounded. The [bill](/wiki/Beak) is usually broad and contains serrated [pectens](/wiki/Pecten_(biology)) , which are particularly well defined in the filter-feeding species. In the case of some fishing species the bill is long and strongly serrated. The scaled legs are strong and well developed, and generally set far back on the body, more so in the highly aquatic species. The wings are very strong and are generally short and pointed, and the [flight](/wiki/Bird_flight) of ducks requires fast continuous strokes, requiring in turn strong wing muscles. Three species of [steamer duck](/wiki/Steamer_duck) are almost flightless, however. Many species of duck are temporarily flightless while [moulting](/wiki/Moult) ; they seek out protected habitat with good food supplies during this period. This moult typically precedes [migration](/wiki/Bird_migration) . +The overall [body plan](/wiki/Body_plan) of ducks is elongated and broad, and they are also relatively long-necked, albeit not as long-necked as the geese and swans. The body shape of diving ducks varies somewhat from this in being more rounded. The [bill](/wiki/Beak) is usually broad and contains serrated [pectens](/wiki/Pecten_(biology)), which are particularly well defined in the filter-feeding species. In the case of some fishing species the bill is long and strongly serrated. The scaled legs are strong and well developed, and generally set far back on the body, more so in the highly aquatic species. The wings are very strong and are generally short and pointed, and the [flight](/wiki/Bird_flight) of ducks requires fast continuous strokes, requiring in turn strong wing muscles. Three species of [steamer duck](/wiki/Steamer_duck) are almost flightless, however. Many species of duck are temporarily flightless while [moulting](/wiki/Moult); they seek out protected habitat with good food supplies during this period. This moult typically precedes [migration](/wiki/Bird_migration). -The drakes of northern species often have extravagant [plumage](/wiki/Plumage) , but that is [moulted](/wiki/Moult) in summer to give a more female-like appearance, the "eclipse" plumage. Southern resident species typically show less [sexual dimorphism](/wiki/Sexual_dimorphism) , although there are exceptions such as the [paradise shelduck](/wiki/Paradise_shelduck) of [New Zealand](/wiki/New_Zealand) , which is both strikingly sexually dimorphic and in which the female's plumage is brighter than that of the male. The plumage of juvenile birds generally resembles that of the female. Female ducks have evolved to have a corkscrew shaped vagina to prevent rape. +The drakes of northern species often have extravagant [plumage](/wiki/Plumage), but that is [moulted](/wiki/Moult) in summer to give a more female-like appearance, the "eclipse" plumage. Southern resident species typically show less [sexual dimorphism](/wiki/Sexual_dimorphism), although there are exceptions such as the [paradise shelduck](/wiki/Paradise_shelduck) of [New Zealand](/wiki/New_Zealand), which is both strikingly sexually dimorphic and in which the female's plumage is brighter than that of the male. The plumage of juvenile birds generally resembles that of the female. Female ducks have evolved to have a corkscrew shaped vagina to prevent rape. ## Distribution and habitat @@ -349,7 +349,7 @@ Flying steamer ducks in Ushuaia, Argentina -Ducks have a [cosmopolitan distribution](/wiki/Cosmopolitan_distribution) , and are found on every continent except Antarctica. [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) Several species manage to live on subantarctic islands, including [South Georgia](/wiki/South_Georgia_and_the_South_Sandwich_Islands) and the [Auckland Islands](/wiki/Auckland_Islands) . [[](#cite_note-FOOTNOTEShirihai2008239,_245-20) [20](#cite_note-FOOTNOTEShirihai2008239,_245-20) []](#cite_note-FOOTNOTEShirihai2008239,_245-20) Ducks have reached a number of isolated oceanic islands, including the [Hawaiian Islands](/wiki/Hawaiian_Islands) , [Micronesia](/wiki/Micronesia) and the [Galápagos Islands](/wiki/Gal%C3%A1pagos_Islands) , where they are often [vagrants](/wiki/Glossary_of_bird_terms#vagrants) and less often [residents](/wiki/Glossary_of_bird_terms#residents) . [[](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) [21](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) []](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) [[](#cite_note-FOOTNOTEFitterFitterHosking200052–3-22) [22](#cite_note-FOOTNOTEFitterFitterHosking200052–3-22) []](#cite_note-FOOTNOTEFitterFitterHosking200052–3-22) A handful are [endemic](/wiki/Endemic) to such far-flung islands. [[](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) [21](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) []](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) +Ducks have a [cosmopolitan distribution](/wiki/Cosmopolitan_distribution), and are found on every continent except Antarctica. [[](#cite_note-FOOTNOTECarboneras1992536-5) [5](#cite_note-FOOTNOTECarboneras1992536-5) []](#cite_note-FOOTNOTECarboneras1992536-5) Several species manage to live on subantarctic islands, including [South Georgia](/wiki/South_Georgia_and_the_South_Sandwich_Islands) and the [Auckland Islands](/wiki/Auckland_Islands). [[](#cite_note-FOOTNOTEShirihai2008239,_245-20) [20](#cite_note-FOOTNOTEShirihai2008239,_245-20) []](#cite_note-FOOTNOTEShirihai2008239,_245-20) Ducks have reached a number of isolated oceanic islands, including the [Hawaiian Islands](/wiki/Hawaiian_Islands), [Micronesia](/wiki/Micronesia) and the [Galápagos Islands](/wiki/Gal%C3%A1pagos_Islands), where they are often [vagrants](/wiki/Glossary_of_bird_terms#vagrants) and less often [residents](/wiki/Glossary_of_bird_terms#residents). [[](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) [21](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) []](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) [[](#cite_note-FOOTNOTEFitterFitterHosking200052–3-22) [22](#cite_note-FOOTNOTEFitterFitterHosking200052–3-22) []](#cite_note-FOOTNOTEFitterFitterHosking200052–3-22) A handful are [endemic](/wiki/Endemic) to such far-flung islands. [[](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) [21](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) []](#cite_note-FOOTNOTEPrattBrunerBerrett198798–107-21) Female mallard in Cornwall, England @@ -369,15 +369,15 @@ Mallard duckling preening -Ducks eat food sources such as [grasses](/wiki/Poaceae) , aquatic plants, fish, insects, small amphibians, worms, and small [molluscs](/wiki/Mollusc) . +Ducks eat food sources such as [grasses](/wiki/Poaceae), aquatic plants, fish, insects, small amphibians, worms, and small [molluscs](/wiki/Mollusc). -[Dabbling ducks](/wiki/Dabbling_duck) feed on the surface of water or on land, or as deep as they can reach by up-ending without completely submerging. [[](#cite_note-24) [24](#cite_note-24) []](#cite_note-24) Along the edge of the bill, there is a comb-like structure called a [pecten](/wiki/Pecten_(biology)) . This strains the water squirting from the side of the bill and traps any food. The pecten is also used to preen feathers and to hold slippery food items. +[Dabbling ducks](/wiki/Dabbling_duck) feed on the surface of water or on land, or as deep as they can reach by up-ending without completely submerging. [[](#cite_note-24) [24](#cite_note-24) []](#cite_note-24) Along the edge of the bill, there is a comb-like structure called a [pecten](/wiki/Pecten_(biology)). This strains the water squirting from the side of the bill and traps any food. The pecten is also used to preen feathers and to hold slippery food items. [Diving ducks](/wiki/Diving_duck) and [sea ducks](/wiki/Sea_duck) forage deep underwater. To be able to submerge more easily, the diving ducks are heavier than dabbling ducks, and therefore have more difficulty taking off to fly. A few specialized species such as the [mergansers](/wiki/Merganser) are adapted to catch and swallow large fish. -The others have the characteristic wide flat bill adapted to [dredging](/wiki/Dredging) -type jobs such as pulling up waterweed, pulling worms and small molluscs out of mud, searching for insect larvae, and bulk jobs such as dredging out, holding, turning head first, and swallowing a squirming frog. To avoid injury when digging into sediment it has no [cere](/wiki/Cere) , but the nostrils come out through hard horn. +The others have the characteristic wide flat bill adapted to [dredging](/wiki/Dredging) -type jobs such as pulling up waterweed, pulling worms and small molluscs out of mud, searching for insect larvae, and bulk jobs such as dredging out, holding, turning head first, and swallowing a squirming frog. To avoid injury when digging into sediment it has no [cere](/wiki/Cere), but the nostrils come out through hard horn. [*The Guardian*](/wiki/The_Guardian) published an article advising that ducks should not be fed with bread because it [damages the health of the ducks](/wiki/Angel_wing) and pollutes waterways. [[](#cite_note-25) [25](#cite_note-25) []](#cite_note-25) @@ -387,13 +387,13 @@ A Muscovy duckling -Ducks generally [only have one partner at a time](/wiki/Monogamy_in_animals) , although the partnership usually only lasts one year. [[](#cite_note-26) [26](#cite_note-26) []](#cite_note-26) Larger species and the more sedentary species (like fast-river specialists) tend to have pair-bonds that last numerous years. [[](#cite_note-27) [27](#cite_note-27) []](#cite_note-27) Most duck species breed once a year, choosing to do so in favourable conditions ( [spring](/wiki/Spring_(season)) /summer or wet seasons). Ducks also tend to make a [nest](/wiki/Bird_nest) before breeding, and, after hatching, lead their ducklings to water. Mother ducks are very caring and protective of their young, but may abandon some of their ducklings if they are physically stuck in an area they cannot get out of (such as nesting in an enclosed [courtyard](/wiki/Courtyard) ) or are not prospering due to genetic defects or sickness brought about by hypothermia, starvation, or disease. Ducklings can also be orphaned by inconsistent late hatching where a few eggs hatch after the mother has abandoned the nest and led her ducklings to water. [[](#cite_note-28) [28](#cite_note-28) []](#cite_note-28) +Ducks generally [only have one partner at a time](/wiki/Monogamy_in_animals), although the partnership usually only lasts one year. [[](#cite_note-26) [26](#cite_note-26) []](#cite_note-26) Larger species and the more sedentary species (like fast-river specialists) tend to have pair-bonds that last numerous years. [[](#cite_note-27) [27](#cite_note-27) []](#cite_note-27) Most duck species breed once a year, choosing to do so in favourable conditions ([spring](/wiki/Spring_(season)) /summer or wet seasons). Ducks also tend to make a [nest](/wiki/Bird_nest) before breeding, and, after hatching, lead their ducklings to water. Mother ducks are very caring and protective of their young, but may abandon some of their ducklings if they are physically stuck in an area they cannot get out of (such as nesting in an enclosed [courtyard](/wiki/Courtyard)) or are not prospering due to genetic defects or sickness brought about by hypothermia, starvation, or disease. Ducklings can also be orphaned by inconsistent late hatching where a few eggs hatch after the mother has abandoned the nest and led her ducklings to water. [[](#cite_note-28) [28](#cite_note-28) []](#cite_note-28) ### Communication -Female [mallard](/wiki/Mallard) ducks (as well as several other species in the genus *Anas* , such as the [American](/wiki/American_black_duck) and [Pacific black ducks](/wiki/Pacific_black_duck) , [spot-billed duck](/wiki/Spot-billed_duck) , [northern pintail](/wiki/Northern_pintail) and [common teal](/wiki/Common_teal) ) make the classic "quack" sound while males make a similar but raspier sound that is sometimes written as "breeeeze", [[](#cite_note-29) [29](#cite_note-29) []](#cite_note-29) [ [*self-published source?*](/wiki/Wikipedia:Verifiability#Self-published_sources) ] but, despite widespread misconceptions, most species of duck do not "quack". [[](#cite_note-30) [30](#cite_note-30) []](#cite_note-30) In general, ducks make a range of [calls](/wiki/Bird_vocalisation) , including whistles, cooing, yodels and grunts. For example, the [scaup](/wiki/Scaup) - which are [diving ducks](/wiki/Diving_duck) - make a noise like "scaup" (hence their name). Calls may be loud displaying calls or quieter contact calls. +Female [mallard](/wiki/Mallard) ducks (as well as several other species in the genus *Anas*, such as the [American](/wiki/American_black_duck) and [Pacific black ducks](/wiki/Pacific_black_duck), [spot-billed duck](/wiki/Spot-billed_duck), [northern pintail](/wiki/Northern_pintail) and [common teal](/wiki/Common_teal)) make the classic "quack" sound while males make a similar but raspier sound that is sometimes written as "breeeeze", [[](#cite_note-29) [29](#cite_note-29) []](#cite_note-29) [[*self-published source?*](/wiki/Wikipedia:Verifiability#Self-published_sources)] but, despite widespread misconceptions, most species of duck do not "quack". [[](#cite_note-30) [30](#cite_note-30) []](#cite_note-30) In general, ducks make a range of [calls](/wiki/Bird_vocalisation), including whistles, cooing, yodels and grunts. For example, the [scaup](/wiki/Scaup) - which are [diving ducks](/wiki/Diving_duck) - make a noise like "scaup" (hence their name). Calls may be loud displaying calls or quieter contact calls. -A common [urban legend](/wiki/Urban_legend) claims that duck quacks do not echo; however, this has been proven to be false. This myth was first debunked by the Acoustics Research Centre at the [University of Salford](/wiki/University_of_Salford) in 2003 as part of the [British Association](/wiki/British_Association) 's Festival of Science. [[](#cite_note-31) [31](#cite_note-31) []](#cite_note-31) It was also debunked in [one of the earlier episodes](/wiki/MythBusters_(2003_season)#Does_a_Duck's_Quack_Echo?) of the popular Discovery Channel television show [*MythBusters*](/wiki/MythBusters) . [[](#cite_note-32) [32](#cite_note-32) []](#cite_note-32) +A common [urban legend](/wiki/Urban_legend) claims that duck quacks do not echo; however, this has been proven to be false. This myth was first debunked by the Acoustics Research Centre at the [University of Salford](/wiki/University_of_Salford) in 2003 as part of the [British Association](/wiki/British_Association) 's Festival of Science. [[](#cite_note-31) [31](#cite_note-31) []](#cite_note-31) It was also debunked in [one of the earlier episodes](/wiki/MythBusters_(2003_season)#Does_a_Duck's_Quack_Echo?) of the popular Discovery Channel television show [*MythBusters*](/wiki/MythBusters). [[](#cite_note-32) [32](#cite_note-32) []](#cite_note-32) ### Predators @@ -401,9 +401,9 @@ Ringed teal -Ducks have many predators. Ducklings are particularly vulnerable, since their inability to fly makes them easy prey not only for predatory birds but also for large fish like [pike](/wiki/Esox) , [crocodilians](/wiki/Crocodilia) , predatory [testudines](/wiki/Testudines) such as the [alligator snapping turtle](/wiki/Alligator_snapping_turtle) , and other aquatic hunters, including fish-eating birds such as [herons](/wiki/Heron) . Ducks' nests are raided by land-based predators, and brooding females may be caught unaware on the nest by mammals, such as [foxes](/wiki/Fox) , or large birds, such as [hawks](/wiki/Hawk) or [owls](/wiki/Owl) . +Ducks have many predators. Ducklings are particularly vulnerable, since their inability to fly makes them easy prey not only for predatory birds but also for large fish like [pike](/wiki/Esox), [crocodilians](/wiki/Crocodilia), predatory [testudines](/wiki/Testudines) such as the [alligator snapping turtle](/wiki/Alligator_snapping_turtle), and other aquatic hunters, including fish-eating birds such as [herons](/wiki/Heron). Ducks' nests are raided by land-based predators, and brooding females may be caught unaware on the nest by mammals, such as [foxes](/wiki/Fox), or large birds, such as [hawks](/wiki/Hawk) or [owls](/wiki/Owl). -Adult ducks are fast fliers, but may be caught on the water by large aquatic predators including big fish such as the North American [muskie](/wiki/Muskellunge) and the European [pike](/wiki/Esox) . In flight, ducks are safe from all but a few predators such as humans and the [peregrine falcon](/wiki/Peregrine_falcon) , which uses its speed and strength to catch ducks. +Adult ducks are fast fliers, but may be caught on the water by large aquatic predators including big fish such as the North American [muskie](/wiki/Muskellunge) and the European [pike](/wiki/Esox). In flight, ducks are safe from all but a few predators such as humans and the [peregrine falcon](/wiki/Peregrine_falcon), which uses its speed and strength to catch ducks. ## Relationship with humans @@ -411,9 +411,9 @@ Adult ducks are fast fliers, but may be caught on the water by large aquatic pre Main article: [Waterfowl hunting](/wiki/Waterfowl_hunting) -Humans have hunted ducks since prehistoric times. Excavations of [middens](/wiki/Midden) in California dating to 7800 - 6400 [BP](/wiki/Before_present) have turned up bones of ducks, including at least one now-extinct flightless species. [[](#cite_note-FOOTNOTEErlandson1994171-33) [33](#cite_note-FOOTNOTEErlandson1994171-33) []](#cite_note-FOOTNOTEErlandson1994171-33) Ducks were captured in "significant numbers" by [Holocene](/wiki/Holocene) inhabitants of the lower [Ohio River](/wiki/Ohio_River) valley, suggesting they took advantage of the seasonal bounty provided by migrating waterfowl. [[](#cite_note-FOOTNOTEJeffries2008168,_243-34) [34](#cite_note-FOOTNOTEJeffries2008168,_243-34) []](#cite_note-FOOTNOTEJeffries2008168,_243-34) Neolithic hunters in locations as far apart as the Caribbean, [[](#cite_note-FOOTNOTESued-Badillo200365-35) [35](#cite_note-FOOTNOTESued-Badillo200365-35) []](#cite_note-FOOTNOTESued-Badillo200365-35) Scandinavia, [[](#cite_note-FOOTNOTEThorpe199668-36) [36](#cite_note-FOOTNOTEThorpe199668-36) []](#cite_note-FOOTNOTEThorpe199668-36) Egypt, [[](#cite_note-FOOTNOTEMaisels199942-37) [37](#cite_note-FOOTNOTEMaisels199942-37) []](#cite_note-FOOTNOTEMaisels199942-37) Switzerland, [[](#cite_note-FOOTNOTERau1876133-38) [38](#cite_note-FOOTNOTERau1876133-38) []](#cite_note-FOOTNOTERau1876133-38) and China relied on ducks as a source of protein for some or all of the year. [[](#cite_note-FOOTNOTEHigman201223-39) [39](#cite_note-FOOTNOTEHigman201223-39) []](#cite_note-FOOTNOTEHigman201223-39) Archeological evidence shows that [Māori people](/wiki/M%C4%81ori_people) in New Zealand hunted the flightless [Finsch's duck](/wiki/Finsch%27s_duck) , possibly to extinction, though rat predation may also have contributed to its fate. [[](#cite_note-FOOTNOTEHume201253-40) [40](#cite_note-FOOTNOTEHume201253-40) []](#cite_note-FOOTNOTEHume201253-40) A similar end awaited the [Chatham duck](/wiki/Chatham_duck) , a species with reduced flying capabilities which went extinct shortly after its island was colonised by Polynesian settlers. [[](#cite_note-FOOTNOTEHume201252-41) [41](#cite_note-FOOTNOTEHume201252-41) []](#cite_note-FOOTNOTEHume201252-41) It is probable that duck eggs were gathered by Neolithic hunter-gathers as well, though hard evidence of this is uncommon. [[](#cite_note-FOOTNOTESued-Badillo200365-35) [35](#cite_note-FOOTNOTESued-Badillo200365-35) []](#cite_note-FOOTNOTESued-Badillo200365-35) [[](#cite_note-FOOTNOTEFieldhouse2002167-42) [42](#cite_note-FOOTNOTEFieldhouse2002167-42) []](#cite_note-FOOTNOTEFieldhouse2002167-42) +Humans have hunted ducks since prehistoric times. Excavations of [middens](/wiki/Midden) in California dating to 7800 - 6400 [BP](/wiki/Before_present) have turned up bones of ducks, including at least one now-extinct flightless species. [[](#cite_note-FOOTNOTEErlandson1994171-33) [33](#cite_note-FOOTNOTEErlandson1994171-33) []](#cite_note-FOOTNOTEErlandson1994171-33) Ducks were captured in "significant numbers" by [Holocene](/wiki/Holocene) inhabitants of the lower [Ohio River](/wiki/Ohio_River) valley, suggesting they took advantage of the seasonal bounty provided by migrating waterfowl. [[](#cite_note-FOOTNOTEJeffries2008168,_243-34) [34](#cite_note-FOOTNOTEJeffries2008168,_243-34) []](#cite_note-FOOTNOTEJeffries2008168,_243-34) Neolithic hunters in locations as far apart as the Caribbean, [[](#cite_note-FOOTNOTESued-Badillo200365-35) [35](#cite_note-FOOTNOTESued-Badillo200365-35) []](#cite_note-FOOTNOTESued-Badillo200365-35) Scandinavia, [[](#cite_note-FOOTNOTEThorpe199668-36) [36](#cite_note-FOOTNOTEThorpe199668-36) []](#cite_note-FOOTNOTEThorpe199668-36) Egypt, [[](#cite_note-FOOTNOTEMaisels199942-37) [37](#cite_note-FOOTNOTEMaisels199942-37) []](#cite_note-FOOTNOTEMaisels199942-37) Switzerland, [[](#cite_note-FOOTNOTERau1876133-38) [38](#cite_note-FOOTNOTERau1876133-38) []](#cite_note-FOOTNOTERau1876133-38) and China relied on ducks as a source of protein for some or all of the year. [[](#cite_note-FOOTNOTEHigman201223-39) [39](#cite_note-FOOTNOTEHigman201223-39) []](#cite_note-FOOTNOTEHigman201223-39) Archeological evidence shows that [Māori people](/wiki/M%C4%81ori_people) in New Zealand hunted the flightless [Finsch's duck](/wiki/Finsch%27s_duck), possibly to extinction, though rat predation may also have contributed to its fate. [[](#cite_note-FOOTNOTEHume201253-40) [40](#cite_note-FOOTNOTEHume201253-40) []](#cite_note-FOOTNOTEHume201253-40) A similar end awaited the [Chatham duck](/wiki/Chatham_duck), a species with reduced flying capabilities which went extinct shortly after its island was colonised by Polynesian settlers. [[](#cite_note-FOOTNOTEHume201252-41) [41](#cite_note-FOOTNOTEHume201252-41) []](#cite_note-FOOTNOTEHume201252-41) It is probable that duck eggs were gathered by Neolithic hunter-gathers as well, though hard evidence of this is uncommon. [[](#cite_note-FOOTNOTESued-Badillo200365-35) [35](#cite_note-FOOTNOTESued-Badillo200365-35) []](#cite_note-FOOTNOTESued-Badillo200365-35) [[](#cite_note-FOOTNOTEFieldhouse2002167-42) [42](#cite_note-FOOTNOTEFieldhouse2002167-42) []](#cite_note-FOOTNOTEFieldhouse2002167-42) -In many areas, wild ducks (including ducks farmed and released into the wild) are hunted for food or sport, [[](#cite_note-43) [43](#cite_note-43) []](#cite_note-43) by shooting, or by being trapped using [duck decoys](/wiki/Duck_decoy_(structure)) . Because an idle floating duck or a duck squatting on land cannot react to fly or move quickly, "a sitting duck" has come to mean "an easy target". These ducks may be [contaminated by pollutants](/wiki/Duck_(food)#Pollution) such as [PCBs](/wiki/Polychlorinated_biphenyl) . [[](#cite_note-44) [44](#cite_note-44) []](#cite_note-44) +In many areas, wild ducks (including ducks farmed and released into the wild) are hunted for food or sport, [[](#cite_note-43) [43](#cite_note-43) []](#cite_note-43) by shooting, or by being trapped using [duck decoys](/wiki/Duck_decoy_(structure)). Because an idle floating duck or a duck squatting on land cannot react to fly or move quickly, "a sitting duck" has come to mean "an easy target". These ducks may be [contaminated by pollutants](/wiki/Duck_(food)#Pollution) such as [PCBs](/wiki/Polychlorinated_biphenyl). [[](#cite_note-44) [44](#cite_note-44) []](#cite_note-44) ### Domestication @@ -423,7 +423,7 @@ Indian Runner ducks, a common breed of domestic ducks -Ducks have many economic uses, being farmed for their meat, eggs, and feathers (particularly their [down](/wiki/Down_feather) ). Approximately 3 billion ducks are slaughtered each year for meat worldwide. [[](#cite_note-45) [45](#cite_note-45) []](#cite_note-45) They are also kept and bred by aviculturists and often displayed in zoos. Almost all the varieties of domestic ducks are descended from the [mallard](/wiki/Mallard) ( *Anas platyrhynchos* ), apart from the [Muscovy duck](/wiki/Muscovy_duck) ( *Cairina moschata* ). [[](#cite_note-46) [46](#cite_note-46) []](#cite_note-46) [[](#cite_note-47) [47](#cite_note-47) []](#cite_note-47) The [Call duck](/wiki/Call_duck) is another example of a domestic duck breed. Its name comes from its original use established by hunters, as a decoy to attract wild mallards from the sky, into traps set for them on the ground. The call duck is the world's smallest domestic duck breed, as it weighs less than 1 kg (2.2 lb). [[](#cite_note-48) [48](#cite_note-48) []](#cite_note-48) +Ducks have many economic uses, being farmed for their meat, eggs, and feathers (particularly their [down](/wiki/Down_feather)). Approximately 3 billion ducks are slaughtered each year for meat worldwide. [[](#cite_note-45) [45](#cite_note-45) []](#cite_note-45) They are also kept and bred by aviculturists and often displayed in zoos. Almost all the varieties of domestic ducks are descended from the [mallard](/wiki/Mallard) (*Anas platyrhynchos*), apart from the [Muscovy duck](/wiki/Muscovy_duck) (*Cairina moschata*). [[](#cite_note-46) [46](#cite_note-46) []](#cite_note-46) [[](#cite_note-47) [47](#cite_note-47) []](#cite_note-47) The [Call duck](/wiki/Call_duck) is another example of a domestic duck breed. Its name comes from its original use established by hunters, as a decoy to attract wild mallards from the sky, into traps set for them on the ground. The call duck is the world's smallest domestic duck breed, as it weighs less than 1 kg (2.2 lb). [[](#cite_note-48) [48](#cite_note-48) []](#cite_note-48) ### Heraldry @@ -431,13 +431,13 @@ Three black-colored ducks in the coat of arms of Maaninka[49] -Ducks appear on several [coats of arms](/wiki/Coats_of_arms) , including the coat of arms of [Lubāna](/wiki/Lub%C4%81na) ( [Latvia](/wiki/Latvia) ) [[](#cite_note-50) [50](#cite_note-50) []](#cite_note-50) and the coat of arms of [Föglö](/wiki/F%C3%B6gl%C3%B6) ( [Åland](/wiki/%C3%85land) ). [[](#cite_note-51) [51](#cite_note-51) []](#cite_note-51) +Ducks appear on several [coats of arms](/wiki/Coats_of_arms), including the coat of arms of [Lubāna](/wiki/Lub%C4%81na) ([Latvia](/wiki/Latvia)) [[](#cite_note-50) [50](#cite_note-50) []](#cite_note-50) and the coat of arms of [Föglö](/wiki/F%C3%B6gl%C3%B6) ([Åland](/wiki/%C3%85land)). [[](#cite_note-51) [51](#cite_note-51) []](#cite_note-51) ### Cultural references -In 2002, psychologist [Richard Wiseman](/wiki/Richard_Wiseman) and colleagues at the [University of Hertfordshire](/wiki/University_of_Hertfordshire) , [UK](/wiki/UK) , finished a year-long [LaughLab](/wiki/LaughLab) experiment, concluding that of all animals, ducks attract the most humor and silliness; he said, "If you're going to tell a joke involving an animal, make it a duck." [[](#cite_note-52) [52](#cite_note-52) []](#cite_note-52) The word "duck" may have become an [inherently funny word](/wiki/Inherently_funny_word) in many languages, possibly because ducks are seen as silly in their looks or behavior. Of the many [ducks in fiction](/wiki/List_of_fictional_ducks) , many are cartoon characters, such as [Walt Disney](/wiki/The_Walt_Disney_Company) 's [Donald Duck](/wiki/Donald_Duck) , and [Warner Bros.](/wiki/Warner_Bros.) ' [Daffy Duck](/wiki/Daffy_Duck) . [Howard the Duck](/wiki/Howard_the_Duck) started as a comic book character in 1973 [[](#cite_note-53) [53](#cite_note-53) []](#cite_note-53) [[](#cite_note-54) [54](#cite_note-54) []](#cite_note-54) and was made into a [movie](/wiki/Howard_the_Duck_(film)) in 1986. +In 2002, psychologist [Richard Wiseman](/wiki/Richard_Wiseman) and colleagues at the [University of Hertfordshire](/wiki/University_of_Hertfordshire), [UK](/wiki/UK), finished a year-long [LaughLab](/wiki/LaughLab) experiment, concluding that of all animals, ducks attract the most humor and silliness; he said, "If you're going to tell a joke involving an animal, make it a duck." [[](#cite_note-52) [52](#cite_note-52) []](#cite_note-52) The word "duck" may have become an [inherently funny word](/wiki/Inherently_funny_word) in many languages, possibly because ducks are seen as silly in their looks or behavior. Of the many [ducks in fiction](/wiki/List_of_fictional_ducks), many are cartoon characters, such as [Walt Disney](/wiki/The_Walt_Disney_Company) 's [Donald Duck](/wiki/Donald_Duck), and [Warner Bros.](/wiki/Warner_Bros.) ' [Daffy Duck](/wiki/Daffy_Duck). [Howard the Duck](/wiki/Howard_the_Duck) started as a comic book character in 1973 [[](#cite_note-53) [53](#cite_note-53) []](#cite_note-53) [[](#cite_note-54) [54](#cite_note-54) []](#cite_note-54) and was made into a [movie](/wiki/Howard_the_Duck_(film)) in 1986. -The 1992 Disney film [*The Mighty Ducks*](/wiki/The_Mighty_Ducks_(film)) , starring [Emilio Estevez](/wiki/Emilio_Estevez) , chose the duck as the mascot for the fictional youth hockey team who are protagonists of the movie, based on the duck being described as a fierce fighter. This led to the duck becoming the nickname and mascot for the eventual [National Hockey League](/wiki/National_Hockey_League) professional team of the [Anaheim Ducks](/wiki/Anaheim_Ducks) , who were founded with the name the Mighty Ducks of Anaheim. [ [*citation needed*](/wiki/Wikipedia:Citation_needed) ] The duck is also the nickname of the [University of Oregon](/wiki/University_of_Oregon) sports teams as well as the [Long Island Ducks](/wiki/Long_Island_Ducks) minor league [baseball](/wiki/Baseball) team. [[](#cite_note-55) [55](#cite_note-55) []](#cite_note-55) +The 1992 Disney film [*The Mighty Ducks*](/wiki/The_Mighty_Ducks_(film)), starring [Emilio Estevez](/wiki/Emilio_Estevez), chose the duck as the mascot for the fictional youth hockey team who are protagonists of the movie, based on the duck being described as a fierce fighter. This led to the duck becoming the nickname and mascot for the eventual [National Hockey League](/wiki/National_Hockey_League) professional team of the [Anaheim Ducks](/wiki/Anaheim_Ducks), who were founded with the name the Mighty Ducks of Anaheim. [[*citation needed*](/wiki/Wikipedia:Citation_needed)] The duck is also the nickname of the [University of Oregon](/wiki/University_of_Oregon) sports teams as well as the [Long Island Ducks](/wiki/Long_Island_Ducks) minor league [baseball](/wiki/Baseball) team. [[](#cite_note-55) [55](#cite_note-55) []](#cite_note-55) ## See also @@ -453,84 +453,84 @@ The 1992 Disney film [*The Mighty Ducks*](/wiki/The_Mighty_Ducks_(film)) , starr ### Citations -1. [**^**](#cite_ref-1) ["Duckling"](http://dictionary.reference.com/browse/duckling) . *The American Heritage Dictionary of the English Language, Fourth Edition* . Houghton Mifflin Company. 2006 . Retrieved 2015-05-22 . -2. [**^**](#cite_ref-2) ["Duckling"](http://dictionary.reference.com/browse/duckling) . *Kernerman English Multilingual Dictionary (Beta Version)* . K. Dictionaries Ltd. 2000-2006 . Retrieved 2015-05-22 . -3. [**^**](#cite_ref-3) Dohner, Janet Vorwald (2001). [*The Encyclopedia of Historic and Endangered Livestock and Poultry Breeds*](https://books.google.com/books?id=WJCTL_mC5w4C&q=male+duck+is+called+a+drake+and+the+female+is+called+a+duck&pg=PA457) . Yale University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0300138139](/wiki/Special:BookSources/978-0300138139) . -4. [**^**](#cite_ref-4) Visca, Curt; Visca, Kelley (2003). [*How to Draw Cartoon Birds*](https://books.google.com/books?id=VqSquCLNrZcC&q=male+duck+is+called+a+drake+and+the+female+is+called+a+duck+%28or+hen%29&pg=PA16) . The Rosen Publishing Group. [ISBN](/wiki/ISBN_(identifier)) [9780823961566](/wiki/Special:BookSources/9780823961566) . -5. ^ [***a***](#cite_ref-FOOTNOTECarboneras1992536_5-0) [***b***](#cite_ref-FOOTNOTECarboneras1992536_5-1) [***c***](#cite_ref-FOOTNOTECarboneras1992536_5-2) [***d***](#cite_ref-FOOTNOTECarboneras1992536_5-3) [Carboneras 1992](#CITEREFCarboneras1992) , p. 536. -6. [**^**](#cite_ref-FOOTNOTELivezey1986737–738_6-0) [Livezey 1986](#CITEREFLivezey1986) , pp. 737-738. -7. [**^**](#cite_ref-FOOTNOTEMadsenMcHughde_Kloet1988452_7-0) [Madsen, McHugh & de Kloet 1988](#CITEREFMadsenMcHughde_Kloet1988) , p. 452. -8. [**^**](#cite_ref-FOOTNOTEDonne-GousséLaudetHänni2002353–354_8-0) [Donne-Goussé, Laudet & Hänni 2002](#CITEREFDonne-GousséLaudetHänni2002) , pp. 353-354. -9. ^ [***a***](#cite_ref-FOOTNOTECarboneras1992540_9-0) [***b***](#cite_ref-FOOTNOTECarboneras1992540_9-1) [***c***](#cite_ref-FOOTNOTECarboneras1992540_9-2) [***d***](#cite_ref-FOOTNOTECarboneras1992540_9-3) [***e***](#cite_ref-FOOTNOTECarboneras1992540_9-4) [***f***](#cite_ref-FOOTNOTECarboneras1992540_9-5) [Carboneras 1992](#CITEREFCarboneras1992) , p. 540. -10. [**^**](#cite_ref-FOOTNOTEElphickDunningSibley2001191_10-0) [Elphick, Dunning & Sibley 2001](#CITEREFElphickDunningSibley2001) , p. 191. -11. [**^**](#cite_ref-FOOTNOTEKear2005448_11-0) [Kear 2005](#CITEREFKear2005) , p. 448. -12. [**^**](#cite_ref-FOOTNOTEKear2005622–623_12-0) [Kear 2005](#CITEREFKear2005) , p. 622-623. -13. [**^**](#cite_ref-FOOTNOTEKear2005686_13-0) [Kear 2005](#CITEREFKear2005) , p. 686. -14. [**^**](#cite_ref-FOOTNOTEElphickDunningSibley2001193_14-0) [Elphick, Dunning & Sibley 2001](#CITEREFElphickDunningSibley2001) , p. 193. -15. ^ [***a***](#cite_ref-FOOTNOTECarboneras1992537_15-0) [***b***](#cite_ref-FOOTNOTECarboneras1992537_15-1) [***c***](#cite_ref-FOOTNOTECarboneras1992537_15-2) [***d***](#cite_ref-FOOTNOTECarboneras1992537_15-3) [***e***](#cite_ref-FOOTNOTECarboneras1992537_15-4) [***f***](#cite_ref-FOOTNOTECarboneras1992537_15-5) [***g***](#cite_ref-FOOTNOTECarboneras1992537_15-6) [Carboneras 1992](#CITEREFCarboneras1992) , p. 537. -16. [**^**](#cite_ref-FOOTNOTEAmerican_Ornithologists'_Union1998xix_16-0) [American Ornithologists' Union 1998](#CITEREFAmerican_Ornithologists'_Union1998) , p. xix. -17. [**^**](#cite_ref-FOOTNOTEAmerican_Ornithologists'_Union1998_17-0) [American Ornithologists' Union 1998](#CITEREFAmerican_Ornithologists'_Union1998) . -18. [**^**](#cite_ref-FOOTNOTECarboneras1992538_18-0) [Carboneras 1992](#CITEREFCarboneras1992) , p. 538. -19. [**^**](#cite_ref-FOOTNOTEChristidisBoles200862_19-0) [Christidis & Boles 2008](#CITEREFChristidisBoles2008) , p. 62. -20. [**^**](#cite_ref-FOOTNOTEShirihai2008239,_245_20-0) [Shirihai 2008](#CITEREFShirihai2008) , pp. 239, 245. -21. ^ [***a***](#cite_ref-FOOTNOTEPrattBrunerBerrett198798–107_21-0) [***b***](#cite_ref-FOOTNOTEPrattBrunerBerrett198798–107_21-1) [Pratt, Bruner & Berrett 1987](#CITEREFPrattBrunerBerrett1987) , pp. 98-107. -22. [**^**](#cite_ref-FOOTNOTEFitterFitterHosking200052–3_22-0) [Fitter, Fitter & Hosking 2000](#CITEREFFitterFitterHosking2000) , pp. 52-3. -23. [**^**](#cite_ref-23) ["Pacific Black Duck"](http://www.wiresnr.org/pacificblackduck.html) . *www.wiresnr.org* . Retrieved 2018-04-27 . -24. [**^**](#cite_ref-24) Ogden, Evans. ["Dabbling Ducks"](https://www.sfu.ca/biology/wildberg/species/dabbducks.html) . CWE . Retrieved 2006-11-02 . -25. [**^**](#cite_ref-25) Karl Mathiesen (16 March 2015). ["Don't feed the ducks bread, say conservationists"](https://www.theguardian.com/environment/2015/mar/16/dont-feed-the-ducks-bread-say-conservationists) . *The Guardian* . Retrieved 13 November 2016 . -26. [**^**](#cite_ref-26) Rohwer, Frank C.; Anderson, Michael G. (1988). "Female-Biased Philopatry, Monogamy, and the Timing of Pair Formation in Migratory Waterfowl". *Current Ornithology* . pp. 187-221. [doi](/wiki/Doi_(identifier)) : [10.1007/978-1-4615-6787-5_4](https://doi.org/10.1007%2F978-1-4615-6787-5_4) . [ISBN](/wiki/ISBN_(identifier)) [978-1-4615-6789-9](/wiki/Special:BookSources/978-1-4615-6789-9) . -27. [**^**](#cite_ref-27) Smith, Cyndi M.; Cooke, Fred; Robertson, Gregory J.; Goudie, R. Ian; Boyd, W. Sean (2000). ["Long-Term Pair Bonds in Harlequin Ducks"](https://doi.org/10.1093%2Fcondor%2F102.1.201) . *The Condor* . **102** (1): 201-205. [doi](/wiki/Doi_(identifier)) : [10.1093/condor/102.1.201](https://doi.org/10.1093%2Fcondor%2F102.1.201) . [hdl](/wiki/Hdl_(identifier)) : [10315/13797](https://hdl.handle.net/10315%2F13797) . -28. [**^**](#cite_ref-28) ["If You Find An Orphaned Duckling - Wildlife Rehabber"](https://web.archive.org/web/20180923152911/http://wildliferehabber.com/content/if-you-find-duckling) . *wildliferehabber.com* . Archived from [the original](https://wildliferehabber.com/content/if-you-find-duckling) on 2018-09-23 . Retrieved 2018-12-22 . -29. [**^**](#cite_ref-29) Carver, Heather (2011). [*The Duck Bible*](https://books.google.com/books?id=VGofAwAAQBAJ&q=mallard+sound+deep+and+raspy&pg=PA39) . Lulu.com. [ISBN](/wiki/ISBN_(identifier)) [9780557901562](/wiki/Special:BookSources/9780557901562) . [ [*self-published source*](/wiki/Wikipedia:Verifiability#Self-published_sources) ] -30. [**^**](#cite_ref-30) Titlow, Budd (2013-09-03). [*Bird Brains: Inside the Strange Minds of Our Fine Feathered Friends*](https://books.google.com/books?id=fXJBBAAAQBAJ&q=Females+of+most+dabbling+ducks+make+the+classic+%22quack%22+sound+but+most+ducks+don%27t+quack&pg=PA123) . Rowman & Littlefield. [ISBN](/wiki/ISBN_(identifier)) [9780762797707](/wiki/Special:BookSources/9780762797707) . -31. [**^**](#cite_ref-31) Amos, Jonathan (2003-09-08). ["Sound science is quackers"](http://news.bbc.co.uk/2/hi/science/nature/3086890.stm) . *BBC News* . Retrieved 2006-11-02 . -32. [**^**](#cite_ref-32) ["Mythbusters Episode 8"](http://mythbustersresults.com/episode8) . 12 December 2003. -33. [**^**](#cite_ref-FOOTNOTEErlandson1994171_33-0) [Erlandson 1994](#CITEREFErlandson1994) , p. 171. -34. [**^**](#cite_ref-FOOTNOTEJeffries2008168,_243_34-0) [Jeffries 2008](#CITEREFJeffries2008) , pp. 168, 243. -35. ^ [***a***](#cite_ref-FOOTNOTESued-Badillo200365_35-0) [***b***](#cite_ref-FOOTNOTESued-Badillo200365_35-1) [Sued-Badillo 2003](#CITEREFSued-Badillo2003) , p. 65. -36. [**^**](#cite_ref-FOOTNOTEThorpe199668_36-0) [Thorpe 1996](#CITEREFThorpe1996) , p. 68. -37. [**^**](#cite_ref-FOOTNOTEMaisels199942_37-0) [Maisels 1999](#CITEREFMaisels1999) , p. 42. -38. [**^**](#cite_ref-FOOTNOTERau1876133_38-0) [Rau 1876](#CITEREFRau1876) , p. 133. -39. [**^**](#cite_ref-FOOTNOTEHigman201223_39-0) [Higman 2012](#CITEREFHigman2012) , p. 23. -40. [**^**](#cite_ref-FOOTNOTEHume201253_40-0) [Hume 2012](#CITEREFHume2012) , p. 53. -41. [**^**](#cite_ref-FOOTNOTEHume201252_41-0) [Hume 2012](#CITEREFHume2012) , p. 52. -42. [**^**](#cite_ref-FOOTNOTEFieldhouse2002167_42-0) [Fieldhouse 2002](#CITEREFFieldhouse2002) , p. 167. -43. [**^**](#cite_ref-43) Livingston, A. D. (1998-01-01). [*Guide to Edible Plants and Animals*](https://books.google.com/books?id=NViSMffyaSgC&q=%C2%A0%C2%A0In+many+areas,+wild+ducks+of+various+species+are+hunted+for+food+or+sport) . Wordsworth Editions, Limited. [ISBN](/wiki/ISBN_(identifier)) [9781853263774](/wiki/Special:BookSources/9781853263774) . -44. [**^**](#cite_ref-44) ["Study plan for waterfowl injury assessment: Determining PCB concentrations in Hudson river resident waterfowl"](https://www.dec.ny.gov/docs/fish_marine_pdf/wfp09a.pdf) (PDF) . *New York State Department of Environmental Conservation* . US Department of Commerce. December 2008. p. 3. [Archived](https://ghostarchive.org/archive/20221009/https://www.dec.ny.gov/docs/fish_marine_pdf/wfp09a.pdf) (PDF) from the original on 2022-10-09 . Retrieved 2 July 2019 . -45. [**^**](#cite_ref-45) ["FAOSTAT"](http://www.fao.org/faostat/en/#data/QL) . *www.fao.org* . Retrieved 2019-10-25 . -46. [**^**](#cite_ref-46) ["Anas platyrhynchos, Domestic Duck; DigiMorph Staff - The University of Texas at Austin"](http://digimorph.org/specimens/anas_platyrhynchos/skull/) . Digimorph.org . Retrieved 2012-12-23 . -47. [**^**](#cite_ref-47) Sy Montgomery. ["Mallard; Encyclopædia Britannica"](https://www.britannica.com/eb/topic-360302/mallard) . *Britannica.com* . Retrieved 2012-12-23 . -48. [**^**](#cite_ref-48) Glenday, Craig (2014). [*Guinness World Records*](https://archive.org/details/guinnessworldrec0000unse_r3e7/page/135) . Guinness World Records Limited. pp. [135](https://archive.org/details/guinnessworldrec0000unse_r3e7/page/135) . [ISBN](/wiki/ISBN_(identifier)) [978-1-908843-15-9](/wiki/Special:BookSources/978-1-908843-15-9) . -49. [**^**](#cite_ref-49) *Suomen kunnallisvaakunat* (in Finnish). Suomen Kunnallisliitto. 1982. p. 147. [ISBN](/wiki/ISBN_(identifier)) [951-773-085-3](/wiki/Special:BookSources/951-773-085-3) . -50. [**^**](#cite_ref-50) ["Lubānas simbolika"](http://www.lubana.lv/index.php/lv/homepage/lubanas-pilseta-2) (in Latvian) . Retrieved September 9, 2021 . -51. [**^**](#cite_ref-51) ["Föglö"](http://digi.narc.fi/digi/view.ka?kuid=1738595) (in Swedish) . Retrieved September 9, 2021 . -52. [**^**](#cite_ref-52) Young, Emma. ["World's funniest joke revealed"](https://www.newscientist.com/article/dn2876-worlds-funniest-joke-revealed/) . *New Scientist* . Retrieved 7 January 2019 . -53. [**^**](#cite_ref-53) ["Howard the Duck (character)"](http://www.comics.org/character/name/Howard%20the%20Duck/sort/chrono/) . [*Grand Comics Database*](/wiki/Grand_Comics_Database) . -54. [**^**](#cite_ref-54) [Sanderson, Peter](/wiki/Peter_Sanderson) ; Gilbert, Laura (2008). "1970s". *Marvel Chronicle A Year by Year History* . London, United Kingdom: [Dorling Kindersley](/wiki/Dorling_Kindersley) . p. 161. [ISBN](/wiki/ISBN_(identifier)) [978-0756641238](/wiki/Special:BookSources/978-0756641238) . December saw the debut of the cigar-smoking Howard the Duck. In this story by writer Steve Gerber and artist Val Mayerik, various beings from different realities had begun turning up in the Man-Thing's Florida swamp, including this bad-tempered talking duck. -55. [**^**](#cite_ref-55) ["The Duck"](https://goducks.com/sports/2003/8/28/153778.aspx) . *University of Oregon Athletics* . Retrieved 2022-01-20 . +1. [**^**](#cite_ref-1) ["Duckling"](http://dictionary.reference.com/browse/duckling). *The American Heritage Dictionary of the English Language, Fourth Edition*. Houghton Mifflin Company. 2006. Retrieved 2015-05-22. +2. [**^**](#cite_ref-2) ["Duckling"](http://dictionary.reference.com/browse/duckling). *Kernerman English Multilingual Dictionary (Beta Version)*. K. Dictionaries Ltd. 2000-2006. Retrieved 2015-05-22. +3. [**^**](#cite_ref-3) Dohner, Janet Vorwald (2001). [*The Encyclopedia of Historic and Endangered Livestock and Poultry Breeds*](https://books.google.com/books?id=WJCTL_mC5w4C&q=male+duck+is+called+a+drake+and+the+female+is+called+a+duck&pg=PA457). Yale University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0300138139](/wiki/Special:BookSources/978-0300138139). +4. [**^**](#cite_ref-4) Visca, Curt; Visca, Kelley (2003). [*How to Draw Cartoon Birds*](https://books.google.com/books?id=VqSquCLNrZcC&q=male+duck+is+called+a+drake+and+the+female+is+called+a+duck+%28or+hen%29&pg=PA16). The Rosen Publishing Group. [ISBN](/wiki/ISBN_(identifier)) [9780823961566](/wiki/Special:BookSources/9780823961566). +5. ^ [***a***](#cite_ref-FOOTNOTECarboneras1992536_5-0) [***b***](#cite_ref-FOOTNOTECarboneras1992536_5-1) [***c***](#cite_ref-FOOTNOTECarboneras1992536_5-2) [***d***](#cite_ref-FOOTNOTECarboneras1992536_5-3) [Carboneras 1992](#CITEREFCarboneras1992), p. 536. +6. [**^**](#cite_ref-FOOTNOTELivezey1986737–738_6-0) [Livezey 1986](#CITEREFLivezey1986), pp. 737-738. +7. [**^**](#cite_ref-FOOTNOTEMadsenMcHughde_Kloet1988452_7-0) [Madsen, McHugh & de Kloet 1988](#CITEREFMadsenMcHughde_Kloet1988), p. 452. +8. [**^**](#cite_ref-FOOTNOTEDonne-GousséLaudetHänni2002353–354_8-0) [Donne-Goussé, Laudet & Hänni 2002](#CITEREFDonne-GousséLaudetHänni2002), pp. 353-354. +9. ^ [***a***](#cite_ref-FOOTNOTECarboneras1992540_9-0) [***b***](#cite_ref-FOOTNOTECarboneras1992540_9-1) [***c***](#cite_ref-FOOTNOTECarboneras1992540_9-2) [***d***](#cite_ref-FOOTNOTECarboneras1992540_9-3) [***e***](#cite_ref-FOOTNOTECarboneras1992540_9-4) [***f***](#cite_ref-FOOTNOTECarboneras1992540_9-5) [Carboneras 1992](#CITEREFCarboneras1992), p. 540. +10. [**^**](#cite_ref-FOOTNOTEElphickDunningSibley2001191_10-0) [Elphick, Dunning & Sibley 2001](#CITEREFElphickDunningSibley2001), p. 191. +11. [**^**](#cite_ref-FOOTNOTEKear2005448_11-0) [Kear 2005](#CITEREFKear2005), p. 448. +12. [**^**](#cite_ref-FOOTNOTEKear2005622–623_12-0) [Kear 2005](#CITEREFKear2005), p. 622-623. +13. [**^**](#cite_ref-FOOTNOTEKear2005686_13-0) [Kear 2005](#CITEREFKear2005), p. 686. +14. [**^**](#cite_ref-FOOTNOTEElphickDunningSibley2001193_14-0) [Elphick, Dunning & Sibley 2001](#CITEREFElphickDunningSibley2001), p. 193. +15. ^ [***a***](#cite_ref-FOOTNOTECarboneras1992537_15-0) [***b***](#cite_ref-FOOTNOTECarboneras1992537_15-1) [***c***](#cite_ref-FOOTNOTECarboneras1992537_15-2) [***d***](#cite_ref-FOOTNOTECarboneras1992537_15-3) [***e***](#cite_ref-FOOTNOTECarboneras1992537_15-4) [***f***](#cite_ref-FOOTNOTECarboneras1992537_15-5) [***g***](#cite_ref-FOOTNOTECarboneras1992537_15-6) [Carboneras 1992](#CITEREFCarboneras1992), p. 537. +16. [**^**](#cite_ref-FOOTNOTEAmerican_Ornithologists'_Union1998xix_16-0) [American Ornithologists' Union 1998](#CITEREFAmerican_Ornithologists'_Union1998), p. xix. +17. [**^**](#cite_ref-FOOTNOTEAmerican_Ornithologists'_Union1998_17-0) [American Ornithologists' Union 1998](#CITEREFAmerican_Ornithologists'_Union1998). +18. [**^**](#cite_ref-FOOTNOTECarboneras1992538_18-0) [Carboneras 1992](#CITEREFCarboneras1992), p. 538. +19. [**^**](#cite_ref-FOOTNOTEChristidisBoles200862_19-0) [Christidis & Boles 2008](#CITEREFChristidisBoles2008), p. 62. +20. [**^**](#cite_ref-FOOTNOTEShirihai2008239,_245_20-0) [Shirihai 2008](#CITEREFShirihai2008), pp. 239, 245. +21. ^ [***a***](#cite_ref-FOOTNOTEPrattBrunerBerrett198798–107_21-0) [***b***](#cite_ref-FOOTNOTEPrattBrunerBerrett198798–107_21-1) [Pratt, Bruner & Berrett 1987](#CITEREFPrattBrunerBerrett1987), pp. 98-107. +22. [**^**](#cite_ref-FOOTNOTEFitterFitterHosking200052–3_22-0) [Fitter, Fitter & Hosking 2000](#CITEREFFitterFitterHosking2000), pp. 52-3. +23. [**^**](#cite_ref-23) ["Pacific Black Duck"](http://www.wiresnr.org/pacificblackduck.html). *www.wiresnr.org*. Retrieved 2018-04-27. +24. [**^**](#cite_ref-24) Ogden, Evans. ["Dabbling Ducks"](https://www.sfu.ca/biology/wildberg/species/dabbducks.html). CWE. Retrieved 2006-11-02. +25. [**^**](#cite_ref-25) Karl Mathiesen (16 March 2015). ["Don't feed the ducks bread, say conservationists"](https://www.theguardian.com/environment/2015/mar/16/dont-feed-the-ducks-bread-say-conservationists). *The Guardian*. Retrieved 13 November 2016. +26. [**^**](#cite_ref-26) Rohwer, Frank C.; Anderson, Michael G. (1988). "Female-Biased Philopatry, Monogamy, and the Timing of Pair Formation in Migratory Waterfowl". *Current Ornithology*. pp. 187-221. [doi](/wiki/Doi_(identifier)) : [10.1007/978-1-4615-6787-5_4](https://doi.org/10.1007%2F978-1-4615-6787-5_4). [ISBN](/wiki/ISBN_(identifier)) [978-1-4615-6789-9](/wiki/Special:BookSources/978-1-4615-6789-9). +27. [**^**](#cite_ref-27) Smith, Cyndi M.; Cooke, Fred; Robertson, Gregory J.; Goudie, R. Ian; Boyd, W. Sean (2000). ["Long-Term Pair Bonds in Harlequin Ducks"](https://doi.org/10.1093%2Fcondor%2F102.1.201). *The Condor*. **102** (1): 201-205. [doi](/wiki/Doi_(identifier)) : [10.1093/condor/102.1.201](https://doi.org/10.1093%2Fcondor%2F102.1.201). [hdl](/wiki/Hdl_(identifier)) : [10315/13797](https://hdl.handle.net/10315%2F13797). +28. [**^**](#cite_ref-28) ["If You Find An Orphaned Duckling - Wildlife Rehabber"](https://web.archive.org/web/20180923152911/http://wildliferehabber.com/content/if-you-find-duckling). *wildliferehabber.com*. Archived from [the original](https://wildliferehabber.com/content/if-you-find-duckling) on 2018-09-23. Retrieved 2018-12-22. +29. [**^**](#cite_ref-29) Carver, Heather (2011). [*The Duck Bible*](https://books.google.com/books?id=VGofAwAAQBAJ&q=mallard+sound+deep+and+raspy&pg=PA39). Lulu.com. [ISBN](/wiki/ISBN_(identifier)) [9780557901562](/wiki/Special:BookSources/9780557901562). [[*self-published source*](/wiki/Wikipedia:Verifiability#Self-published_sources)] +30. [**^**](#cite_ref-30) Titlow, Budd (2013-09-03). [*Bird Brains: Inside the Strange Minds of Our Fine Feathered Friends*](https://books.google.com/books?id=fXJBBAAAQBAJ&q=Females+of+most+dabbling+ducks+make+the+classic+%22quack%22+sound+but+most+ducks+don%27t+quack&pg=PA123). Rowman & Littlefield. [ISBN](/wiki/ISBN_(identifier)) [9780762797707](/wiki/Special:BookSources/9780762797707). +31. [**^**](#cite_ref-31) Amos, Jonathan (2003-09-08). ["Sound science is quackers"](http://news.bbc.co.uk/2/hi/science/nature/3086890.stm). *BBC News*. Retrieved 2006-11-02. +32. [**^**](#cite_ref-32) ["Mythbusters Episode 8"](http://mythbustersresults.com/episode8). 12 December 2003. +33. [**^**](#cite_ref-FOOTNOTEErlandson1994171_33-0) [Erlandson 1994](#CITEREFErlandson1994), p. 171. +34. [**^**](#cite_ref-FOOTNOTEJeffries2008168,_243_34-0) [Jeffries 2008](#CITEREFJeffries2008), pp. 168, 243. +35. ^ [***a***](#cite_ref-FOOTNOTESued-Badillo200365_35-0) [***b***](#cite_ref-FOOTNOTESued-Badillo200365_35-1) [Sued-Badillo 2003](#CITEREFSued-Badillo2003), p. 65. +36. [**^**](#cite_ref-FOOTNOTEThorpe199668_36-0) [Thorpe 1996](#CITEREFThorpe1996), p. 68. +37. [**^**](#cite_ref-FOOTNOTEMaisels199942_37-0) [Maisels 1999](#CITEREFMaisels1999), p. 42. +38. [**^**](#cite_ref-FOOTNOTERau1876133_38-0) [Rau 1876](#CITEREFRau1876), p. 133. +39. [**^**](#cite_ref-FOOTNOTEHigman201223_39-0) [Higman 2012](#CITEREFHigman2012), p. 23. +40. [**^**](#cite_ref-FOOTNOTEHume201253_40-0) [Hume 2012](#CITEREFHume2012), p. 53. +41. [**^**](#cite_ref-FOOTNOTEHume201252_41-0) [Hume 2012](#CITEREFHume2012), p. 52. +42. [**^**](#cite_ref-FOOTNOTEFieldhouse2002167_42-0) [Fieldhouse 2002](#CITEREFFieldhouse2002), p. 167. +43. [**^**](#cite_ref-43) Livingston, A. D. (1998-01-01). [*Guide to Edible Plants and Animals*](https://books.google.com/books?id=NViSMffyaSgC&q=%C2%A0%C2%A0In+many+areas,+wild+ducks+of+various+species+are+hunted+for+food+or+sport). Wordsworth Editions, Limited. [ISBN](/wiki/ISBN_(identifier)) [9781853263774](/wiki/Special:BookSources/9781853263774). +44. [**^**](#cite_ref-44) ["Study plan for waterfowl injury assessment: Determining PCB concentrations in Hudson river resident waterfowl"](https://www.dec.ny.gov/docs/fish_marine_pdf/wfp09a.pdf) (PDF). *New York State Department of Environmental Conservation*. US Department of Commerce. December 2008. p. 3. [Archived](https://ghostarchive.org/archive/20221009/https://www.dec.ny.gov/docs/fish_marine_pdf/wfp09a.pdf) (PDF) from the original on 2022-10-09. Retrieved 2 July 2019. +45. [**^**](#cite_ref-45) ["FAOSTAT"](http://www.fao.org/faostat/en/#data/QL). *www.fao.org*. Retrieved 2019-10-25. +46. [**^**](#cite_ref-46) ["Anas platyrhynchos, Domestic Duck; DigiMorph Staff - The University of Texas at Austin"](http://digimorph.org/specimens/anas_platyrhynchos/skull/). Digimorph.org. Retrieved 2012-12-23. +47. [**^**](#cite_ref-47) Sy Montgomery. ["Mallard; Encyclopædia Britannica"](https://www.britannica.com/eb/topic-360302/mallard). *Britannica.com*. Retrieved 2012-12-23. +48. [**^**](#cite_ref-48) Glenday, Craig (2014). [*Guinness World Records*](https://archive.org/details/guinnessworldrec0000unse_r3e7/page/135). Guinness World Records Limited. pp. [135](https://archive.org/details/guinnessworldrec0000unse_r3e7/page/135). [ISBN](/wiki/ISBN_(identifier)) [978-1-908843-15-9](/wiki/Special:BookSources/978-1-908843-15-9). +49. [**^**](#cite_ref-49) *Suomen kunnallisvaakunat* (in Finnish). Suomen Kunnallisliitto. 1982. p. 147. [ISBN](/wiki/ISBN_(identifier)) [951-773-085-3](/wiki/Special:BookSources/951-773-085-3). +50. [**^**](#cite_ref-50) ["Lubānas simbolika"](http://www.lubana.lv/index.php/lv/homepage/lubanas-pilseta-2) (in Latvian). Retrieved September 9, 2021. +51. [**^**](#cite_ref-51) ["Föglö"](http://digi.narc.fi/digi/view.ka?kuid=1738595) (in Swedish). Retrieved September 9, 2021. +52. [**^**](#cite_ref-52) Young, Emma. ["World's funniest joke revealed"](https://www.newscientist.com/article/dn2876-worlds-funniest-joke-revealed/). *New Scientist*. Retrieved 7 January 2019. +53. [**^**](#cite_ref-53) ["Howard the Duck (character)"](http://www.comics.org/character/name/Howard%20the%20Duck/sort/chrono/). [*Grand Comics Database*](/wiki/Grand_Comics_Database). +54. [**^**](#cite_ref-54) [Sanderson, Peter](/wiki/Peter_Sanderson); Gilbert, Laura (2008). "1970s". *Marvel Chronicle A Year by Year History*. London, United Kingdom: [Dorling Kindersley](/wiki/Dorling_Kindersley). p. 161. [ISBN](/wiki/ISBN_(identifier)) [978-0756641238](/wiki/Special:BookSources/978-0756641238). December saw the debut of the cigar-smoking Howard the Duck. In this story by writer Steve Gerber and artist Val Mayerik, various beings from different realities had begun turning up in the Man-Thing's Florida swamp, including this bad-tempered talking duck. +55. [**^**](#cite_ref-55) ["The Duck"](https://goducks.com/sports/2003/8/28/153778.aspx). *University of Oregon Athletics*. Retrieved 2022-01-20. ### Sources -- American Ornithologists' Union (1998). [*Checklist of North American Birds*](https://americanornithology.org/wp-content/uploads/2019/07/AOSChecklistTin-Falcon.pdf) (PDF) . Washington, DC: American Ornithologists' Union. [ISBN](/wiki/ISBN_(identifier)) [978-1-891276-00-2](/wiki/Special:BookSources/978-1-891276-00-2) . [Archived](https://ghostarchive.org/archive/20221009/https://americanornithology.org/wp-content/uploads/2019/07/AOSChecklistTin-Falcon.pdf) (PDF) from the original on 2022-10-09. -- Carboneras, Carlos (1992). del Hoyo, Josep; Elliott, Andrew; Sargatal, Jordi (eds.). *Handbook of the Birds of the World* . Vol. 1: Ostrich to Ducks. Barcelona: Lynx Edicions. [ISBN](/wiki/ISBN_(identifier)) [978-84-87334-10-8](/wiki/Special:BookSources/978-84-87334-10-8) . -- Christidis, Les; Boles, Walter E., eds. (2008). *Systematics and Taxonomy of Australian Birds* . Collingwood, VIC: Csiro Publishing. [ISBN](/wiki/ISBN_(identifier)) [978-0-643-06511-6](/wiki/Special:BookSources/978-0-643-06511-6) . -- Donne-Goussé, Carole; Laudet, Vincent; Hänni, Catherine (July 2002). "A molecular phylogeny of Anseriformes based on mitochondrial DNA analysis". *Molecular Phylogenetics and Evolution* . **23** (3): 339-356. [Bibcode](/wiki/Bibcode_(identifier)) : [2002MolPE..23..339D](https://ui.adsabs.harvard.edu/abs/2002MolPE..23..339D) . [doi](/wiki/Doi_(identifier)) : [10.1016/S1055-7903(02)00019-2](https://doi.org/10.1016%2FS1055-7903%2802%2900019-2) . [PMID](/wiki/PMID_(identifier)) [12099792](https://pubmed.ncbi.nlm.nih.gov/12099792) . -- Elphick, Chris; Dunning, John B. Jr.; Sibley, David, eds. (2001). *The Sibley Guide to Bird Life and Behaviour* . London: Christopher Helm. [ISBN](/wiki/ISBN_(identifier)) [978-0-7136-6250-4](/wiki/Special:BookSources/978-0-7136-6250-4) . -- Erlandson, Jon M. (1994). [*Early Hunter-Gatherers of the California Coast*](https://books.google.com/books?id=nGTaBwAAQBAJ&pg=171) . New York, NY: Springer Science & Business Media. [ISBN](/wiki/ISBN_(identifier)) [978-1-4419-3231-0](/wiki/Special:BookSources/978-1-4419-3231-0) . -- Fieldhouse, Paul (2002). [*Food, Feasts, and Faith: An Encyclopedia of Food Culture in World Religions*](https://books.google.com/books?id=P-FqDgAAQBAJ&pg=PA167) . Vol. I: A-K. Santa Barbara: ABC-CLIO. [ISBN](/wiki/ISBN_(identifier)) [978-1-61069-412-4](/wiki/Special:BookSources/978-1-61069-412-4) . -- Fitter, Julian; Fitter, Daniel; Hosking, David (2000). *Wildlife of the Galápagos* . Princeton, NJ: Princeton University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-691-10295-5](/wiki/Special:BookSources/978-0-691-10295-5) . -- Higman, B. W. (2012). [*How Food Made History*](https://books.google.com/books?id=YIUoz98yMvgC&pg=RA1-PA1801) . Chichester, UK: John Wiley & Sons. [ISBN](/wiki/ISBN_(identifier)) [978-1-4051-8947-7](/wiki/Special:BookSources/978-1-4051-8947-7) . -- Hume, Julian H. (2012). [*Extinct Birds*](https://books.google.com/books?id=40sxDwAAQBAJ&pg=PA53) . London: Christopher Helm. [ISBN](/wiki/ISBN_(identifier)) [978-1-4729-3744-5](/wiki/Special:BookSources/978-1-4729-3744-5) . -- Jeffries, Richard (2008). [*Holocene Hunter-Gatherers of the Lower Ohio River Valley*](https://archive.org/details/holocenehunterga0000jeff/mode/2up) . Tuscaloosa: University of Alabama Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-8173-1658-7](/wiki/Special:BookSources/978-0-8173-1658-7) . -- Kear, Janet, ed. (2005). *Ducks, Geese and Swans: Species Accounts (* Cairina *to* Mergus *)* . Bird Families of the World. Oxford: Oxford University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-19-861009-0](/wiki/Special:BookSources/978-0-19-861009-0) . -- Livezey, Bradley C. (October 1986). ["A phylogenetic analysis of recent Anseriform genera using morphological characters"](https://sora.unm.edu/sites/default/files/journals/auk/v103n04/p0737-p0754.pdf) (PDF) . *The Auk* . **103** (4): 737-754. [doi](/wiki/Doi_(identifier)) : [10.1093/auk/103.4.737](https://doi.org/10.1093%2Fauk%2F103.4.737) . [Archived](https://ghostarchive.org/archive/20221009/https://sora.unm.edu/sites/default/files/journals/auk/v103n04/p0737-p0754.pdf) (PDF) from the original on 2022-10-09. -- Madsen, Cort S.; McHugh, Kevin P.; de Kloet, Siwo R. (July 1988). ["A partial classification of waterfowl (Anatidae) based on single-copy DNA"](https://sora.unm.edu/sites/default/files/journals/auk/v105n03/p0452-p0459.pdf) (PDF) . *The Auk* . **105** (3): 452-459. [doi](/wiki/Doi_(identifier)) : [10.1093/auk/105.3.452](https://doi.org/10.1093%2Fauk%2F105.3.452) . [Archived](https://ghostarchive.org/archive/20221009/https://sora.unm.edu/sites/default/files/journals/auk/v105n03/p0452-p0459.pdf) (PDF) from the original on 2022-10-09. -- Maisels, Charles Keith (1999). [*Early Civilizations of the Old World*](https://books.google.com/books?id=I2dgI2ijww8C&pg=PA42) . London: Routledge. [ISBN](/wiki/ISBN_(identifier)) [978-0-415-10975-8](/wiki/Special:BookSources/978-0-415-10975-8) . -- Pratt, H. Douglas; Bruner, Phillip L.; Berrett, Delwyn G. (1987). *A Field Guide to the Birds of Hawaii and the Tropical Pacific* . Princeton, NJ: Princeton University Press. [ISBN](/wiki/ISBN_(identifier)) [0-691-02399-9](/wiki/Special:BookSources/0-691-02399-9) . -- Rau, Charles (1876). [*Early Man in Europe*](https://books.google.com/books?id=9XBgAAAAIAAJ&pg=133) . New York: Harper & Brothers. [LCCN](/wiki/LCCN_(identifier)) [05040168](https://lccn.loc.gov/05040168) . -- Shirihai, Hadoram (2008). *A Complete Guide to Antarctic Wildlife* . Princeton, NJ, US: Princeton University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-691-13666-0](/wiki/Special:BookSources/978-0-691-13666-0) . -- Sued-Badillo, Jalil (2003). [*Autochthonous Societies*](https://books.google.com/books?id=zexcW7q-4LgC&pg=PA65) . General History of the Caribbean. Paris: UNESCO. [ISBN](/wiki/ISBN_(identifier)) [978-92-3-103832-7](/wiki/Special:BookSources/978-92-3-103832-7) . -- Thorpe, I. J. (1996). [*The Origins of Agriculture in Europe*](https://books.google.com/books?id=YA-EAgAAQBAJ&pg=PA68) . New York: Routledge. [ISBN](/wiki/ISBN_(identifier)) [978-0-415-08009-5](/wiki/Special:BookSources/978-0-415-08009-5) . +- American Ornithologists' Union (1998). [*Checklist of North American Birds*](https://americanornithology.org/wp-content/uploads/2019/07/AOSChecklistTin-Falcon.pdf) (PDF). Washington, DC: American Ornithologists' Union. [ISBN](/wiki/ISBN_(identifier)) [978-1-891276-00-2](/wiki/Special:BookSources/978-1-891276-00-2). [Archived](https://ghostarchive.org/archive/20221009/https://americanornithology.org/wp-content/uploads/2019/07/AOSChecklistTin-Falcon.pdf) (PDF) from the original on 2022-10-09. +- Carboneras, Carlos (1992). del Hoyo, Josep; Elliott, Andrew; Sargatal, Jordi (eds.). *Handbook of the Birds of the World*. Vol. 1: Ostrich to Ducks. Barcelona: Lynx Edicions. [ISBN](/wiki/ISBN_(identifier)) [978-84-87334-10-8](/wiki/Special:BookSources/978-84-87334-10-8). +- Christidis, Les; Boles, Walter E., eds. (2008). *Systematics and Taxonomy of Australian Birds*. Collingwood, VIC: Csiro Publishing. [ISBN](/wiki/ISBN_(identifier)) [978-0-643-06511-6](/wiki/Special:BookSources/978-0-643-06511-6). +- Donne-Goussé, Carole; Laudet, Vincent; Hänni, Catherine (July 2002). "A molecular phylogeny of Anseriformes based on mitochondrial DNA analysis". *Molecular Phylogenetics and Evolution*. **23** (3): 339-356. [Bibcode](/wiki/Bibcode_(identifier)) : [2002MolPE..23..339D](https://ui.adsabs.harvard.edu/abs/2002MolPE..23..339D). [doi](/wiki/Doi_(identifier)) : [10.1016/S1055-7903(02)00019-2](https://doi.org/10.1016%2FS1055-7903%2802%2900019-2). [PMID](/wiki/PMID_(identifier)) [12099792](https://pubmed.ncbi.nlm.nih.gov/12099792). +- Elphick, Chris; Dunning, John B. Jr.; Sibley, David, eds. (2001). *The Sibley Guide to Bird Life and Behaviour*. London: Christopher Helm. [ISBN](/wiki/ISBN_(identifier)) [978-0-7136-6250-4](/wiki/Special:BookSources/978-0-7136-6250-4). +- Erlandson, Jon M. (1994). [*Early Hunter-Gatherers of the California Coast*](https://books.google.com/books?id=nGTaBwAAQBAJ&pg=171). New York, NY: Springer Science & Business Media. [ISBN](/wiki/ISBN_(identifier)) [978-1-4419-3231-0](/wiki/Special:BookSources/978-1-4419-3231-0). +- Fieldhouse, Paul (2002). [*Food, Feasts, and Faith: An Encyclopedia of Food Culture in World Religions*](https://books.google.com/books?id=P-FqDgAAQBAJ&pg=PA167). Vol. I: A-K. Santa Barbara: ABC-CLIO. [ISBN](/wiki/ISBN_(identifier)) [978-1-61069-412-4](/wiki/Special:BookSources/978-1-61069-412-4). +- Fitter, Julian; Fitter, Daniel; Hosking, David (2000). *Wildlife of the Galápagos*. Princeton, NJ: Princeton University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-691-10295-5](/wiki/Special:BookSources/978-0-691-10295-5). +- Higman, B. W. (2012). [*How Food Made History*](https://books.google.com/books?id=YIUoz98yMvgC&pg=RA1-PA1801). Chichester, UK: John Wiley & Sons. [ISBN](/wiki/ISBN_(identifier)) [978-1-4051-8947-7](/wiki/Special:BookSources/978-1-4051-8947-7). +- Hume, Julian H. (2012). [*Extinct Birds*](https://books.google.com/books?id=40sxDwAAQBAJ&pg=PA53). London: Christopher Helm. [ISBN](/wiki/ISBN_(identifier)) [978-1-4729-3744-5](/wiki/Special:BookSources/978-1-4729-3744-5). +- Jeffries, Richard (2008). [*Holocene Hunter-Gatherers of the Lower Ohio River Valley*](https://archive.org/details/holocenehunterga0000jeff/mode/2up). Tuscaloosa: University of Alabama Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-8173-1658-7](/wiki/Special:BookSources/978-0-8173-1658-7). +- Kear, Janet, ed. (2005). *Ducks, Geese and Swans: Species Accounts (* Cairina *to* Mergus *)*. Bird Families of the World. Oxford: Oxford University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-19-861009-0](/wiki/Special:BookSources/978-0-19-861009-0). +- Livezey, Bradley C. (October 1986). ["A phylogenetic analysis of recent Anseriform genera using morphological characters"](https://sora.unm.edu/sites/default/files/journals/auk/v103n04/p0737-p0754.pdf) (PDF). *The Auk*. **103** (4): 737-754. [doi](/wiki/Doi_(identifier)) : [10.1093/auk/103.4.737](https://doi.org/10.1093%2Fauk%2F103.4.737). [Archived](https://ghostarchive.org/archive/20221009/https://sora.unm.edu/sites/default/files/journals/auk/v103n04/p0737-p0754.pdf) (PDF) from the original on 2022-10-09. +- Madsen, Cort S.; McHugh, Kevin P.; de Kloet, Siwo R. (July 1988). ["A partial classification of waterfowl (Anatidae) based on single-copy DNA"](https://sora.unm.edu/sites/default/files/journals/auk/v105n03/p0452-p0459.pdf) (PDF). *The Auk*. **105** (3): 452-459. [doi](/wiki/Doi_(identifier)) : [10.1093/auk/105.3.452](https://doi.org/10.1093%2Fauk%2F105.3.452). [Archived](https://ghostarchive.org/archive/20221009/https://sora.unm.edu/sites/default/files/journals/auk/v105n03/p0452-p0459.pdf) (PDF) from the original on 2022-10-09. +- Maisels, Charles Keith (1999). [*Early Civilizations of the Old World*](https://books.google.com/books?id=I2dgI2ijww8C&pg=PA42). London: Routledge. [ISBN](/wiki/ISBN_(identifier)) [978-0-415-10975-8](/wiki/Special:BookSources/978-0-415-10975-8). +- Pratt, H. Douglas; Bruner, Phillip L.; Berrett, Delwyn G. (1987). *A Field Guide to the Birds of Hawaii and the Tropical Pacific*. Princeton, NJ: Princeton University Press. [ISBN](/wiki/ISBN_(identifier)) [0-691-02399-9](/wiki/Special:BookSources/0-691-02399-9). +- Rau, Charles (1876). [*Early Man in Europe*](https://books.google.com/books?id=9XBgAAAAIAAJ&pg=133). New York: Harper & Brothers. [LCCN](/wiki/LCCN_(identifier)) [05040168](https://lccn.loc.gov/05040168). +- Shirihai, Hadoram (2008). *A Complete Guide to Antarctic Wildlife*. Princeton, NJ, US: Princeton University Press. [ISBN](/wiki/ISBN_(identifier)) [978-0-691-13666-0](/wiki/Special:BookSources/978-0-691-13666-0). +- Sued-Badillo, Jalil (2003). [*Autochthonous Societies*](https://books.google.com/books?id=zexcW7q-4LgC&pg=PA65). General History of the Caribbean. Paris: UNESCO. [ISBN](/wiki/ISBN_(identifier)) [978-92-3-103832-7](/wiki/Special:BookSources/978-92-3-103832-7). +- Thorpe, I. J. (1996). [*The Origins of Agriculture in Europe*](https://books.google.com/books?id=YA-EAgAAQBAJ&pg=PA68). New York: Routledge. [ISBN](/wiki/ISBN_(identifier)) [978-0-415-08009-5](/wiki/Special:BookSources/978-0-415-08009-5). ## External links @@ -587,8 +587,8 @@ Hidden categories: - [Webarchive template wayback links](/wiki/Category:Webarchive_template_wayback_links) - [Articles with Project Gutenberg links](/wiki/Category:Articles_with_Project_Gutenberg_links) - [Articles containing video clips](/wiki/Category:Articles_containing_video_clips) -- This page was last edited on 21 September 2024, at 12:11 (UTC) . -- Text is available under the [Creative Commons Attribution-ShareAlike License 4.0](//en.wikipedia.org/wiki/Wikipedia:Text_of_the_Creative_Commons_Attribution-ShareAlike_4.0_International_License) ; additional terms may apply. By using this site, you agree to the [Terms of Use](//foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Terms_of_Use) and [Privacy Policy](//foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy) . Wikipedia® is a registered trademark of the [Wikimedia Foundation, Inc.](//wikimediafoundation.org/) , a non-profit organization. +- This page was last edited on 21 September 2024, at 12:11 (UTC). +- Text is available under the [Creative Commons Attribution-ShareAlike License 4.0](//en.wikipedia.org/wiki/Wikipedia:Text_of_the_Creative_Commons_Attribution-ShareAlike_4.0_International_License); additional terms may apply. By using this site, you agree to the [Terms of Use](//foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Terms_of_Use) and [Privacy Policy](//foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy). Wikipedia® is a registered trademark of the [Wikimedia Foundation, Inc.](//wikimediafoundation.org/), a non-profit organization. - [Privacy policy](https://foundation.wikimedia.org/wiki/Special:MyLanguage/Policy:Privacy_policy) - [About Wikipedia](/wiki/Wikipedia:About) - [Disclaimers](/wiki/Wikipedia:General_disclaimer) diff --git a/crates/fleischwolf/tests/data/jats/expected/elife-56337.nxml.strict.md b/crates/fleischwolf/tests/data/jats/expected/elife-56337.nxml.strict.md index 9374d341..3abbba4e 100644 --- a/crates/fleischwolf/tests/data/jats/expected/elife-56337.nxml.strict.md +++ b/crates/fleischwolf/tests/data/jats/expected/elife-56337.nxml.strict.md @@ -174,7 +174,7 @@ Conceptualization, Resources, Supervision, Funding acquisition, Investigation, W Conceptualization, Resources, Supervision, Funding acquisition, Investigation, Methodology, Writing - original draft, Project administration, Writing - review and editing. -Animal experimentation: All studies using mice were performed in accordance to the Guide for the Care and Use of Laboratory Animals of the NIH, under IACUC animal protocol (ASP )18-026. +Animal experimentation: All studies using mice were performed in accordance to the Guide for the Care and Use of Laboratory Animals of the NIH, under IACUC animal protocol (ASP)18-026. ## Additional files diff --git a/crates/fleischwolf/tests/data/jats/expected/elife-56337.xml.strict.md b/crates/fleischwolf/tests/data/jats/expected/elife-56337.xml.strict.md index 9374d341..3abbba4e 100644 --- a/crates/fleischwolf/tests/data/jats/expected/elife-56337.xml.strict.md +++ b/crates/fleischwolf/tests/data/jats/expected/elife-56337.xml.strict.md @@ -174,7 +174,7 @@ Conceptualization, Resources, Supervision, Funding acquisition, Investigation, W Conceptualization, Resources, Supervision, Funding acquisition, Investigation, Methodology, Writing - original draft, Project administration, Writing - review and editing. -Animal experimentation: All studies using mice were performed in accordance to the Guide for the Care and Use of Laboratory Animals of the NIH, under IACUC animal protocol (ASP )18-026. +Animal experimentation: All studies using mice were performed in accordance to the Guide for the Care and Use of Laboratory Animals of the NIH, under IACUC animal protocol (ASP)18-026. ## Additional files diff --git a/crates/fleischwolf/tests/data/odf/expected/text_document_01.odt.strict.md b/crates/fleischwolf/tests/data/odf/expected/text_document_01.odt.strict.md index 8240ec45..2ffb4859 100644 --- a/crates/fleischwolf/tests/data/odf/expected/text_document_01.odt.strict.md +++ b/crates/fleischwolf/tests/data/odf/expected/text_document_01.odt.strict.md @@ -23,6 +23,6 @@ Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots ### Heading level 2: B -Contrary to popular belief, **Lorem Ipsum is not simply random text** . Richard McClintock, *a Latin professor at Hampden-Sydney College in Virginia* , looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature , discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" ( ~~The Extremes of Good and Evil~~ ) by Cicero, written in 45 BC. +Contrary to popular belief, **Lorem Ipsum is not simply random text**. Richard McClintock, *a Latin professor at Hampden-Sydney College in Virginia*, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (~~The Extremes of Good and Evil~~) by Cicero, written in 45 BC. X 2 + Y 2 = Z diff --git a/crates/fleischwolf/tests/data/odf/expected/text_document_03.odt.strict.md b/crates/fleischwolf/tests/data/odf/expected/text_document_03.odt.strict.md index ed14d009..63bcd231 100644 --- a/crates/fleischwolf/tests/data/odf/expected/text_document_03.odt.strict.md +++ b/crates/fleischwolf/tests/data/odf/expected/text_document_03.odt.strict.md @@ -19,7 +19,7 @@ Before table | A | B | C | | ~~Cell 1~~ | Cell 2 | Cell 3 | -After table with **bold** , underline , ~~strikethrough~~ , and *italic* formatting +After table with **bold**, underline, ~~strikethrough~~, and *italic* formatting ### Table with pictures diff --git a/crates/fleischwolf/tests/data/pptx/expected/powerpoint_comments.pptx.strict.md b/crates/fleischwolf/tests/data/pptx/expected/powerpoint_comments.pptx.strict.md index 6990f821..64327d06 100644 --- a/crates/fleischwolf/tests/data/pptx/expected/powerpoint_comments.pptx.strict.md +++ b/crates/fleischwolf/tests/data/pptx/expected/powerpoint_comments.pptx.strict.md @@ -8,6 +8,6 @@ Install Docling as a Python library with your favorite package manager # Features -- Import many document formats into a unified and structured Docling Document , including scanned pages via an OCR engine of your choice. +- Import many document formats into a unified and structured Docling Document, including scanned pages via an OCR engine of your choice. - Export a parsed document to formats that simplify processing and ingestion into AI, RAG, and agentic systems. - Extract document components and their properties from the Docling Document. diff --git a/crates/fleischwolf/tests/data/uspto/expected/ipa20110039701.xml.strict.md b/crates/fleischwolf/tests/data/uspto/expected/ipa20110039701.xml.strict.md index f66d1875..4809a615 100644 --- a/crates/fleischwolf/tests/data/uspto/expected/ipa20110039701.xml.strict.md +++ b/crates/fleischwolf/tests/data/uspto/expected/ipa20110039701.xml.strict.md @@ -722,7 +722,7 @@ The reaction mixture is poured onto ice, taken up in ethyl acetate and extracted The following compounds of the formula (I-c) are obtained analogously to Examples (I-c-1) and (I-c-17) and in accordance with the general statements on the preparation: -(I-c) Ex. M.p. [° C.] or ¹H-NMR (400 MHz, No. X Y Z A B M R2 CDCL₃, δ in ppm) Isomerism I-c-2 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ δ = 1.21 (d, 6 H), 1.88 and 1.98 (in anti each case mc, in each case 1 H), 3.89 (dd. 2 H), 4.81 (quint, 1H) I-c-3 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ δ =1.32 (d, 6 H), 1.92-2.13 (m, 3 H), syn 3.92 (dd, 2H), 4.83 (quint, 1 H) I-c-4 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—O—CH₂— O CH₃ 132-133 syn I-c-5 C₂H₅ CH₃ C₂H₅ ═CH₂ O C₂H₅ δ = 1.26 (t, 3H), 3.20 (mc, 1 H), 4.02 (mc, 1H), 4.82 (mc, 2 H). I-c-6 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(CH₃)₂—CH₂—O— O C₂H₅ 125-126 I-c-7 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₂—O— O C₂H₅ δ = 1.08, 1.09 and 1.22 (in each case t, in each case 3H), 3.20 (mc, 1 H), 3.89 (mc, 4 H), 4.04 (mc, 1H), 4.19 (mc, 2H) I-c-8 C₂H₅ CH₃ C₂H₅ —O—CHCH₃—CH₂—O— O C₂H₅ 79 syn/anti mixture I-c-9 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₄—O— O C₂H₅ 113 I-c-10 C₂H₅ CH₃ C₂H₅ —O—CHCH₃—CH₂—CHCH₃—O— O C₂H₅ δ = 1.02-1.28 (m, 15 H), 3.20 (mc, Isomer mixture with 1H), 3.80-4.01 (m, 3 H), 4.18 (mc, CH₃-groups at the acetal 2H) ring I-c-11 C₂H₅ CH₃ C₂H₅ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ δ = 1.08. 1.12 and 1.24 (in each case t, in each case 3 H), 4.01-4.32 (m, 7 H), 5.65 (s, 2 H) I-c-12 C₂H₅ CH₃ C₂H₅ O C₂H₅ 119 I-c-13 C₂H₅ CH₃ C₂H₅ —O—CH(CH₃)—CH₂—CH(CH₃)O— O C₂H₅ δ = 1.05-1.25 (m, 15H), 3.20 and 3.92 (R,R)-Configuration of (in each case mc, in each case 1 H), the CH₃-groups at the 4.00 (mc, 2H), 4.18 (mc, 2 H) acetal ring I-c-14 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₃—O— O C₂H₅ 110 I-c-15 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—S— O C₂H₅ δ = 1.25 (t, 3H), 2.61 (mc, 2H), 3.35 (mc, 5H), 4.19 (mc, 3H), 6.90 (s, 2H) I-c-16 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—S— O C₂H₅ δ = 1.26 (t, 3H), 2.83 (mc, 3H), 2.93 (mc, 3H), 4.20 (mc, 2H), 4.22 (mc, 1H) I-c-17 C₂H₅ CH₃ C₂H₅ ═O O C₂H₅ 1.26 (t, 3 H), 3.51 and 4.31 (in each case mc, in each case 1 H), 4.20 (mc, 2H) I-c-18 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—C(CH₃)₂—O— O C₂H₅ 116-117 I-c-19 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—O— O C₂H₅ 1.24 (t, 3H), 3.00 (mc, 2H), 3.72 (mc, syn/anti mixture 2H), 4.18 (mc, 1H) I-c-20 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—S— O CH₃ 2.62 (mc, 1H), 2.80-2.98 (m, 5H), 3.49 (mc, 1H), 3.78 (s, 1H), 4.23 (mc, 1H) I-c-21 C₂H₅ CH₃ C₂H₅ —O—CH₂—CH═CH—CH₂—O— O CH₃ 1.08 and 1.12 (in each case t, in each case 3H), 3.75 (s, 3H), 4.02 (mc, 2H), 4.16-4.32 (m, 3H), 5.67 (s, 2H) I-c-22 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(CH₃)₂—CH₂—O— O C₂H₅ 98-99 I-c-23 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(CH₃)₂—CH₂—O— O CH₃ 126-127 I-c-24 C₂H₅ CH₃ C₂H₅ —O—CH(CH₃)—CH₂—CH(CH₃)O— O CH₃ 1.03-1.22 (m, 12H), 3.20 (mc, 1H), (R,R)-Configuration of 3.75 (doubled singlet, Σ 3H), 3.90- the CH₃-groups at the 4.02 (m, 3H) acetal ring I-c-25 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(OCH₃)—CH₂—O— O C₂H₅ 1.23 (t, 3H), 2.70-2.79 (m, 1H), 4.19 (mc, 2H), 3.10 (mc, 1H), 3.38 (s, 3H), I-c-26 C₂H₅ CH₃ C₂H₅ —O—CH₂CH(OC₂H₅)CH₂—O— O C₂H₅ 1.03-1.28 (m, 12H); 3.20 and 3.39 (in each case mc, in each case 1H), 3.95- 4.05 (m, 2H), 4.11-4.25 (m, 3H) I-c-27 C₂H₅ CH₃ C₂H₅ —OCH₂—CH(OC₂H₅)CH₂—O— O CH₃ 1.00-1.21 (m, 12H), 3.76 (s, 3H), 3.92- 4.05 (m, 2H), 4.21 (mc, 1H) I-c-28 C₂H₅ CH₃ C₂H₅ —OCH₂—CH(OCH₂C₆H₅)CH₂—O— O C₂H₅ 1.22 (t, 3H), 2.95 (mc, 2H), 4.15 (mc, 2H), 4.55 (s, 2H), 6.88 and 6.91 (in each case s, in each case 1H), 7.27- 7.85 (m, 5H) I-c-29 C₂H₅ CH₃ C₂H₅ —OCH₂—CH(OCH₂C₆H₅)CH₂—O— O CH₃ 2.05-2.12 (m, 2H), 3.41 (mc, 1H), 3.74 (s, 3H), 4.60 (s, 2H), I-c-30 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—O— O C₂H₅ 94-95 syn/anti mixture I-c-31 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—O— O CH₃ 3.00 (mc, 2H), 3.77 (s, 3H), 3.96 (mc, syn/anti mixture 1H), 4.02-4.10 (m, 2H) I-c-32 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—O— O CH₃ 2.95-3.05 (m, 2H), 3.25 (mc, 1H), 3.72 syn/anti mixture (mc, 2H), 3.75 (s, 3H), 4.08 (mc, 1H) I-c-33 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—O— O i-C₃H₇ 1.23 (6H), 3.01 (mc, 2H), 4.08 (mc, syn/anti mixture 2H), 4.81 (mc, 1H) I-c-34 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₃—O— O i-C₃H₇ 1.22 (mc, 6H), 3.18 (mc, 1H), 3.79 (mc, 2H), 3.88 (mc, 2H), 3.99, (mc, 1H), 4.81 (hept, 1H) I-c-35 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₃—O— O CH₃ 2.00-2.12 (m, 2H), 3.19 (mc, 1H), 3.73 (s, 3H), 3.88 (mc, 1H), 3.99 (mc, 1H) I-c-36 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₂—O— O i-C₃H₇ 110-111 I-c-37 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₂—O— O CH₃ 116 I-c-38 C₂H₅ CH₃ C₂H₅ ═NOtC₄H₉ O C₂H₅ 1.24 (s, 9H), 1.28 (mc, 3H), 2.62-2.90 (m, 4H), 4.15 (mc, 1H), 4.20 (mc, 2H) I-c-39 C₂H₅ CH₃ C₂H₅ ═NOi-C₃H₇ O C₂H₅ 1.03 (mc, 6H), 1.15-1.30 (m, 9H), 2.35 (hept, 2H), 3.32 (mc, 1H), 4.20 (mc, 2H), 4.25 (mc, 1H) I-c-39 C₂H₅ CH₃ C₂H₅ ═NOCyclopentyl O C₂H₅ 1.52-1.80 (m, 8H), 3.30 (mc, 1H), 4.12-4.22 (m, 3H), 4.62 (mc, 1H) I-c-40 C₂H₅ CH₃ C₂H₅ ═NOCH₂-cyclopropyl O C₂H₅ 0.23 and 0.51 (in each case mc, in each case 2H), 3.19-3.49 (m, 1H), 3.82 (mc, 2H), 4.12-4.24 (m, 3H) I-c-41 C₂H₅ CH₃ C₂H₅ ═NOCH₂C≡CH O C₂H₅ 1.25 (mc, 3H), 2.47 (mc, 1H), 4.15- 4.25 (m, 3H), 4.61 (d, 2H) I-c-42 C₂H₅ CH₃ C₂H₅ O═ O CH₃ 2.60-2.85 (m, 3H), 3.51 (mc, 1H), 3.79 (s, 3H), 4.30 (mc, 1H) I-c-43 C₂H₅ CH₃ C₂H₅ ═NOCH(CH₃)—C≡CH O C₂H₅ 1.28 (t, 3H), 1.48 (mc, 3H), 2.43 (mc, 1H), 3.34 (mc, 1H), 4.80 (mc, 1H) I-c-44 CH₃ CH₃ CH₃ —O—(CH₂)₂—O— O C₂H₅ 1.21 (t, 3H), 2.05, 2.12 and 2.22 (in each case s, in each case 3H), 3.19 (mc, 1H), 3.89 (mc, 4H), 3.91 (mc, 1H), 4.12 (mc, 2H) I-c-45 CH₃ CH₃ CH₃ CH₂═ O C₂H₅ 1.21 (t, 3H), 1.98, 2.06 and 2.24 (in each case s, in each case 3H), 4.15 (mc, 2H), 4.90 (mc, 2H) I-c-46 CH₃ CH₃ CH₃ CH₂═ O CH₃ 1.99, 2.05 and 2.22 (in each case s, in each case 3H), 2.40-2.72 (m, 4H), 3.72 (s, 3H), 4.90 (mc, 2H) I-c-47 CH₃ CH₃ CH₃ —O—(CH₂)₃—O— O C₂H₅ 1.20 (t, 3H), 2.80 (mc, 1H), 3.16 (mc, 1H), 3.70-3.90 (m, 5H), 4.12 (mc, 2H) I-c-48 CH₃ CH₃ CH₃ —O—CH₂—CH(CH₃)—CH₂—O O C₂H₅ 0.71 and 0.82 (in each case d, Σ 3H), 2.45-2.50 (m, 1H), 3.28-3.45 (m, 2H), 4.12 (mc, 2H) I-c-49 CH₃ CH₃ CH₃ —O—(CH₂)₄—O— O CH₃ 122 I-c-50 CH₃ CH₃ CH₃ —O—(CH₂)₄—O— O C₂H₅ 131 I-c-51 CH₃ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ 1.21 (t, 3H), 4.00-4.31 (m, 6H), 5.65 (mc, 2H), 6.85 (mc, 2H) I-c-52 CH₃ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O CH₃ 3.70 (s, 3H), 3.94 (mc, 1H), 3.96-4.30 (m, 4H), 5.64 (mc, 2H) I-c-53 CH₃ CH₃ CH₃ —O—CH₂—CH(CH₃)—CH₂—O— O CH₃ 0.70 and 0.82 (in each case t, Σ 3H), 2.48 (mc, 1H), 3.15 (mc, 1H), 3.29- 3.45 (m, 2H), 3.71 (s, 3H) I-c-54 CH₃ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O C₂H₅ 1.20 (t, 3H), 1.48 (s, 6H), 3.34 (mc, syn/anti mixture 1H), 3.85 and 3.89 (in each case d, in each case 1H), 4.12 (q, 2H) I-c-55 CH₃ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ 1.15 and 1.19 (in each case d, Σ 6H), syn/anti mixture 1.38 (s, 6H), 3.85 and 3.90 (in each case d, in each case 1H), 4.72 (hept, 1H) I-c-56 CH₃ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O CH₃ 1.38 (s, 6H), 3.36 (mc, 1H), 3.71 (s, syn/anti mixture 3H), 4.00 (mc, 1H) I-c-57 CH₃ CH₃ CH₃ ═O O CH₃ 1.98, 2.10 and 2.26 (in each case s, in each case 3H), 3.50 (mc, 1H), 3.75 (s, 3H), 4.19 (mc, 1H) I-c-58 CH₃ CH₃ CH₃ ═O O C₂H₅ 1.22 (t, 3H), 2.00, 2.11 and 2.26 (in each case s, in each case 3H), 2.42- 2.85 (m, 4H), 4.10-4.22 (3H), I-c-59 CH₃ CH₃ CH₃ ═NOCH₂C≡CH O CH₃ 2.45 (mc, 1H), 2.70-3.08 (m, 4H), 3.75 (s, 3H), 4.61 (mc, 2H), I-c-60 CH₃ CH₃ CH₃ ═NOCH₂C≡CH O C₂H₅ 1.23 (mc, 3H), 2.44 (mc, 1H), 2.70- 3.08 (m, 4H), 4.18 (mc, 2H), 4.61 (mc, 2H) I-c-61 OCH₃ CH₃ CH₃ CH₂═ O C₂H₅ 2.30 (s, 3H), 2.39-2.70 (m, 4H), 3.70 (s, 3H), 4.18 (mc, 2H) I-c-62 OCH₃ CH₃ CH₃ CH₂═ O CH₃ 2.38-2.70 (m, 4H), 3.70 and 3.75 (in each case s, in each case 1H), 4.89 (mc, 2H) I-c-62 OCH₃ CH₃ CH₃ O═ O C₂H₅ 1.25 (mc, 3H), 2.30(s, 3H), 2.40-2.85 (m, 4H), 3.50 (mc, 1H), 4.10 (mc, 2H) I-c-63 OCH₃ CH₃ CH₃ —O—(CH₂)₃—O— O C₂H₅ 1.22 (t, 3H), 2.09 and 2.29 (in each case s, in each case 3H), 2.76-2.80 (m, 1H), 3.18 (mc, 1H), 3.70 (s, 3H) I-c-64 OCH₃ CH₃ CH₃ —O—(CH₂)₂—O— O C₂H₅ 21.12 and 2.30 (in each case s, in each case 3H), 3.70 (s, 3H), 3.85 (mc, 4H), 4.18 (q, 2H) I-c-65 OCH₃ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ 1.25 (t, 3H), 3.70 (s, 3H), 3.86-430 (m, 7H), 5.64 (mc, 2H) I-c-66 OCH₃ CH₃ CH₃ —O—(CH₂)₄—O— O C₂H₅ 1.22 (t, 3H), 2.22 and 2.30 (in each case s, in each case 3H), 3.12 (mc, 1H), 3.70 (s, 3H), 4.16 (q, 2H) I-c-67 OCH₃ CH₃ C₂H₅ CH₂═ O C₂H₅ 0.99 and 1.08 (in each case t, Σ 3H), 1.26 (mc, 3H), 3.61 and 3.68 (in each case s, Σ 3H), 4.89 (mc, 2H) . I-c-68 OCH₃ CH₃ C₂H₅ O═ O C₂H₅ 1.05 and 1.11 (in each case t, Σ 3H), 1.26 (mc, 3H), 2.25-2.83 (m, 4H), 2.30 (s, 3H), 4.20 (mc, 2H) I-c-69 OCH₃ CH₃ C₂H₅ —O—(CH₂)₂—O— O C₂H₅ 1.09 (t, 3H), 1.24 (t, 3H), 2.31 (s, 3H), 3.70 (s, 3H), 3.88 (mc, 4H), 4.19 (q, 2H) I-c-70 OCH₃ CH₃ C₂H₅ —O—(CH₂)₃—O— O C₂H₅ 1.10 and 1.15 (in each case t, in each case 3H), 3.70 (s, 3H), 3.70-4.00 (m, 4H), 4.18 (q, 2H) I-c-71 C₂H₅ CH₃ CH₃ —O—(CH₂)₂—O— O C₂H₅ 1.08 and 1.22 (in each case t, in each case 3H), 3.88 (mc, 4H), 3.96 (mc, 1H), 4.15 (mc, 2H) I-c-72 C₂H₅ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ 124-125 I-c-73 C₂H₅ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O CH₃ 1.08 (t, 3H), 3.18 (mc, 1H), 3.71 (s, 3H), 3.95-4.31 (m, 5H), 5.65 (mc, 2H) I-c-74 C₂H₅ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O i-C₃H₇ 1.20 (mc, 6H), 3.91-4.32 (m, 5H), 4.79 (hept, 1H), 5.64 (mc, 2H) I-c-75 C₂H₅ CH₃ CH₃ —O—(CH₂)₄—O— O C₂H₅ 102 I-c-76 C₂H₅ CH₃ CH₃ CH₂═ O C₂H₅ 0.96 and 1.08 (in each case t, Σ 3H), 1.22 (t, 3H), 2.26 (s, 3H), 4.15 (mc, 2H), 4.91 (mc, 1H) I-c-77 C₂H₅ CH₃ CH₃ CH₂═ O CH₃ 0.97 and 1.05 (in each case t, Σ 3H), 3.75 (s, 3H), 4.92 (mc, 2H) I-c-78 C₂H₅ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ 116-117 syn/anti mixture I-c-79 C₂H₅ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O CH₃ 1.02-1.11 (m, 3H), 1.38 (s, 6H), 3.74 syn/anti mixture (s, 3H), 3.85 and 3.88 (in each case d, in each case 1H) I-c-80 C₂H₅ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O C₂H₅ 1.20 (t, 3H), 1.38 (s, 6H), 2.30 (s, 3H), syn/anti mixture 3.86 and 4.00 (in each case d, in each case 1H), 4.15 (mc, 2H) I-c-81 C₂H₅ C₂H₅ C₂H₅ CH₂═ O C₂H₅ 0.98 and 1.07 (in each case t, in each case 3H), 1.22-1.29 (m, 6H), 4.20 (mc, 2H), 4.92 (mc, 2H) I-c-82 C₂H₅ C₂H₅ C₂H₅ O═ O C₂H₅ 103 I-c-83 C₂H₅ C₂H₅ C₂H₅ —O—(CH₂)₃—O— O C₂H₅ 122 I-c-84 C₂H₅ C₂H₅ C₂H₅ —O—(CH₂)₂—O— O C₂H₅ 98 I-c-85 C₂H₅ CH₃ H —O—(CH₂)₃—O— O C₂H₅ I-c-86 C₂H₅ CH₃ H —O—(CH₂)₃—O— O CH₃ 1-c-87 C₂H₅ CH₃ H —O—(CH₂)₄—O— O C₂H₅ I-c-88 C₂H₅ CH₃ H —O—(CH₂)₂—O— O C₂H₅ I-c-89 C₂H₅ CH₃ C₂H₅ —O—CH(CH₃)—CH₂—CH₂—O— O C₂H₅ 1.05-1.28 (m, 12H), 2.32 (s, 3H), 3.70- syn/anti mixture 4.05 (m, 4H), 4.18 (mc, 2H) +(I-c) Ex. M.p. [° C.] or ¹H-NMR (400 MHz, No. X Y Z A B M R2 CDCL₃, δ in ppm) Isomerism I-c-2 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ δ = 1.21 (d, 6 H), 1.88 and 1.98 (in anti each case mc, in each case 1 H), 3.89 (dd. 2 H), 4.81 (quint, 1H) I-c-3 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ δ =1.32 (d, 6 H), 1.92-2.13 (m, 3 H), syn 3.92 (dd, 2H), 4.83 (quint, 1 H) I-c-4 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—O—CH₂— O CH₃ 132-133 syn I-c-5 C₂H₅ CH₃ C₂H₅ ═CH₂ O C₂H₅ δ = 1.26 (t, 3H), 3.20 (mc, 1 H), 4.02 (mc, 1H), 4.82 (mc, 2 H). I-c-6 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(CH₃)₂—CH₂—O— O C₂H₅ 125-126 I-c-7 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₂—O— O C₂H₅ δ = 1.08, 1.09 and 1.22 (in each case t, in each case 3H), 3.20 (mc, 1 H), 3.89 (mc, 4 H), 4.04 (mc, 1H), 4.19 (mc, 2H) I-c-8 C₂H₅ CH₃ C₂H₅ —O—CHCH₃—CH₂—O— O C₂H₅ 79 syn/anti mixture I-c-9 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₄—O— O C₂H₅ 113 I-c-10 C₂H₅ CH₃ C₂H₅ —O—CHCH₃—CH₂—CHCH₃—O— O C₂H₅ δ = 1.02-1.28 (m, 15 H), 3.20 (mc, Isomer mixture with 1H), 3.80-4.01 (m, 3 H), 4.18 (mc, CH₃-groups at the acetal 2H) ring I-c-11 C₂H₅ CH₃ C₂H₅ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ δ = 1.08. 1.12 and 1.24 (in each case t, in each case 3 H), 4.01-4.32 (m, 7 H), 5.65 (s, 2 H) I-c-12 C₂H₅ CH₃ C₂H₅ O C₂H₅ 119 I-c-13 C₂H₅ CH₃ C₂H₅ —O—CH(CH₃)—CH₂—CH(CH₃)O— O C₂H₅ δ = 1.05-1.25 (m, 15H), 3.20 and 3.92 (R,R)-Configuration of (in each case mc, in each case 1 H), the CH₃-groups at the 4.00 (mc, 2H), 4.18 (mc, 2 H) acetal ring I-c-14 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₃—O— O C₂H₅ 110 I-c-15 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—S— O C₂H₅ δ = 1.25 (t, 3H), 2.61 (mc, 2H), 3.35 (mc, 5H), 4.19 (mc, 3H), 6.90 (s, 2H) I-c-16 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—S— O C₂H₅ δ = 1.26 (t, 3H), 2.83 (mc, 3H), 2.93 (mc, 3H), 4.20 (mc, 2H), 4.22 (mc, 1H) I-c-17 C₂H₅ CH₃ C₂H₅ ═O O C₂H₅ 1.26 (t, 3 H), 3.51 and 4.31 (in each case mc, in each case 1 H), 4.20 (mc, 2H) I-c-18 C₂H₅ CH₃ C₂H₅ —O—C(CH₃)₂—C(CH₃)₂—O— O C₂H₅ 116-117 I-c-19 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—O— O C₂H₅ 1.24 (t, 3H), 3.00 (mc, 2H), 3.72 (mc, syn/anti mixture 2H), 4.18 (mc, 1H) I-c-20 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—S— O CH₃ 2.62 (mc, 1H), 2.80-2.98 (m, 5H), 3.49 (mc, 1H), 3.78 (s, 1H), 4.23 (mc, 1H) I-c-21 C₂H₅ CH₃ C₂H₅ —O—CH₂—CH═CH—CH₂—O— O CH₃ 1.08 and 1.12 (in each case t, in each case 3H), 3.75 (s, 3H), 4.02 (mc, 2H), 4.16-4.32 (m, 3H), 5.67 (s, 2H) I-c-22 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(CH₃)₂—CH₂—O— O C₂H₅ 98-99 I-c-23 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(CH₃)₂—CH₂—O— O CH₃ 126-127 I-c-24 C₂H₅ CH₃ C₂H₅ —O—CH(CH₃)—CH₂—CH(CH₃)O— O CH₃ 1.03-1.22 (m, 12H), 3.20 (mc, 1H), (R,R)-Configuration of 3.75 (doubled singlet, Σ 3H), 3.90- the CH₃-groups at the 4.02 (m, 3H) acetal ring I-c-25 C₂H₅ CH₃ C₂H₅ —O—CH₂—C(OCH₃)—CH₂—O— O C₂H₅ 1.23 (t, 3H), 2.70-2.79 (m, 1H), 4.19 (mc, 2H), 3.10 (mc, 1H), 3.38 (s, 3H), I-c-26 C₂H₅ CH₃ C₂H₅ —O—CH₂CH(OC₂H₅)CH₂—O— O C₂H₅ 1.03-1.28 (m, 12H); 3.20 and 3.39 (in each case mc, in each case 1H), 3.95- 4.05 (m, 2H), 4.11-4.25 (m, 3H) I-c-27 C₂H₅ CH₃ C₂H₅ —OCH₂—CH(OC₂H₅)CH₂—O— O CH₃ 1.00-1.21 (m, 12H), 3.76 (s, 3H), 3.92- 4.05 (m, 2H), 4.21 (mc, 1H) I-c-28 C₂H₅ CH₃ C₂H₅ —OCH₂—CH(OCH₂C₆H₅)CH₂—O— O C₂H₅ 1.22 (t, 3H), 2.95 (mc, 2H), 4.15 (mc, 2H), 4.55 (s, 2H), 6.88 and 6.91 (in each case s, in each case 1H), 7.27- 7.85 (m, 5H) I-c-29 C₂H₅ CH₃ C₂H₅ —OCH₂—CH(OCH₂C₆H₅)CH₂—O— O CH₃ 2.05-2.12 (m, 2H), 3.41 (mc, 1H), 3.74 (s, 3H), 4.60 (s, 2H), I-c-30 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—O— O C₂H₅ 94-95 syn/anti mixture I-c-31 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—O— O CH₃ 3.00 (mc, 2H), 3.77 (s, 3H), 3.96 (mc, syn/anti mixture 1H), 4.02-4.10 (m, 2H) I-c-32 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₃—O— O CH₃ 2.95-3.05 (m, 2H), 3.25 (mc, 1H), 3.72 syn/anti mixture (mc, 2H), 3.75 (s, 3H), 4.08 (mc, 1H) I-c-33 C₂H₅ CH₃ C₂H₅ —S—(CH₂)₂—O— O i-C₃H₇ 1.23 (6H), 3.01 (mc, 2H), 4.08 (mc, syn/anti mixture 2H), 4.81 (mc, 1H) I-c-34 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₃—O— O i-C₃H₇ 1.22 (mc, 6H), 3.18 (mc, 1H), 3.79 (mc, 2H), 3.88 (mc, 2H), 3.99, (mc, 1H), 4.81 (hept, 1H) I-c-35 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₃—O— O CH₃ 2.00-2.12 (m, 2H), 3.19 (mc, 1H), 3.73 (s, 3H), 3.88 (mc, 1H), 3.99 (mc, 1H) I-c-36 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₂—O— O i-C₃H₇ 110-111 I-c-37 C₂H₅ CH₃ C₂H₅ —O—(CH₂)₂—O— O CH₃ 116 I-c-38 C₂H₅ CH₃ C₂H₅ ═NOtC₄H₉ O C₂H₅ 1.24 (s, 9H), 1.28 (mc, 3H), 2.62-2.90 (m, 4H), 4.15 (mc, 1H), 4.20 (mc, 2H) I-c-39 C₂H₅ CH₃ C₂H₅ ═NOi-C₃H₇ O C₂H₅ 1.03 (mc, 6H), 1.15-1.30 (m, 9H), 2.35 (hept, 2H), 3.32 (mc, 1H), 4.20 (mc, 2H), 4.25 (mc, 1H) I-c-39 C₂H₅ CH₃ C₂H₅ ═NOCyclopentyl O C₂H₅ 1.52-1.80 (m, 8H), 3.30 (mc, 1H), 4.12-4.22 (m, 3H), 4.62 (mc, 1H) I-c-40 C₂H₅ CH₃ C₂H₅ ═NOCH₂-cyclopropyl O C₂H₅ 0.23 and 0.51 (in each case mc, in each case 2H), 3.19-3.49 (m, 1H), 3.82 (mc, 2H), 4.12-4.24 (m, 3H) I-c-41 C₂H₅ CH₃ C₂H₅ ═NOCH₂C≡CH O C₂H₅ 1.25 (mc, 3H), 2.47 (mc, 1H), 4.15- 4.25 (m, 3H), 4.61 (d, 2H) I-c-42 C₂H₅ CH₃ C₂H₅ O═ O CH₃ 2.60-2.85 (m, 3H), 3.51 (mc, 1H), 3.79 (s, 3H), 4.30 (mc, 1H) I-c-43 C₂H₅ CH₃ C₂H₅ ═NOCH(CH₃)—C≡CH O C₂H₅ 1.28 (t, 3H), 1.48 (mc, 3H), 2.43 (mc, 1H), 3.34 (mc, 1H), 4.80 (mc, 1H) I-c-44 CH₃ CH₃ CH₃ —O—(CH₂)₂—O— O C₂H₅ 1.21 (t, 3H), 2.05, 2.12 and 2.22 (in each case s, in each case 3H), 3.19 (mc, 1H), 3.89 (mc, 4H), 3.91 (mc, 1H), 4.12 (mc, 2H) I-c-45 CH₃ CH₃ CH₃ CH₂═ O C₂H₅ 1.21 (t, 3H), 1.98, 2.06 and 2.24 (in each case s, in each case 3H), 4.15 (mc, 2H), 4.90 (mc, 2H) I-c-46 CH₃ CH₃ CH₃ CH₂═ O CH₃ 1.99, 2.05 and 2.22 (in each case s, in each case 3H), 2.40-2.72 (m, 4H), 3.72 (s, 3H), 4.90 (mc, 2H) I-c-47 CH₃ CH₃ CH₃ —O—(CH₂)₃—O— O C₂H₅ 1.20 (t, 3H), 2.80 (mc, 1H), 3.16 (mc, 1H), 3.70-3.90 (m, 5H), 4.12 (mc, 2H) I-c-48 CH₃ CH₃ CH₃ —O—CH₂—CH(CH₃)—CH₂—O O C₂H₅ 0.71 and 0.82 (in each case d, Σ 3H), 2.45-2.50 (m, 1H), 3.28-3.45 (m, 2H), 4.12 (mc, 2H) I-c-49 CH₃ CH₃ CH₃ —O—(CH₂)₄—O— O CH₃ 122 I-c-50 CH₃ CH₃ CH₃ —O—(CH₂)₄—O— O C₂H₅ 131 I-c-51 CH₃ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ 1.21 (t, 3H), 4.00-4.31 (m, 6H), 5.65 (mc, 2H), 6.85 (mc, 2H) I-c-52 CH₃ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O CH₃ 3.70 (s, 3H), 3.94 (mc, 1H), 3.96-4.30 (m, 4H), 5.64 (mc, 2H) I-c-53 CH₃ CH₃ CH₃ —O—CH₂—CH(CH₃)—CH₂—O— O CH₃ 0.70 and 0.82 (in each case t, Σ 3H), 2.48 (mc, 1H), 3.15 (mc, 1H), 3.29- 3.45 (m, 2H), 3.71 (s, 3H) I-c-54 CH₃ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O C₂H₅ 1.20 (t, 3H), 1.48 (s, 6H), 3.34 (mc, syn/anti mixture 1H), 3.85 and 3.89 (in each case d, in each case 1H), 4.12 (q, 2H) I-c-55 CH₃ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ 1.15 and 1.19 (in each case d, Σ 6H), syn/anti mixture 1.38 (s, 6H), 3.85 and 3.90 (in each case d, in each case 1H), 4.72 (hept, 1H) I-c-56 CH₃ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O CH₃ 1.38 (s, 6H), 3.36 (mc, 1H), 3.71 (s, syn/anti mixture 3H), 4.00 (mc, 1H) I-c-57 CH₃ CH₃ CH₃ ═O O CH₃ 1.98, 2.10 and 2.26 (in each case s, in each case 3H), 3.50 (mc, 1H), 3.75 (s, 3H), 4.19 (mc, 1H) I-c-58 CH₃ CH₃ CH₃ ═O O C₂H₅ 1.22 (t, 3H), 2.00, 2.11 and 2.26 (in each case s, in each case 3H), 2.42- 2.85 (m, 4H), 4.10-4.22 (3H), I-c-59 CH₃ CH₃ CH₃ ═NOCH₂C≡CH O CH₃ 2.45 (mc, 1H), 2.70-3.08 (m, 4H), 3.75 (s, 3H), 4.61 (mc, 2H), I-c-60 CH₃ CH₃ CH₃ ═NOCH₂C≡CH O C₂H₅ 1.23 (mc, 3H), 2.44 (mc, 1H), 2.70- 3.08 (m, 4H), 4.18 (mc, 2H), 4.61 (mc, 2H) I-c-61 OCH₃ CH₃ CH₃ CH₂═ O C₂H₅ 2.30 (s, 3H), 2.39-2.70 (m, 4H), 3.70 (s, 3H), 4.18 (mc, 2H) I-c-62 OCH₃ CH₃ CH₃ CH₂═ O CH₃ 2.38-2.70 (m, 4H), 3.70 and 3.75 (in each case s, in each case 1H), 4.89 (mc, 2H) I-c-62 OCH₃ CH₃ CH₃ O═ O C₂H₅ 1.25 (mc, 3H), 2.30(s, 3H), 2.40-2.85 (m, 4H), 3.50 (mc, 1H), 4.10 (mc, 2H) I-c-63 OCH₃ CH₃ CH₃ —O—(CH₂)₃—O— O C₂H₅ 1.22 (t, 3H), 2.09 and 2.29 (in each case s, in each case 3H), 2.76-2.80 (m, 1H), 3.18 (mc, 1H), 3.70 (s, 3H) I-c-64 OCH₃ CH₃ CH₃ —O—(CH₂)₂—O— O C₂H₅ 21.12 and 2.30 (in each case s, in each case 3H), 3.70 (s, 3H), 3.85 (mc, 4H), 4.18 (q, 2H) I-c-65 OCH₃ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ 1.25 (t, 3H), 3.70 (s, 3H), 3.86-430 (m, 7H), 5.64 (mc, 2H) I-c-66 OCH₃ CH₃ CH₃ —O—(CH₂)₄—O— O C₂H₅ 1.22 (t, 3H), 2.22 and 2.30 (in each case s, in each case 3H), 3.12 (mc, 1H), 3.70 (s, 3H), 4.16 (q, 2H) I-c-67 OCH₃ CH₃ C₂H₅ CH₂═ O C₂H₅ 0.99 and 1.08 (in each case t, Σ 3H), 1.26 (mc, 3H), 3.61 and 3.68 (in each case s, Σ 3H), 4.89 (mc, 2H). I-c-68 OCH₃ CH₃ C₂H₅ O═ O C₂H₅ 1.05 and 1.11 (in each case t, Σ 3H), 1.26 (mc, 3H), 2.25-2.83 (m, 4H), 2.30 (s, 3H), 4.20 (mc, 2H) I-c-69 OCH₃ CH₃ C₂H₅ —O—(CH₂)₂—O— O C₂H₅ 1.09 (t, 3H), 1.24 (t, 3H), 2.31 (s, 3H), 3.70 (s, 3H), 3.88 (mc, 4H), 4.19 (q, 2H) I-c-70 OCH₃ CH₃ C₂H₅ —O—(CH₂)₃—O— O C₂H₅ 1.10 and 1.15 (in each case t, in each case 3H), 3.70 (s, 3H), 3.70-4.00 (m, 4H), 4.18 (q, 2H) I-c-71 C₂H₅ CH₃ CH₃ —O—(CH₂)₂—O— O C₂H₅ 1.08 and 1.22 (in each case t, in each case 3H), 3.88 (mc, 4H), 3.96 (mc, 1H), 4.15 (mc, 2H) I-c-72 C₂H₅ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O C₂H₅ 124-125 I-c-73 C₂H₅ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O CH₃ 1.08 (t, 3H), 3.18 (mc, 1H), 3.71 (s, 3H), 3.95-4.31 (m, 5H), 5.65 (mc, 2H) I-c-74 C₂H₅ CH₃ CH₃ —O—CH₂—CH═CH—CH₂—O— O i-C₃H₇ 1.20 (mc, 6H), 3.91-4.32 (m, 5H), 4.79 (hept, 1H), 5.64 (mc, 2H) I-c-75 C₂H₅ CH₃ CH₃ —O—(CH₂)₄—O— O C₂H₅ 102 I-c-76 C₂H₅ CH₃ CH₃ CH₂═ O C₂H₅ 0.96 and 1.08 (in each case t, Σ 3H), 1.22 (t, 3H), 2.26 (s, 3H), 4.15 (mc, 2H), 4.91 (mc, 1H) I-c-77 C₂H₅ CH₃ CH₃ CH₂═ O CH₃ 0.97 and 1.05 (in each case t, Σ 3H), 3.75 (s, 3H), 4.92 (mc, 2H) I-c-78 C₂H₅ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O i-C₃H₇ 116-117 syn/anti mixture I-c-79 C₂H₅ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O CH₃ 1.02-1.11 (m, 3H), 1.38 (s, 6H), 3.74 syn/anti mixture (s, 3H), 3.85 and 3.88 (in each case d, in each case 1H) I-c-80 C₂H₅ CH₃ CH₃ —O—C(CH₃)₂—O—CH₂— O C₂H₅ 1.20 (t, 3H), 1.38 (s, 6H), 2.30 (s, 3H), syn/anti mixture 3.86 and 4.00 (in each case d, in each case 1H), 4.15 (mc, 2H) I-c-81 C₂H₅ C₂H₅ C₂H₅ CH₂═ O C₂H₅ 0.98 and 1.07 (in each case t, in each case 3H), 1.22-1.29 (m, 6H), 4.20 (mc, 2H), 4.92 (mc, 2H) I-c-82 C₂H₅ C₂H₅ C₂H₅ O═ O C₂H₅ 103 I-c-83 C₂H₅ C₂H₅ C₂H₅ —O—(CH₂)₃—O— O C₂H₅ 122 I-c-84 C₂H₅ C₂H₅ C₂H₅ —O—(CH₂)₂—O— O C₂H₅ 98 I-c-85 C₂H₅ CH₃ H —O—(CH₂)₃—O— O C₂H₅ I-c-86 C₂H₅ CH₃ H —O—(CH₂)₃—O— O CH₃ 1-c-87 C₂H₅ CH₃ H —O—(CH₂)₄—O— O C₂H₅ I-c-88 C₂H₅ CH₃ H —O—(CH₂)₂—O— O C₂H₅ I-c-89 C₂H₅ CH₃ C₂H₅ —O—CH(CH₃)—CH₂—CH₂—O— O C₂H₅ 1.05-1.28 (m, 12H), 2.32 (s, 3H), 3.70- syn/anti mixture 4.05 (m, 4H), 4.18 (mc, 2H) ### Example I-d-1 diff --git a/crates/fleischwolf/tests/data/uspto/expected/ipg07997973.xml.strict.md b/crates/fleischwolf/tests/data/uspto/expected/ipg07997973.xml.strict.md index e92e1766..7f5c7aed 100644 --- a/crates/fleischwolf/tests/data/uspto/expected/ipg07997973.xml.strict.md +++ b/crates/fleischwolf/tests/data/uspto/expected/ipg07997973.xml.strict.md @@ -70,7 +70,7 @@ The term “e.g.” and like terms mean “for example”, and thus does not lim The term “i.e.” and like terms mean “that is”, and thus limits the term or phrase it explains. For example, in the sentence “the computer sends data (i.e., instructions) over the Internet”, the term “i.e.” explains that “instructions” are the “data” that the computer sends over the Internet. -Any given numerical range shall include whole and fractions of numbers within the range. For example, the range “1 to 10” shall be interpreted to specifically include whole numbers between 1 and 10 (e.g., 1, 2, 3, 4, . . . 9) and non-whole numbers (e.g., 1.1, 1.2, . . . 1.9). +Any given numerical range shall include whole and fractions of numbers within the range. For example, the range “1 to 10” shall be interpreted to specifically include whole numbers between 1 and 10 (e.g., 1, 2, 3, 4,... 9) and non-whole numbers (e.g., 1.1, 1.2,... 1.9). ### II. Determining diff --git a/crates/fleischwolf/tests/data/webvtt/expected/webvtt_example_02.vtt.strict.md b/crates/fleischwolf/tests/data/webvtt/expected/webvtt_example_02.vtt.strict.md index 14117d7b..fbd874f5 100644 --- a/crates/fleischwolf/tests/data/webvtt/expected/webvtt_example_02.vtt.strict.md +++ b/crates/fleischwolf/tests/data/webvtt/expected/webvtt_example_02.vtt.strict.md @@ -6,4 +6,4 @@ Hee! *laughter* That’s awesome! -Sur les *playground* , ici à Montpellier +Sur les *playground*, ici à Montpellier diff --git a/crates/fleischwolf/tests/data/xbrl/expected/mlac-20251231.xml.strict.md b/crates/fleischwolf/tests/data/xbrl/expected/mlac-20251231.xml.strict.md index 37557e73..127afdab 100644 --- a/crates/fleischwolf/tests/data/xbrl/expected/mlac-20251231.xml.strict.md +++ b/crates/fleischwolf/tests/data/xbrl/expected/mlac-20251231.xml.strict.md @@ -436,7 +436,7 @@ NOTE 9 - SEGMENT INFORMATION ASC Topic 280, "Segment Reporting," establishes standards for companies to report in their financial statement information about operating segments, products, services, geographic areas, and major customers. Operating segments are defined as components of an enterprise for which separate financial information is available that is regularly evaluated by the Company's chief operating officer decision maker ("CODM"), or group, in deciding how to allocate resources and assess performance. -The Company's CODM has been identified as the Chief Executive Officer , who reviews the operating results for the Company as a whole to make decisions about allocating resources and assessing financial performance. Accordingly, management has determined that the Company only has one reportable segment. +The Company's CODM has been identified as the Chief Executive Officer, who reviews the operating results for the Company as a whole to make decisions about allocating resources and assessing financial performance. Accordingly, management has determined that the Company only has one reportable segment. The CODM assesses performance for the single segment and decides how to allocate resources based on net income that also is reported on the statements of operations as net income. The measure of segment assets is reported on the balance sheets as total assets. When evaluating the Company's performance and making key decisions regarding resource allocation, the CODM reviews several key metrics, which include the following: @@ -474,4 +474,4 @@ NOTE 10 - SUBSEQUENT EVENTS The Company evaluated subsequent events and transactions that occurred after the balance sheet date up to the date that the financial statements were issued. Based upon this review, the Company did not identify any subsequent events that would have required adjustment or disclosure in the financial statements. -On January 13, 2026, Mountain Lake Acquisition Corp. entered into Amendment No. 1 to the Business Combination Agreement ( the "Business Combination Agreement Amendment"), effective as of October 1, 2025, which, among other things, added Astral Horizon, L.P. and certain Seller affiliates as parties to the agreement, modified the allocation and form of merger consideration, revised the parties making seller representations and warranties, and replaced Exhibit E to the Business Combination Agreement. +On January 13, 2026, Mountain Lake Acquisition Corp. entered into Amendment No. 1 to the Business Combination Agreement (the "Business Combination Agreement Amendment"), effective as of October 1, 2025, which, among other things, added Astral Horizon, L.P. and certain Seller affiliates as parties to the agreement, modified the allocation and form of merger consideration, revised the parties making seller representations and warranties, and replaced Exhibit E to the Business Combination Agreement. diff --git a/scripts/export_tableformer.py b/scripts/export_tableformer.py new file mode 100644 index 00000000..f612c709 --- /dev/null +++ b/scripts/export_tableformer.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Export docling's TableFormer (TableModel04_rs) to ONNX for the Rust pipeline. + +TableFormer is autoregressive: an image encoder + a tag-transformer encoder run +once to produce a memory tensor, then a decoder step is looped to emit OTSL +structure tokens, and a bbox decoder turns the per-cell hidden states into boxes. +We export three graphs and drive the loop from Rust: + + encoder.onnx : image[1,3,448,448] -> memory[784,1,512] + decoder.onnx : tags[seq,1] + memory -> logits[1,V], hidden[1,512] + bbox.onnx : memory + cell_hidden[ncells,512] -> classes, coords (optional) + +IMPORTANT: export from the *same* checkpoint docling runs. Current docling pulls +`docling-project/docling-models` (NOT the older `ds4sd/docling-models`); their +TableFormer weights differ and produce different OTSL. Point the arg at: + ~/.cache/huggingface/hub/models--docling-project--docling-models/snapshots/*/model_artifacts/tableformer/accurate + +Verified: with these weights the exported graphs reproduce docling's OTSL token +sequence byte-exact on docling's own preprocessed table tensor. + +Run inside the docling venv: + .venv-compare/bin/python scripts/export_tableformer.py [out_dir] +""" +import json +import os +import sys +import warnings + +import torch +import torch.nn as nn + +warnings.filterwarnings("ignore") + +ART = sys.argv[1] +OUT = sys.argv[2] if len(sys.argv) > 2 else "models/tableformer" +os.makedirs(OUT, exist_ok=True) + +cfg = json.load(open(f"{ART}/tm_config.json")) +cfg["model"]["save_dir"] = ART +cfg["predict"]["profiling"] = False + +from docling_ibm_models.tableformer.data_management.tf_predictor import TFPredictor # noqa: E402 + +pred = TFPredictor(cfg, device="cpu") +m = pred._model +m.eval() +torch.set_grad_enabled(False) +for p in m.parameters(): + p.requires_grad_(False) +tt = m._tag_transformer +nh = tt._n_heads +word_map = pred._init_data["word_map"]["word_map_tag"] +start = word_map[""] + + +class Encode(nn.Module): + def forward(self, img): + eo_raw = m._encoder(img) # [1,28,28,512] — also feeds the bbox decoder + eo = tt._input_filter(eo_raw.permute(0, 3, 1, 2)).permute(0, 2, 3, 1) + ei = eo.reshape(1, -1, eo.size(-1)).permute(1, 0, 2) + pos = ei.shape[0] + mem = tt._encoder(ei, mask=torch.zeros((nh, pos, pos), dtype=torch.bool)) + return mem, eo_raw + + +class BBoxDecode(nn.Module): + # docling's BBoxDecoder.inference, batched over cells: each cell's tag hidden + # state attends over the (bbox-decoder-filtered) encoder output to a box. + def forward(self, enc_out, tag_h): # enc_out [1,28,28,512], tag_h [N,512] + bd = m._bbox_decoder + e = bd._input_filter(enc_out.permute(0, 3, 1, 2)).permute(0, 2, 3, 1) + e = e.reshape(1, -1, e.size(3)) # [1, 784, 512] + n = tag_h.shape[0] + h = bd._init_h(e.mean(dim=1)).expand(n, -1) # [N, dim] (same for all cells) + a = bd._attention + att = a._full_att( + a._relu( + a._encoder_att(e) + + a._tag_decoder_att(tag_h).unsqueeze(1) + + a._language_att(h).unsqueeze(1) + ) + ).squeeze(2) + alpha = a._softmax(att) # [N, 784] + awe = (e * alpha.unsqueeze(2)).sum(dim=1) # [N, 512] + h = (bd._sigmoid(bd._f_beta(h)) * awe) * h + return bd._bbox_embed(h).sigmoid(), bd._class_embed(h) + + +class Decode(nn.Module): + # The model's custom decoder layer keeps only the last token per layer and + # relies on a (non-standard) cache for the previous tokens' per-layer states. + # Re-running it cache-less loses deep context. Equivalently and statelessly we + # apply each layer to the *whole* prefix under a causal mask — verified to + # match the cache-based output exactly — so the ONNX graph is a plain step. + def forward(self, tags, memory): + o = tt._positional_encoding(tt._embedding(tags)) + s = o.shape[0] + cm = torch.triu(torch.full((s, s), float("-inf")), diagonal=1) + for mod in tt._decoder.layers: + o = mod.norm1(o + mod.self_attn(o, o, o, attn_mask=cm, need_weights=False)[0]) + o = mod.norm2(o + mod.multihead_attn(o, memory, memory, need_weights=False)[0]) + o = mod.norm3(o + mod.linear2(mod.activation(mod.linear1(o)))) + last = o[-1] + return tt._fc(last), last + + +def check(name, a, b): + import numpy as np + + d = float(np.abs(a - b).max()) + print(f" {name}: shape {tuple(a.shape)} | max|onnx-torch| = {d:.2e}") + return d + + +from torch.export import Dim # noqa: E402 + +img = torch.randn(1, 3, 448, 448) +with torch.no_grad(): + mem, enc_out = Encode()(img) +torch.onnx.export( + Encode(), (img,), f"{OUT}/encoder.onnx", + input_names=["image"], output_names=["memory", "enc_out"], + opset_version=17, dynamo=False, +) +tags = torch.full((4, 1), start, dtype=torch.long) +with torch.no_grad(): + logits, hidden = Decode()(tags, mem) +# The dynamo exporter is needed here: the legacy tracer bakes the sequence length +# into nn.MultiheadAttention's reshape, so a 1-token first step fails. dynamo keeps +# the `seq` axis symbolic. +seq = Dim("seq", min=1, max=1024) +torch.onnx.export( + Decode(), (tags, mem), f"{OUT}/decoder.onnx", + input_names=["tags", "memory"], output_names=["logits", "hidden"], + dynamo=True, dynamic_shapes=({0: seq}, {}), +) +# bbox decoder: N cell hiddens → N boxes (+ classes). N is dynamic. +tag_h = torch.randn(5, 512) +with torch.no_grad(): + boxes, classes = BBoxDecode()(enc_out, tag_h) +ncells = Dim("ncells", min=1, max=1024) +torch.onnx.export( + BBoxDecode(), (enc_out, tag_h), f"{OUT}/bbox.onnx", + input_names=["enc_out", "tag_h"], output_names=["boxes", "classes"], + dynamo=True, dynamic_shapes=({}, {0: ncells}), +) + +import onnxruntime as ort # noqa: E402 + +print("encoder.onnx:") +eres = ort.InferenceSession(f"{OUT}/encoder.onnx").run(None, {"image": img.numpy()}) +check("memory", eres[0], mem.numpy()) +check("enc_out", eres[1], enc_out.numpy()) +print("decoder.onnx:") +do = ort.InferenceSession(f"{OUT}/decoder.onnx").run( + None, {"tags": tags.numpy(), "memory": mem.numpy()} +) +check("logits", do[0], logits.numpy()) +check("hidden", do[1], hidden.numpy()) +print("bbox.onnx:") +bo = ort.InferenceSession(f"{OUT}/bbox.onnx").run( + None, {"enc_out": enc_out.numpy(), "tag_h": tag_h.numpy()} +) +check("boxes", bo[0], boxes.numpy()) +check("classes", bo[1], classes.numpy()) + +# word map → tokens file for the Rust decode loop +json.dump( + {"word_map_tag": word_map, "start": start, "end": word_map[""]}, + open(f"{OUT}/wordmap.json", "w"), +) +print("wrote wordmap.json; OTSL vocab size:", len(word_map)) diff --git a/scripts/pdf_conformance.sh b/scripts/pdf_conformance.sh index ca160c1f..f21a0716 100755 --- a/scripts/pdf_conformance.sh +++ b/scripts/pdf_conformance.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Regenerate PDF output for the test corpus and diff it against the committed -# snapshot baseline (tests/pdf_snapshots/). The pipeline is deterministic, so a +# snapshot baseline (tests/snapshots/). The pipeline is deterministic, so a # clean checkout should report every fixture EXACT; a non-zero diff means the # output drifted. Run scripts/pdf_setup.sh first to fetch the libs/models. set -euo pipefail @@ -23,7 +23,7 @@ cargo run --release -q -p fleischwolf-pdf --example snapshot -- tests/data "$tmp exact=0; drift=0; tot=0 while IFS= read -r snap; do - rel="${snap#tests/pdf_snapshots/}" + rel="${snap#tests/snapshots/}" gen="$tmp/$rel" tot=$((tot + 1)) if [ -f "$gen" ] && diff -q "$snap" "$gen" >/dev/null 2>&1; then @@ -33,7 +33,7 @@ while IFS= read -r snap; do d=$(diff "$snap" "$gen" 2>/dev/null | grep -cE '^[<>]' || true) printf " %-55s %s\n" "$rel" "${d:-MISSING}" fi -done < <(find tests/pdf_snapshots -name '*.md' | sort) +done < <(find tests/snapshots -name '*.md' | sort) echo "PDF snapshot conformance: $exact/$tot exact ($drift drifted)" [ "$drift" -eq 0 ] diff --git a/scripts/pdf_groundtruth.sh b/scripts/pdf_groundtruth.sh new file mode 100755 index 00000000..5f9ce6cb --- /dev/null +++ b/scripts/pdf_groundtruth.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# +# Per-PDF byte-conformance of the Rust pipeline vs the committed docling +# groundtruth (tests/data/pdf/groundtruth/*.md). Unlike conformance.sh this needs +# no docling install — it diffs against the checked-in reference. Use it to track +# how many groundtruth PDFs are byte-for-byte exact (see PDF_CONFORMANCE.md). +# +# Usage: scripts/pdf_groundtruth.sh + +set -euo pipefail +cd "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/.." + +export PDFIUM_DYNAMIC_LIB_PATH="${PDFIUM_DYNAMIC_LIB_PATH:-$(pwd)/.pdfium/lib}" +export DOCLING_LAYOUT_ONNX="${DOCLING_LAYOUT_ONNX:-$(pwd)/models/layout_heron.onnx}" +export DOCLING_OCR_REC_ONNX="${DOCLING_OCR_REC_ONNX:-$(pwd)/models/ocr_rec.onnx}" +export DOCLING_OCR_DICT="${DOCLING_OCR_DICT:-$(pwd)/models/ppocr_keys_v1.txt}" + +cargo build --release --quiet -p fleischwolf-cli +BIN=./target/release/fleischwolf + +exact=0 +total=0 +printf "%-34s %12s\n" "PDF" "DIFF-LINES" +printf "%-34s %12s\n" "---" "----------" +for gt in tests/data/pdf/groundtruth/*.md; do + stem="$(basename "$gt" .md)" + src="tests/data/pdf/sources/$stem.pdf" + [[ -f "$src" ]] || continue + total=$((total + 1)) + out="$("$BIN" "$src" 2>/dev/null || echo '')" + # Compare trailing-newline-insensitively; one changed line counts as 2. + d="$(diff <(printf '%s' "$out") <(printf '%s' "$(cat "$gt")") | grep -cE '^[<>]' || true)" + if [[ "$d" -eq 0 ]]; then + exact=$((exact + 1)) + mark="EXACT" + else + mark="$d" + fi + printf "%-34s %12s\n" "$stem" "$mark" +done +echo +echo "Fully conformant: $exact / $total" diff --git a/tests/data/pdf/groundtruth/2203.01017v2.md b/tests/data/pdf/groundtruth/2203.01017v2.md index 9853a499..f553ec90 100644 --- a/tests/data/pdf/groundtruth/2203.01017v2.md +++ b/tests/data/pdf/groundtruth/2203.01017v2.md @@ -14,17 +14,17 @@ The occurrence of tables in documents is ubiquitous. They often summarise quanti ## a. Picture of a table: -| 1 | -| - | +| 1 | +|-----| 7 -| 0 | 1 2 1 | 1 2 1 | 1 2 1 | -| - | - | - | - | -| 3 4 | 5 | 6 | 7 | -| 9 13 | 10 | 11 | 12 | -| 8 2 | 14 | 15 | 16 | -| 17 | 18 | 19 | 20 | +| 0 | 1 2 1 | 1 2 1 | 1 2 1 | +|------|---------|---------|---------| +| 3 4 | 5 | 6 | 7 | +| 9 13 | 10 | 11 | 12 | +| 8 2 | 14 | 15 | 16 | +| 17 | 18 | 19 | 20 | Figure 1: Picture of a table with subtle, complex features such as (1) multi-column headers, (2) cell with multi-row text and (3) cells with no content. Image from PubTabNet evaluation set, filename: 'PMC2944238 004 02'. @@ -85,14 +85,14 @@ In this regard, we have prepared four synthetic datasets, each one containing 15 Table 1: Both 'Combined-Tabnet' and 'CombinedTabnet' are variations of the following: (*) The CombinedTabnet dataset is the processed combination of PubTabNet and Fintabnet. (**) The combined dataset is the processed combination of PubTabNet, Fintabnet and TableBank. -| | Tags | Bbox | Size | Format | -| - | - | - | - | - | -| PubTabNet | 3 | 3 | 509k | PNG | -| FinTabNet | 3 | 3 | 112k | PDF | -| TableBank | 3 | 7 | 145k | JPEG | -| Combined-Tabnet(*) | 3 | 3 | 400k | PNG | -| Combined(**) | 3 | 3 | 500k | PNG | -| SynthTabNet | 3 | 3 | 600k | PNG | +| | Tags | Bbox | Size | Format | +|--------------------|--------|--------|--------|----------| +| PubTabNet | 3 | 3 | 509k | PNG | +| FinTabNet | 3 | 3 | 112k | PDF | +| TableBank | 3 | 7 | 145k | JPEG | +| Combined-Tabnet(*) | 3 | 3 | 400k | PNG | +| Combined(**) | 3 | 3 | 500k | PNG | +| SynthTabNet | 3 | 3 | 600k | PNG | Tab. 1 summarizes the various attributes of the datasets. @@ -166,18 +166,18 @@ where T a and T b represent tables in tree structure HTML format. EditDist denot Structure. As shown in Tab. 2, TableFormer outperforms all SOTA methods across different datasets by a large margin for predicting the table structure from an image. All the more, our model outperforms pre-trained methods. During the evaluation we do not apply any table filtering. We also provide our baseline results on the SynthTabNet dataset. It has been observed that large tables (e.g. tables that occupy half of the page or more) yield poor predictions. We attribute this issue to the image resizing during the preprocessing step, that produces downsampled images with indistinguishable features. This problem can be addressed by treating such big tables with a separate model which accepts a large input image size. -| Model | Dataset | Simple | TEDS Complex | All | -| - | - | - | - | - | -| EDD | PTN | 91.1 | 88.7 | 89.9 | -| GTE | PTN | - | - | 93.01 | -| TableFormer | PTN | 98.5 | 95.0 | 96.75 | -| EDD | FTN | 88.4 | 92.08 | 90.6 | -| GTE | FTN | - | - | 87.14 | -| GTE (FT) | FTN | - | - | 91.02 | -| TableFormer | FTN | 97.5 | 96.0 | 96.8 | -| EDD | TB | 86.0 | - | 86.0 | -| TableFormer | TB | 89.6 | - | 89.6 | -| TableFormer | STN | 96.9 | 95.7 | 96.7 | +| Model | Dataset | Simple | TEDS Complex | All | +|-------------|-----------|----------|----------------|-------| +| EDD | PTN | 91.1 | 88.7 | 89.9 | +| GTE | PTN | - | - | 93.01 | +| TableFormer | PTN | 98.5 | 95.0 | 96.75 | +| EDD | FTN | 88.4 | 92.08 | 90.6 | +| GTE | FTN | - | - | 87.14 | +| GTE (FT) | FTN | - | - | 91.02 | +| TableFormer | FTN | 97.5 | 96.0 | 96.8 | +| EDD | TB | 86.0 | - | 86.0 | +| TableFormer | TB | 89.6 | - | 89.6 | +| TableFormer | STN | 96.9 | 95.7 | 96.7 | Table 2: Structure results on PubTabNet (PTN), FinTabNet (FTN), TableBank (TB) and SynthTabNet (STN). @@ -187,24 +187,24 @@ Cell Detection. Like any object detector, our Cell BBox Detector provides boundi Table 3: Cell Bounding Box detection results on PubTabNet, and FinTabNet. PP: Post-processing. -| Model | Dataset | mAP | mAP (PP) | -| - | - | - | - | -| EDD+BBox | PubTabNet | 79.2 | 82.7 | -| TableFormer | PubTabNet | 82.1 | 86.8 | -| TableFormer | SynthTabNet | 87.7 | - | +| Model | Dataset | mAP | mAP (PP) | +|-------------|-------------|-------|------------| +| EDD+BBox | PubTabNet | 79.2 | 82.7 | +| TableFormer | PubTabNet | 82.1 | 86.8 | +| TableFormer | SynthTabNet | 87.7 | - | Cell Content. In this section, we evaluate the entire pipeline of recovering a table with content. Here we put our approach to test by capitalizing on extracting content from the PDF cells rather than decoding from images. Tab. 4 shows the TEDs score of HTML code representing the structure of the table along with the content inserted in the data cell and compared with the ground-truth. Our method achieved a 5.3% increase over the state-of-the-art, and commercial solutions. We believe our scores would be higher if the HTML ground-truth matched the extracted PDF cell content. Unfortunately, there are small discrepancies such as spacings around words or special characters with various unicode representations. Table 4: Results of structure with content retrieved using cell detection on PubTabNet. In all cases the input is PDF documents with cropped tables. -| Model | Simple | TEDS Complex | All | -| - | - | - | - | -| Tabula | 78.0 | 57.8 | 67.9 | -| Traprange | 60.8 | 49.9 | 55.4 | -| Camelot | 80.0 | 66.0 | 73.0 | -| Acrobat Pro | 68.9 | 61.8 | 65.3 | -| EDD | 91.2 | 85.4 | 88.3 | -| TableFormer | 95.4 | 90.1 | 93.6 | +| Model | Simple | TEDS Complex | All | +|-------------|----------|----------------|-------| +| Tabula | 78.0 | 57.8 | 67.9 | +| Traprange | 60.8 | 49.9 | 55.4 | +| Camelot | 80.0 | 66.0 | 73.0 | +| Acrobat Pro | 68.9 | 61.8 | 65.3 | +| EDD | 91.2 | 85.4 | 88.3 | +| TableFormer | 95.4 | 90.1 | 93.6 | - a. Red - PDF cells, Green - predicted bounding boxes, Blue - post-processed predictions matched to PDF cells @@ -349,24 +349,40 @@ Figure 9: Example of a table with big empty distance between cells. -Figure 10: Example of a complex table with empty cells. +| | | ANOVA | ANOVA | 2 | +|-----------|---------|---------|---------|--------------| +| 3 | Sum Sq | 5Df | FValue | Pr (>F) | +| | 5745.2 | | 266.75 | 4.64 × 10−9 | +| 2onc | 2191.39 | | 0.7 | 2.76 × 10 | +| R1× conc | 2648.33 | | 1.48 | 1.07 × 10 -6 | +| Residuals | 236.91 | | 6 | | - +Figure 10: Example of a complex table with empty cells. Figure 11: Simple table with different style and empty cells. + + Figure 13: Table predictions example on colorful table. +PDF Cells + Figure 12: Simple table predictions and post processing. Figure 14: Example with multi-line text. +4 [4.0] + +9 μ4.1 + +## PDF Cells + Figure 15: Example with triangular table. diff --git a/tests/data/pdf/groundtruth/2206.01062.md b/tests/data/pdf/groundtruth/2206.01062.md index 1875eb4c..6a81ca46 100644 --- a/tests/data/pdf/groundtruth/2206.01062.md +++ b/tests/data/pdf/groundtruth/2206.01062.md @@ -97,21 +97,21 @@ The annotation campaign was carried out in four phases. In phase one, we identif Table 1: DocLayNet dataset overview. Along with the frequency of each class label, we present the relative occurrence (as % of row 'Total') in the train, test and validation sets. The inter-annotator agreement is computed as the mAP@0.5-0.95 metric between pairwise annotations from the triple-annotated pages, from which we obtain accuracy ranges. -| | | % of Total | % of Total | % of Total | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | -| - | - | - | - | - | - | - | - | - | - | - | - | -| class label | Count | Train | Test | Val | All | Fin | Man | Sci | Law | Pat | Ten | -| Caption | 22524 | 2.04 | 1.77 | 2.32 | 84-89 | 40-61 | 86-92 | 94-99 | 95-99 | 69-78 | n/a | -| Footnote | 6318 | 0.60 | 0.31 | 0.58 | 83-91 | n/a | 100 | 62-88 | 85-94 | n/a | 82-97 | -| Formula | 25027 | 2.25 | 1.90 | 2.96 | 83-85 | n/a | n/a | 84-87 | 86-96 | n/a | n/a | -| List-item | 185660 | 17.19 | 13.34 | 15.82 | 87-88 | 74-83 | 90-92 | 97-97 | 81-85 | 75-88 | 93-95 | -| Page-footer | 70878 | 6.51 | 5.58 | 6.00 | 93-94 | 88-90 | 95-96 | 100 | 92-97 | 100 | 96-98 | -| Page-header | 58022 | 5.10 | 6.70 | 5.06 | 85-89 | 66-76 | 90-94 | 98-100 | 91-92 | 97-99 | 81-86 | -| Picture | 45976 | 4.21 | 2.78 | 5.31 | 69-71 | 56-59 | 82-86 | 69-82 | 80-95 | 66-71 | 59-76 | -| Section-header | 142884 | 12.60 | 15.77 | 12.85 | 83-84 | 76-81 | 90-92 | 94-95 | 87-94 | 69-73 | 78-86 | -| Table | 34733 | 3.20 | 2.27 | 3.60 | 77-81 | 75-80 | 83-86 | 98-99 | 58-80 | 79-84 | 70-85 | -| Text | 510377 | 45.82 | 49.28 | 45.00 | 84-86 | 81-86 | 88-93 | 89-93 | 87-92 | 71-79 | 87-95 | -| Title | 5071 | 0.47 | 0.30 | 0.50 | 60-72 | 24-63 | 50-63 | 94-100 | 82-96 | 68-79 | 24-56 | -| Total | 1107470 | 941123 | 99816 | 66531 | 82-83 | 71-74 | 79-81 | 89-94 | 86-91 | 71-76 | 68-85 | +| | | % of Total | % of Total | % of Total | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | +|----------------|---------|--------------|--------------|--------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------| +| class label | Count | Train | Test | Val | All | Fin | Man | Sci | Law | Pat | Ten | +| Caption | 22524 | 2.04 | 1.77 | 2.32 | 84-89 | 40-61 | 86-92 | 94-99 | 95-99 | 69-78 | n/a | +| Footnote | 6318 | 0.60 | 0.31 | 0.58 | 83-91 | n/a | 100 | 62-88 | 85-94 | n/a | 82-97 | +| Formula | 25027 | 2.25 | 1.90 | 2.96 | 83-85 | n/a | n/a | 84-87 | 86-96 | n/a | n/a | +| List-item | 185660 | 17.19 | 13.34 | 15.82 | 87-88 | 74-83 | 90-92 | 97-97 | 81-85 | 75-88 | 93-95 | +| Page-footer | 70878 | 6.51 | 5.58 | 6.00 | 93-94 | 88-90 | 95-96 | 100 | 92-97 | 100 | 96-98 | +| Page-header | 58022 | 5.10 | 6.70 | 5.06 | 85-89 | 66-76 | 90-94 | 98-100 | 91-92 | 97-99 | 81-86 | +| Picture | 45976 | 4.21 | 2.78 | 5.31 | 69-71 | 56-59 | 82-86 | 69-82 | 80-95 | 66-71 | 59-76 | +| Section-header | 142884 | 12.60 | 15.77 | 12.85 | 83-84 | 76-81 | 90-92 | 94-95 | 87-94 | 69-73 | 78-86 | +| Table | 34733 | 3.20 | 2.27 | 3.60 | 77-81 | 75-80 | 83-86 | 98-99 | 58-80 | 79-84 | 70-85 | +| Text | 510377 | 45.82 | 49.28 | 45.00 | 84-86 | 81-86 | 88-93 | 89-93 | 87-92 | 71-79 | 87-95 | +| Title | 5071 | 0.47 | 0.30 | 0.50 | 60-72 | 24-63 | 50-63 | 94-100 | 82-96 | 68-79 | 24-56 | +| Total | 1107470 | 941123 | 99816 | 66531 | 82-83 | 71-74 | 79-81 | 89-94 | 86-91 | 71-76 | 68-85 | Figure 3: Corpus Conversion Service annotation user interface. The PDF page is shown in the background, with overlaid text-cells (in darker shades). The annotation boxes can be drawn by dragging a rectangle over each segment with the respective label from the palette on the right. @@ -152,21 +152,21 @@ Phase 4: Production annotation. The previously selected 80K pages were annotated Table 2: Prediction performance (mAP@0.5-0.95) of object detection networks on DocLayNet test set. The MRCNN (Mask R-CNN) and FRCNN (Faster R-CNN) models with ResNet-50 or ResNet-101 backbone were trained based on the network architectures from the detectron2 model zoo (Mask R-CNN R50, R101-FPN 3x, Faster R-CNN R101-FPN 3x), with default configurations. The YOLO implementation utilized was YOLOv5x6 [13]. All models were initialised using pre-trained weights from the COCO 2017 dataset. -| | human | MRCNN | MRCNN | FRCNN | YOLO | -| - | - | - | - | - | - | -| | | R50 | R101 | R101 | v5x6 | -| Caption | 84-89 | 68.4 | 71.5 | 70.1 | 77.7 | -| Footnote | 83-91 | 70.9 | 71.8 | 73.7 | 77.2 | -| Formula | 83-85 | 60.1 | 63.4 | 63.5 | 66.2 | -| List-item | 87-88 | 81.2 | 80.8 | 81.0 | 86.2 | -| Page-footer | 93-94 | 61.6 | 59.3 | 58.9 | 61.1 | -| Page-header | 85-89 | 71.9 | 70.0 | 72.0 | 67.9 | -| Picture | 69-71 | 71.7 | 72.7 | 72.0 | 77.1 | -| Section-header | 83-84 | 67.6 | 69.3 | 68.4 | 74.6 | -| Table | 77-81 | 82.2 | 82.9 | 82.2 | 86.3 | -| Text | 84-86 | 84.6 | 85.8 | 85.4 | 88.1 | -| Title | 60-72 | 76.7 | 80.4 | 79.9 | 82.7 | -| All | 82-83 | 72.4 | 73.5 | 73.4 | 76.8 | +| | human | MRCNN | MRCNN | FRCNN | YOLO | +|----------------|---------|---------|---------|---------|--------| +| | | R50 | R101 | R101 | v5x6 | +| Caption | 84-89 | 68.4 | 71.5 | 70.1 | 77.7 | +| Footnote | 83-91 | 70.9 | 71.8 | 73.7 | 77.2 | +| Formula | 83-85 | 60.1 | 63.4 | 63.5 | 66.2 | +| List-item | 87-88 | 81.2 | 80.8 | 81.0 | 86.2 | +| Page-footer | 93-94 | 61.6 | 59.3 | 58.9 | 61.1 | +| Page-header | 85-89 | 71.9 | 70.0 | 72.0 | 67.9 | +| Picture | 69-71 | 71.7 | 72.7 | 72.0 | 77.1 | +| Section-header | 83-84 | 67.6 | 69.3 | 68.4 | 74.6 | +| Table | 77-81 | 82.2 | 82.9 | 82.2 | 86.3 | +| Text | 84-86 | 84.6 | 85.8 | 85.4 | 88.1 | +| Title | 60-72 | 76.7 | 80.4 | 79.9 | 82.7 | +| All | 82-83 | 72.4 | 73.5 | 73.4 | 76.8 | ## 5 EXPERIMENTS @@ -184,20 +184,20 @@ In Table 2, we present baseline experiments (given in mAP) on Mask R-CNN [12], F Table 3: Performance of a Mask R-CNN R50 network in mAP@0.5-0.95 scores trained on DocLayNet with different class label sets. The reduced label sets were obtained by either down-mapping or dropping labels. -| Class-count | 11 | 6 | 5 | 4 | -| - | - | - | - | - | -| Caption | 68 | Text | Text | Text | -| Footnote | 71 | Text | Text | Text | -| Formula | 60 | Text | Text | Text | -| List-item | 81 | Text | 82 | Text | -| Page-footer | 62 | 62 | - | - | -| Page-header | 72 | 68 | - | - | -| Picture | 72 | 72 | 72 | 72 | -| Section-header | 68 | 67 | 69 | 68 | -| Table | 82 | 83 | 82 | 82 | -| Text | 85 | 84 | 84 | 84 | -| Title | 77 | Sec.-h. | Sec.-h. | Sec.-h. | -| Overall | 72 | 73 | 78 | 77 | +| Class-count | 11 | 6 | 5 | 4 | +|----------------|------|---------|---------|---------| +| Caption | 68 | Text | Text | Text | +| Footnote | 71 | Text | Text | Text | +| Formula | 60 | Text | Text | Text | +| List-item | 81 | Text | 82 | Text | +| Page-footer | 62 | 62 | - | - | +| Page-header | 72 | 68 | - | - | +| Picture | 72 | 72 | 72 | 72 | +| Section-header | 68 | 67 | 69 | 68 | +| Table | 82 | 83 | 82 | 82 | +| Text | 85 | 84 | 84 | 84 | +| Title | 77 | Sec.-h. | Sec.-h. | Sec.-h. | +| Overall | 72 | 73 | 78 | 77 | ## Learning Curve @@ -209,21 +209,21 @@ The choice and number of labels can have a significant effect on the overall mod Table 4: Performance of a Mask R-CNN R50 network with document-wise and page-wise split for different label sets. Naive page-wise split will result in /tildelow 10% point improvement. -| Class-count Split | 11 | 11 | 5 | 5 | -| - | - | - | - | - | -| | Doc | Page | Doc | Page | -| Caption | 68 | 83 | | | -| Footnote | 71 | 84 | | | -| Formula | 60 | 66 | | | -| List-item | 81 | 88 | 82 | 88 | -| Page-footer | 62 | 89 | | | -| Page-header | 72 | 90 | | | -| Picture | 72 | 82 | 72 | 82 | -| Section-header | 68 | 83 | 69 | 83 | -| Table | 82 | 89 | 82 | 90 | -| Text | 85 | 91 | 84 | 90 | -| Title | 77 | 81 | | | -| All | 72 | 84 | 78 | 87 | +| Class-count Split | 11 | 11 | 5 | 5 | +|---------------------|------|------|-----|------| +| | Doc | Page | Doc | Page | +| Caption | 68 | 83 | | | +| Footnote | 71 | 84 | | | +| Formula | 60 | 66 | | | +| List-item | 81 | 88 | 82 | 88 | +| Page-footer | 62 | 89 | | | +| Page-header | 72 | 90 | | | +| Picture | 72 | 82 | 72 | 82 | +| Section-header | 68 | 83 | 69 | 83 | +| Table | 82 | 89 | 82 | 90 | +| Text | 85 | 91 | 84 | 90 | +| Title | 77 | 81 | | | +| All | 72 | 84 | 78 | 87 | ## Impact of Document Split in Train and Test Set @@ -233,22 +233,22 @@ Many documents in DocLayNet have a unique styling. In order to avoid overfitting Throughout this paper, we claim that DocLayNet's wider variety of document layouts leads to more robust layout detection models. In Table 5, we provide evidence for that. We trained models on each of the available datasets (PubLayNet, DocBank and DocLayNet) and evaluated them on the test sets of the other datasets. Due to the different label sets and annotation styles, a direct comparison is not possible. Hence, we focussed on the common labels among the datasets. Between PubLayNet and DocLayNet, these are Picture , KDD '22, August 14-18, 2022, Washington, DC, USA Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar Table 5: Prediction Performance (mAP@0.5-0.95) of a Mask R-CNN R50 network across the PubLayNet, DocBank & DocLayNet data-sets. By evaluating on common label classes of each dataset, we observe that the DocLayNet-trained model has much less pronounced variations in performance across all datasets. -| | | Testing on | Testing on | Testing on | -| - | - | - | - | - | -| Training on | labels | PLN | DB | DLN | -| PubLayNet (PLN) | Figure | 96 | 43 | 23 | -| PubLayNet (PLN) | Sec-header | 87 | - | 32 | -| | Table | 95 | 24 | 49 | -| | Text | 96 | - | 42 | -| | total | 93 | 34 | 30 | -| DocBank (DB) | Figure | 77 | 71 | 31 | -| DocBank (DB) | Table | 19 | 65 | 22 | -| DocBank (DB) | total | 48 | 68 | 27 | -| DocLayNet (DLN) | Figure | 67 | 51 | 72 | -| DocLayNet (DLN) | Sec-header | 53 | - | 68 | -| | Table | 87 | 43 | 82 | -| | Text | 77 | - | 84 | -| | total | 59 | 47 | 78 | +| | | Testing on | Testing on | Testing on | +|-----------------|------------|--------------|--------------|--------------| +| Training on | labels | PLN | DB | DLN | +| PubLayNet (PLN) | Figure | 96 | 43 | 23 | +| PubLayNet (PLN) | Sec-header | 87 | - | 32 | +| | Table | 95 | 24 | 49 | +| | Text | 96 | - | 42 | +| | total | 93 | 34 | 30 | +| DocBank (DB) | Figure | 77 | 71 | 31 | +| DocBank (DB) | Table | 19 | 65 | 22 | +| DocBank (DB) | total | 48 | 68 | 27 | +| DocLayNet (DLN) | Figure | 67 | 51 | 72 | +| DocLayNet (DLN) | Sec-header | 53 | - | 68 | +| | Table | 87 | 43 | 82 | +| | Text | 77 | - | 84 | +| | total | 59 | 47 | 78 | Section-header , Table and Text . Before training, we either mapped or excluded DocLayNet's other labels as specified in table 3, and also PubLayNet's List to Text . Note that the different clustering of lists (by list-element vs. whole list objects) naturally decreases the mAP score for Text . diff --git a/tests/data/pdf/groundtruth/2305.03393v1-pg9.md b/tests/data/pdf/groundtruth/2305.03393v1-pg9.md index 52576c63..82ec7912 100644 --- a/tests/data/pdf/groundtruth/2305.03393v1-pg9.md +++ b/tests/data/pdf/groundtruth/2305.03393v1-pg9.md @@ -6,13 +6,13 @@ We have chosen the PubTabNet data set to perform HPO, since it includes a highly Table 1. HPO performed in OTSL and HTML representation on the same transformer-based TableFormer [9] architecture, trained only on PubTabNet [22]. Effects of reducing the # of layers in encoder and decoder stages of the model show that smaller models trained on OTSL perform better, especially in recognizing complex table structures, and maintain a much higher mAP score than the HTML counterpart. -| # enc-layers | # dec-layers | Language | TEDs | TEDs | TEDs | mAP (0.75) | Inference time (secs) | -| - | - | - | - | - | - | - | - | -| # enc-layers | # dec-layers | Language | simple | complex | all | mAP (0.75) | Inference time (secs) | -| 6 | 6 | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | -| 4 | 4 | OTSL HTML | 0.938 0.952 | 0.904 0.909 | 0.927 0.938 | 0.853 0.843 | 1.97 3.77 | -| 2 | 4 | OTSL HTML | 0.923 0.945 | 0.897 0.901 | 0.915 0.931 | 0.859 0.834 | 1.91 3.81 | -| 4 | 2 | OTSL HTML | 0.952 0.944 | 0.92 0.903 | 0.942 0.931 | 0.857 0.824 | 1.22 2 | +| # enc-layers | # dec-layers | Language | TEDs | TEDs | TEDs | mAP (0.75) | Inference time (secs) | +|----------------|----------------|------------|-------------|-------------|-------------|--------------|-------------------------| +| # enc-layers | # dec-layers | Language | simple | complex | all | mAP (0.75) | Inference time (secs) | +| 6 | 6 | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | +| 4 | 4 | OTSL HTML | 0.938 0.952 | 0.904 0.909 | 0.927 0.938 | 0.853 0.843 | 1.97 3.77 | +| 2 | 4 | OTSL HTML | 0.923 0.945 | 0.897 0.901 | 0.915 0.931 | 0.859 0.834 | 1.91 3.81 | +| 4 | 2 | OTSL HTML | 0.952 0.944 | 0.92 0.903 | 0.942 0.931 | 0.857 0.824 | 1.22 2 | ## 5.2 Quantitative Results diff --git a/tests/data/pdf/groundtruth/2305.03393v1.md b/tests/data/pdf/groundtruth/2305.03393v1.md index a89a5710..f9422ad5 100644 --- a/tests/data/pdf/groundtruth/2305.03393v1.md +++ b/tests/data/pdf/groundtruth/2305.03393v1.md @@ -46,6 +46,10 @@ All known Im2Seq based models for TSR fundamentally work in similar ways. Given Fig. 2. Frequency of tokens in HTML and OTSL as they appear in PubTabNet. +HTML + +OTSL + Obviously, HTML and other general-purpose markup languages were not designed for Im2Seq models. As such, they have some serious drawbacks. First, the token vocabulary needs to be artificially large in order to describe all plausible tabular structures. Since most Im2Seq models use an autoregressive approach, they generate the sequence token by token. Therefore, to reduce inference time, a shorter sequence length is critical. Every table-cell is represented by at least two tokens ( <td> and </td> ). Furthermore, when tokenizing the HTML structure, one needs to explicitly enumerate possible column-spans and row-spans as words. In practice, this ends up requiring 28 different HTML tokens (when including column- and row-spans up to 10 cells) just to describe every table in the PubTabNet dataset. Clearly, not every token is equally represented, as is depicted in Figure 2. This skewed distribution of tokens in combination with variable token row-length makes it challenging for models to learn the HTML structure. @@ -116,13 +120,13 @@ We have chosen the PubTabNet data set to perform HPO, since it includes a highly Table 1. HPO performed in OTSL and HTML representation on the same transformer-based TableFormer [9] architecture, trained only on PubTabNet [22]. Effects of reducing the # of layers in encoder and decoder stages of the model show that smaller models trained on OTSL perform better, especially in recognizing complex table structures, and maintain a much higher mAP score than the HTML counterpart. -| # enc-layers | # dec-layers | Language | TEDs | TEDs | TEDs | mAP (0.75) | Inference time (secs) | -| - | - | - | - | - | - | - | - | -| # enc-layers | # dec-layers | Language | simple | complex | all | mAP (0.75) | Inference time (secs) | -| 6 | 6 | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | -| 4 | 4 | OTSL HTML | 0.938 0.952 | 0.904 0.909 | 0.927 0.938 | 0.853 0.843 | 1.97 3.77 | -| 2 | 4 | OTSL HTML | 0.923 0.945 | 0.897 0.901 | 0.915 0.931 | 0.859 0.834 | 1.91 3.81 | -| 4 | 2 | OTSL HTML | 0.952 0.944 | 0.92 0.903 | 0.942 0.931 | 0.857 0.824 | 1.22 2 | +| # enc-layers | # dec-layers | Language | TEDs | TEDs | TEDs | mAP (0.75) | Inference time (secs) | +|----------------|----------------|------------|-------------|-------------|-------------|--------------|-------------------------| +| # enc-layers | # dec-layers | Language | simple | complex | all | mAP (0.75) | Inference time (secs) | +| 6 | 6 | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | +| 4 | 4 | OTSL HTML | 0.938 0.952 | 0.904 0.909 | 0.927 0.938 | 0.853 0.843 | 1.97 3.77 | +| 2 | 4 | OTSL HTML | 0.923 0.945 | 0.897 0.901 | 0.915 0.931 | 0.859 0.834 | 1.91 3.81 | +| 4 | 2 | OTSL HTML | 0.952 0.944 | 0.92 0.903 | 0.942 0.931 | 0.857 0.824 | 1.22 2 | ## 5.2 Quantitative Results @@ -132,12 +136,12 @@ Additionally, the results show that OTSL has an advantage over HTML when applied Table 2. TSR and cell detection results compared between OTSL and HTML on the PubTabNet [22], FinTabNet [21] and PubTables-1M [14] data sets using TableFormer [9] (with enc=6, dec=6, heads=8). -| Data set | Language | TEDs | TEDs | TEDs | mAP(0.75) | Inference time (secs) | -| - | - | - | - | - | - | - | -| Data set | Language | simple | complex | all | mAP(0.75) | Inference time (secs) | -| PubTabNet | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | -| FinTabNet | OTSL HTML | 0.955 0.917 | 0.961 0.922 | 0.959 0.92 | 0.862 0.722 | 1.85 3.26 | -| PubTables-1M | OTSL HTML | 0.987 0.983 | 0.964 0.944 | 0.977 0.966 | 0.896 0.889 | 1.79 3.26 | +| Data set | Language | TEDs | TEDs | TEDs | mAP(0.75) | Inference time (secs) | +|--------------|------------|-------------|-------------|-------------|-------------|-------------------------| +| Data set | Language | simple | complex | all | mAP(0.75) | Inference time (secs) | +| PubTabNet | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | +| FinTabNet | OTSL HTML | 0.955 0.917 | 0.961 0.922 | 0.959 0.92 | 0.862 0.722 | 1.85 3.26 | +| PubTables-1M | OTSL HTML | 0.987 0.983 | 0.964 0.944 | 0.977 0.966 | 0.896 0.889 | 1.79 3.26 | ## 5.3 Qualitative Results diff --git a/tests/data/pdf/groundtruth/normal_4pages.md b/tests/data/pdf/groundtruth/normal_4pages.md index 821914e8..7610770f 100644 --- a/tests/data/pdf/groundtruth/normal_4pages.md +++ b/tests/data/pdf/groundtruth/normal_4pages.md @@ -48,12 +48,12 @@ [표 1] 감염병예방법 제2조제2호 개정전·후 비교 -| 구분 | 개정전 | 개정후 | -| - | - | - | -| 분류 | 1군감염병 | 1급감염병 | -| 분류 기준 | ◦ 마시는물또는식품을매개로 발생하고집단발생의우려가 큰감염병 | ◦ 생물테러감염병또는치명률이 높거나집단발생의우려가커높 은수준의격리가필요한감염병 | -| 대상 질병 | ◦ (6종)콜레라,장티푸스,파라 티푸스, 세균성이질, 장출혈 성대장균감염증,A형간염 | ◦ (17종)에볼라,페스트등 *좌측6종(2급감염병분류)은 미포함 | -| U코드 | ◦ 대상질병에U코드없음 | ◦ 대상질병에U코드일부(3종) 포함 ①신종감염병증후군→코로나19(U) ②중증급성호흡기증후군(SARS)(U) ③중동호흡기증후군(MERS)(U) | +| 구분 | 개정전 | 개정후 | +|-------|------------------------------------------------|--------------------------------------------------------------------------------| +| 분류 | 1군감염병 | 1급감염병 | +| 분류 기준 | ◦ 마시는물또는식품을매개로 발생하고집단발생의우려가 큰감염병 | ◦ 생물테러감염병또는치명률이 높거나집단발생의우려가커높 은수준의격리가필요한감염병 | +| 대상 질병 | ◦ (6종)콜레라,장티푸스,파라 티푸스, 세균성이질, 장출혈 성대장균감염증,A형간염 | ◦ (17종)에볼라,페스트등 *좌측6종(2급감염병분류)은 미포함 | +| U코드 | ◦ 대상질병에U코드없음 | ◦ 대상질병에U코드일부(3종) 포함 ①신종감염병증후군→코로나19(U) ②중증급성호흡기증후군(SARS)(U) ③중동호흡기증후군(MERS)(U) | 기존 생명보험에서 재해로 보장하는 법정1군 전염 병은 '콜레라, 장티푸스, 파라티푸스, 세균성이질, 장 출혈성대장균감염증, A형간염'이었으나 이번에 개 diff --git a/tests/data/pdf/groundtruth/redp5110_sampled.md b/tests/data/pdf/groundtruth/redp5110_sampled.md index b789d39f..ed7e8c33 100644 --- a/tests/data/pdf/groundtruth/redp5110_sampled.md +++ b/tests/data/pdf/groundtruth/redp5110_sampled.md @@ -8,49 +8,49 @@ Front cover ## Contents -| Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . vii | -| - | - | -| Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | viii | -| DB2 for i Center of Excellence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . ix | -| Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . xi | -| Authors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . xi | -| Now you can become a published author, too! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | xiii | -| Comments welcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | xiii | -| Stay connected to IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | xiv | -| Chapter 1. Securing and protecting IBM DB2 data . . . . . . . . . . . . . . . . . . . . . . . | . 1 | -| 1.1 Security fundamentals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 2 | -| 1.2 Current state of IBM i security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 2 | -| 1.3 DB2 for i security controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 3 | -| 1.3.1 Existing row and column control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 4 | -| 1.3.2 New controls: Row and Column Access Control. . . . . . . . . . . . . . . . . . . . . | . 5 | -| Chapter 2. Roles and separation of duties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 7 | -| 2.1 Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 8 | -| 2.1.1 DDM and DRDA application server access: QIBM_DB_DDMDRDA . . . . . | . 8 | -| 2.1.2 Toolbox application server access: QIBM_DB_ZDA. . . . . . . . . . . . . . . . . . | . 8 | -| 2.1.3 Database Administrator function: QIBM_DB_SQLADM . . . . . . . . . . . . . . . | . 9 | -| 2.1.4 Database Information function: QIBM_DB_SYSMON . . . . . . . . . . . . . . . . | . 9 | -| 2.1.5 Security Administrator function: QIBM_DB_SECADM . . . . . . . . . . . . . . . . | . 9 | -| 2.1.6 Change Function Usage CL command. . . . . . . . . . . . . . . . . . . . . . . . . . . . | 10 | -| 2.1.7 Verifying function usage IDs for RCAC with the FUNCTION_USAGE view | 10 | -| 2.2 Separation of duties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 10 | -| Chapter 3. Row and Column Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 13 | -| 3.1 Explanation of RCAC and the concept of access control . . . . . . . . . . . . . . . . . . | 14 | -| 3.1.1 Row permission and column mask definitions . . . . . . . . . . . . . . . . . . . . . . 3.1.2 Enabling and activating RCAC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 14 | -| 3.2 Special registers and built-in global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . | 16 18 | -| 3.2.1 Special registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 18 | -| 3.2.2 Built-in global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 19 | -| 3.3 VERIFY_GROUP_FOR_USER function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 20 | -| 3.4 Establishing and controlling accessibility by using the RCAC rule text. . . . . . . . | 21 | -| 3.5 SELECT, INSERT, and UPDATE behavior with RCAC . . . . . . . . . . . . . . . . . . . | 22 | -| Human resources example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 22 | -| 3.6 3.6.1 Assigning the QIBM_DB_SECADM function ID to the consultants. . . . . . . | 23 | -| 3.6.2 Creating group profiles for the users and their roles. . . . . . . . . . . . . . . . . . | 23 | -| 3.6.3 Demonstrating data access without RCAC. . . . . . . . . . . . . . . . . . . . . . . . . | 24 | -| 3.6.4 Defining and creating row permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 25 | -| masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 26 | -| 3.6.5 Defining and creating column | 28 | -| 3.6.6 Activating RCAC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.6.7 Demonstrating data access with RCAC . . . . . . . . . . . . . . . . . . . . . . . . . . . | 29 | -| 3.6.8 Demonstrating data access with a view and RCAC . . . . . . . . . . . . . . . . . . | 32 | +| Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . vii | +|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------| +| Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | viii | +| DB2 for i Center of Excellence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . ix | +| Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . xi | +| Authors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . xi | +| Now you can become a published author, too! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | xiii | +| Comments welcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | xiii | +| Stay connected to IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | xiv | +| Chapter 1. Securing and protecting IBM DB2 data . . . . . . . . . . . . . . . . . . . . . . . | . 1 | +| 1.1 Security fundamentals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 2 | +| 1.2 Current state of IBM i security. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 2 | +| 1.3 DB2 for i security controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 3 | +| 1.3.1 Existing row and column control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 4 | +| 1.3.2 New controls: Row and Column Access Control. . . . . . . . . . . . . . . . . . . . . | . 5 | +| Chapter 2. Roles and separation of duties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 7 | +| 2.1 Roles. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | . 8 | +| 2.1.1 DDM and DRDA application server access: QIBM_DB_DDMDRDA . . . . . | . 8 | +| 2.1.2 Toolbox application server access: QIBM_DB_ZDA. . . . . . . . . . . . . . . . . . | . 8 | +| 2.1.3 Database Administrator function: QIBM_DB_SQLADM . . . . . . . . . . . . . . . | . 9 | +| 2.1.4 Database Information function: QIBM_DB_SYSMON . . . . . . . . . . . . . . . . | . 9 | +| 2.1.5 Security Administrator function: QIBM_DB_SECADM . . . . . . . . . . . . . . . . | . 9 | +| 2.1.6 Change Function Usage CL command. . . . . . . . . . . . . . . . . . . . . . . . . . . . | 10 | +| 2.1.7 Verifying function usage IDs for RCAC with the FUNCTION_USAGE view | 10 | +| 2.2 Separation of duties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 10 | +| Chapter 3. Row and Column Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 13 | +| 3.1 Explanation of RCAC and the concept of access control . . . . . . . . . . . . . . . . . . | 14 | +| 3.1.1 Row permission and column mask definitions . . . . . . . . . . . . . . . . . . . . . . 3.1.2 Enabling and activating RCAC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 14 | +| 3.2 Special registers and built-in global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . | 16 18 | +| 3.2.1 Special registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 18 | +| 3.2.2 Built-in global variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 19 | +| 3.3 VERIFY_GROUP_FOR_USER function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 20 | +| 3.4 Establishing and controlling accessibility by using the RCAC rule text. . . . . . . . | 21 | +| 3.5 SELECT, INSERT, and UPDATE behavior with RCAC . . . . . . . . . . . . . . . . . . . | 22 | +| Human resources example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 22 | +| 3.6 3.6.1 Assigning the QIBM_DB_SECADM function ID to the consultants. . . . . . . | 23 | +| 3.6.2 Creating group profiles for the users and their roles. . . . . . . . . . . . . . . . . . | 23 | +| 3.6.3 Demonstrating data access without RCAC. . . . . . . . . . . . . . . . . . . . . . . . . | 24 | +| 3.6.4 Defining and creating row permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 25 | +| masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . | 26 | +| 3.6.5 Defining and creating column | 28 | +| 3.6.6 Activating RCAC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3.6.7 Demonstrating data access with RCAC . . . . . . . . . . . . . . . . . . . . . . . . . . . | 29 | +| 3.6.8 Demonstrating data access with a view and RCAC . . . . . . . . . . . . . . . . . . | 32 | DB2 for i Center of Excellence @@ -189,21 +189,21 @@ The FUNCTION\_USAGE view contains function usage configuration details. Table 2- Table 2-1 FUNCTION\_USAGE view -| Column name | Data type | Description | -| - | - | - | -| FUNCTION_ID | VARCHAR(30) | ID of the function. | -| USER_NAME | VARCHAR(10) | Name of the user profile that has a usage setting for this function. | -| USAGE | VARCHAR(7) | Usage setting: /SM590000 ALLOWED: The user profile is allowed to use the function. /SM590000 DENIED: The user profile is not allowed to use the function. | -| USER_TYPE | VARCHAR(5) | Type of user profile: /SM590000 USER: The user profile is a user. /SM590000 GROUP: The user profile is a group. | +| Column name | Data type | Description | +|---------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| FUNCTION_ID | VARCHAR(30) | ID of the function. | +| USER_NAME | VARCHAR(10) | Name of the user profile that has a usage setting for this function. | +| USAGE | VARCHAR(7) | Usage setting: /SM590000 ALLOWED: The user profile is allowed to use the function. /SM590000 DENIED: The user profile is not allowed to use the function. | +| USER_TYPE | VARCHAR(5) | Type of user profile: /SM590000 USER: The user profile is a user. /SM590000 GROUP: The user profile is a group. | To discover who has authorization to define and manage RCAC, you can use the query that is shown in Example 2-1. Example 2-1 Query to determine who has authority to define and manage RCAC -| SELECT | function_id, user_name, usage, user_type | -| - | - | +| SELECT | function_id, user_name, usage, user_type | +|------------|--------------------------------------------------------| | FROM ORDER | function_usage function_id='QIBM_DB_SECADM' user_name; | -| WHERE | | +| WHERE | | ## 2.2 Separation of duties @@ -223,20 +223,20 @@ Table 2-2 shows a comparison of the different function usage IDs and *JOBCTL aut Table 2-2 Comparison of the different function usage IDs and *JOBCTL authority -| User action | *JOBCTL | QIBM_DB_SECADM | QIBM_DB_SQLADM | QIBM_DB_SYSMON | No Authority | -| - | - | - | - | - | - | -| SET CURRENT DEGREE (SQL statement) | X | | X | | | -| CHGQRYA command targeting a different user's job | X | | X | | | -| STRDBMON or ENDDBMON commands targeting a different user's job | X | | X | | | -| STRDBMON or ENDDBMON commands targeting a job that matches the current user | X | | X | X | X | -| QUSRJOBI() API format 900 or System i Navigator's SQL Details for Job | X | | X | X | | -| Visual Explain within Run SQL scripts | X | | X | X | X | -| Visual Explain outside of Run SQL scripts | X | | X | | | -| ANALYZE PLAN CACHE procedure | X | | X | | | -| DUMP PLAN CACHE procedure | X | | X | | | -| MODIFY PLAN CACHE procedure | X | | X | | | -| MODIFY PLAN CACHE PROPERTIES procedure (currently does not check authority) | X | | X | | | -| CHANGE PLAN CACHE SIZE procedure (currently does not check authority) | X | | X | | | +| User action | *JOBCTL | QIBM_DB_SECADM | QIBM_DB_SQLADM | QIBM_DB_SYSMON | No Authority | +|-----------------------------------------------------------------------------|-----------|------------------|------------------|------------------|----------------| +| SET CURRENT DEGREE (SQL statement) | X | | X | | | +| CHGQRYA command targeting a different user's job | X | | X | | | +| STRDBMON or ENDDBMON commands targeting a different user's job | X | | X | | | +| STRDBMON or ENDDBMON commands targeting a job that matches the current user | X | | X | X | X | +| QUSRJOBI() API format 900 or System i Navigator's SQL Details for Job | X | | X | X | | +| Visual Explain within Run SQL scripts | X | | X | X | X | +| Visual Explain outside of Run SQL scripts | X | | X | | | +| ANALYZE PLAN CACHE procedure | X | | X | | | +| DUMP PLAN CACHE procedure | X | | X | | | +| MODIFY PLAN CACHE procedure | X | | X | | | +| MODIFY PLAN CACHE PROPERTIES procedure (currently does not check authority) | X | | X | | | +| CHANGE PLAN CACHE SIZE procedure (currently does not check authority) | X | | X | | | The SQL CREATE PERMISSION statement that is shown in Figure 3-1 is used to define and initially enable or disable the row access rules. @@ -252,11 +252,11 @@ Table 3-1 summarizes these special registers and their values. Table 3-1 Special registers and their corresponding values -| Special register | Corresponding value | -| - | - | -| USER or SESSION_USER | The effective user of the thread excluding adopted authority. | -| CURRENT_USER | The effective user of the thread including adopted authority. When no adopted authority is present, this has the same value as USER. | -| SYSTEM_USER | The authorization ID that initiated the connection. | +| Special register | Corresponding value | +|----------------------|--------------------------------------------------------------------------------------------------------------------------------------| +| USER or SESSION_USER | The effective user of the thread excluding adopted authority. | +| CURRENT_USER | The effective user of the thread including adopted authority. When no adopted authority is present, this has the same value as USER. | +| SYSTEM_USER | The authorization ID that initiated the connection. | Figure 3-5 shows the difference in the special register values when an adopted authority is used: @@ -280,17 +280,17 @@ Table 3-2 lists the nine built-in global variables. Table 3-2 Built-in global variables -| Global variable | Type | Description | -| - | - | - | -| CLIENT_HOST | VARCHAR(255) | Host name of the current client as returned by the system | -| CLIENT_IPADDR | VARCHAR(128) | IP address of the current client as returned by the system | -| CLIENT_PORT | INTEGER | Port used by the current client to communicate with the server | -| PACKAGE_NAME | VARCHAR(128) | Name of the currently running package | -| PACKAGE_SCHEMA | VARCHAR(128) | Schema name of the currently running package | -| PACKAGE_VERSION | VARCHAR(64) | Version identifier of the currently running package | -| ROUTINE_SCHEMA | VARCHAR(128) | Schema name of the currently running routine | -| ROUTINE_SPECIFIC_NAME | VARCHAR(128) | Name of the currently running routine | -| ROUTINE_TYPE | CHAR(1) | Type of the currently running routine | +| Global variable | Type | Description | +|-----------------------|--------------|----------------------------------------------------------------| +| CLIENT_HOST | VARCHAR(255) | Host name of the current client as returned by the system | +| CLIENT_IPADDR | VARCHAR(128) | IP address of the current client as returned by the system | +| CLIENT_PORT | INTEGER | Port used by the current client to communicate with the server | +| PACKAGE_NAME | VARCHAR(128) | Name of the currently running package | +| PACKAGE_SCHEMA | VARCHAR(128) | Schema name of the currently running package | +| PACKAGE_VERSION | VARCHAR(64) | Version identifier of the currently running package | +| ROUTINE_SCHEMA | VARCHAR(128) | Schema name of the currently running routine | +| ROUTINE_SPECIFIC_NAME | VARCHAR(128) | Name of the currently running routine | +| ROUTINE_TYPE | CHAR(1) | Type of the currently running routine | ## 3.3 VERIFY\_GROUP\_FOR\_USER function diff --git a/tests/data/pdf/groundtruth/table_mislabeled_as_picture.md b/tests/data/pdf/groundtruth/table_mislabeled_as_picture.md index 3405aa69..2d667a55 100644 --- a/tests/data/pdf/groundtruth/table_mislabeled_as_picture.md +++ b/tests/data/pdf/groundtruth/table_mislabeled_as_picture.md @@ -69,12 +69,12 @@ Other (Please select all that apply) -| | | State funded legal aid | CSOs | -| - | - | - | - | -| y | Persons with disabilities | * | * | -| y | Children | * | * | -| y | Women | * | * | -| y | The elderly | * | * | -| y | Migrants | * | * | -| y | Refugees,asylum seekers,or stateless persons | * | * | -| y | Internally displaced persons | * | * | \ No newline at end of file +| | | State funded legal aid | CSOs | +|----|----------------------------------------------|--------------------------|--------| +| y | Persons with disabilities | * | * | +| y | Children | * | * | +| y | Women | * | * | +| y | The elderly | * | * | +| y | Migrants | * | * | +| y | Refugees,asylum seekers,or stateless persons | * | * | +| y | Internally displaced persons | * | * | \ No newline at end of file diff --git a/tests/pdf_snapshots/latex/sources/2305.03393/llncsdoc.pdf.md b/tests/pdf_snapshots/latex/sources/2305.03393/llncsdoc.pdf.md deleted file mode 100644 index a05dbe5c..00000000 --- a/tests/pdf_snapshots/latex/sources/2305.03393/llncsdoc.pdf.md +++ /dev/null @@ -1,267 +0,0 @@ -## Instructions for Using Springer’s llncs Class for Computer Science Proceedings Papers - -, Version 2.22, Sep 05, 2022 llncs - -## 1 Installation - -Copy llncs.cls to a directory that is searched by LA LAT ATE TEX EX, e.g. either your texmf tree or the local work directory with your main LA LAT ATE TEX EX file. - -## 2 Working with the llncs Document Class - -## 2.1 General Information - -The llncs class is an extension of the standard LA LAT ATE TEX EX article class. Therefore you may use all article commands in your manuscript. - -If you are already familiar with LA LAT ATE TEX EX, the llncs class should not give you any major difficulties. It basically adjusts the layout to the required standard, defining styles and spacing of headings and captions and setting the printing area to 122mm horizontally by 193mm vertically. To keep the layout consistent, we kindly ask you to refrain from using any LA LAT ATE TEX EX or TE TEX EX command that modifies these settings (i.e. \textheight , \vspace , baselinestretch ,etc.). Such manual layout adjustments should be lim ited to very exceptional cases. - -In addition to defining the general layout, the llncs document class pro vides some special commands for typesetting the contribution header, i.e. title, authors, affiliations, abstract, and additional metadata. These special commands are described in Sect. 3 . - -For a more detailed description of how to prepare your text, illustrations, and references, see the Springer Guidelines for Authors of Proceedings . - -## 2.2 How to Use the llncs Document Class - -The llncs class is invoked by replacing article by llncs in the first line of your LA LAT ATE EX document: TEX - -\documentclass{llncs} - -\begin{document} \end{document} If your file is already coded with LA LAT ATE TEX EX, you can easily adapt it to the llncs document class by replacing \documentclass{article} with \documentclass{llncs} - -\begin{document} \end{document} - -If your file is already coded with LA LAT ATE TEX EX, you can easily adapt it to the llncs document class by replacing - -\documentclass{article} with \documentclass{llncs} - -with - -\documentclass{llncs} - -## 3 How to Code the Header of Your Paper - -## 3.1 Title - -\title Please code the title of your contribution as follows: - -\title{} - -All words in titles should be capitalized except for conjunctions, prepositions (e.g. on, of, by, and, or, but, from, with, without, under), and definite/indefinite articles (the, a, an), unless they appear at the beginning. Formula letters are typeset as in the text. Long titles that run over multiple lines can be wrapped explicitly with \\ . Titles have no end punctuation. - -Acknowledgements should generally be placed in an unnumbered subsection at the end of the paper. If you still need to refer to a support or funding program \thanks in a note to the title, you can use the \thanks macro inside the title: - -\title{\thanks{}} - -Please do not use \thanks inside \author \institute as footnotes for these or elements are not supported in the online version and will therefore be dropped. - -If you need two or more footnot es please separate them with \fnmsep (i.e. fo foot n ote m ark sep arator). - -\fnmsep - -If a long title does not fit in the single line of the running head, a warning is generated. You can specify an abbreviated title for the running head with the command - -\titlerunning - -\titlerunning{} - -\subtitle An optional subtitle may also be added: - -\subtitle{} - -## 3.2 Author(s) - -\author The name(s) of the author(s) are specified by: - -\author{} - -\and If there is more than one author, please separate them by \and . This makes sure that correct punctuation is inserted according to the number of authors. - -\inst Numbers referring to different addresses or affiliations should be attached to each author with the \inst{} command. If an author is affiliated with multiple institutions the numbers should be separated by a comma, for example \inst{2,3} . - -\orcidID ORCID identifiers can be included with - -\orcidID{} - -The ORCID (Open Researcher and Contributor ID) registry provides authors with unique digital identifiers that distinguish them from other researchers and help them link their research activities to these identifiers. Authors who are not yet registered with ORCID are encouraged to apply for an individual ORCID id at https://www.orcid.org and to include it in their papers. In the final publication, the ORCID id will be replaced by an ORCID icon, which will link from the eBook to the actual ID in the ORCID database. The ORCID icon will also replace the number in the printed book. - -If you have done this correctly, the author line now reads, for example: - -\author{First Author\inst{1}\orcidID{0000-1111-2222-3333} \and Second Author\inst{2,3}\orcidID{1111-2222-3333-4444}} - -The given name(s) should always be followed by the family name(s). Au thors who have more than one family name should indicate which part of their name represents the family name(s), for example by non-breaking spaces Jos\’{e} Martinez~Perez or curly braces Jos\’{e} {Martinez Perez} . - -As given name(s) are to be shortened to initials in the running heads, speci fying an abbreviated author list with the optional command: - -\authorrunning - -\authorrunning{} - -might add some clarity about the correct representation of author names, in the running-heads as well as in the author index. - -## 3.3 Affiliations - -\institute Addresses of institutes, companies, etc. should be given in \institute . - -Multiple affiliations are separated by \and , which automatically assures cor rect numbering: - -\and - -\institute{ \and \and } \email Inside \institute you can use \email{} \url and \url{} - -\institute{ \and \and } - -\email Inside \institute you can use - -\email{} - -\url and - -\url{} - -to provide author email addresses and Web pages. If you need to typeset the tilde character – e.g. for your Web page in your unix system’s home directory – the \homedir command will do this. If multiple authors have the same affiliation, please check that the order of email addresses matches the sequence of (affiliated) author names. - -Please note that, if email addresses are given in your paper, they will also be included in the metadata of the online version. - -## 3.4 Format the Header - -\maketitle The command \maketitle formats the header of your paper. If you leave it out the work done so far will produce no text. - -## 3.5 Abstract and Keywords - -abstract ( env. ) The abstract is coded as follows: - -abstract ( env. ) The abstract is coded as follows: \begin{abstract} \end{abstract} - -\begin{abstract} \end{abstract} - -\keywords Keywords should be specified inside the abstract environment. Please capitalize \and the first letter of each keyword and again separate them with \and : - -\keywords{First keyword \and Second keyword \and Third keyword} - -The keyword separator will then be properly rendered as a middle dot. - -## 4 How to Code the Body of Your Paper - -## 4.1 General Rules - -From a technical point of view, the llncs document class does not require any specific LA LAT ATE TEX EX coding in the body of your paper. You can simply use the com mands provided by the ‘article’ document class. For more information about what will be done with your manuscript before publication, please refer to the Springer Guidelines for Authors of Proceedings . - -## 4.2 Special Math Characters - -The llncs document class supports some additional special characters: - -\grole yields >< >< \getsto yields ← → \lid yields < \gid yields > = = - -If you need blackboard bold characters, i.e. for sets of numbers, please load the related AM AMS MS- S-TE TEX EXfonts. If for some reason this is not possible you can also use the following commands from the llncs class: - -| \bbbc | yields | C | \bbbf | yields IF | | -|---------|-----------|-----|---------|-------------|-------| -| \bbbh | yields IH | | \bbbk | yields IK | | -| \bbbm | yields IM | | \bbbn | yields IN | | -| \bbbp | yields IP | | \bbbq | yields | Q | -| \bbbr | yields IR | | \bbbs | yields | S | -| \bbbt | yields | T | \bbbz | yields | ZZ ZZ | -| \bbbone | yields 1l | | | | | - -Please note that all these characters are only available in math mode. - -## 5 Theorems, Definitions, and Proofs - -## 5.1 Predefined Theorem-Like Environments - -corollary ( env. ) Several theorem-like environments are predefined in the llncs document class. ( ) The following environments have a bold run-in heading, while the following text definition env. lemma ( env. ) is in italics: - -( ) proposition env. - -\begin{corollary} \end{corollary} theorem ( env. ) \begin{definition} \end{definition} \begin{lemma} \end{lemma} \begin{proposition} \end{proposition} \begin{theorem} \end{theorem} - -( ) Other theorem-like environments render the text in roman, while the run-in case env. conjecture ( env. ) heading is bold as well: - -example ( env. ) - -( ) \begin{case} \end{case} exercise env. \begin{conjecture} \end{conjecture} note ( env. ) \begin{example} \end{example} problem ( env. ) ( ) \begin{exercise} \end{exercise} property env. \begin{note} \end{note} question ( env. ) \begin{problem} \end{problem} remark ( env. ) \begin{property} \end{property} ( ) solution env. \begin{question} \end{question} \begin{remark} \end{remark} \begin{solution} \end{solution} - -claim ( env. ) Finally, there are also two unnumbered environments that have the run-in head proof ( env. ) ing in italics and the text in upright roman. - -\begin{claim} \end{claim} \begin{proof} \end{proof} - -\qed Proofs may contain an eye catching square, which can be inserted with \qed ) before the environment ends. - -## 5.2 User-Defined Theorem-Like Environments - -\spnewtheorem We have enhanced the standard \newtheorem command and slightly changed its syntax to get two new commands \spnewtheorem and \spnewtheorem* that now can be used to define additional environments. They require two additional arguments, namely the font style of the label and the font style of the text of the new environment: - -\spnewtheorem{}[]{}{}{} - -\spnewtheorem{}[]{}{}{} For example, \spnewtheorem{maintheorem}[theorem]{Main Theorem}{\bfseries}{\itshape} - -For example, - -\spnewtheorem{maintheorem}[theorem]{Main Theorem}{\bfseries}{\itshape} - -will create a main theorem environment that is numbered together with the predefined theorem . The sharing of the default counter ( [theorem] ) is desired. If you omit the optional second argument of \spnewtheorem , a separate counter for your new environment is used throughout your document. - -In combination with the (o bsolete) class option envcountsect (see. Sect. 7 ), the \spnewtheorem command also supports the syntax: - -\spnewtheorem{}{}[]{}{} - -With the parameter , you can control the sectio ning element that resets the theorem counters. If you specify, for example, subsection , the newly defined environment is numbered subsectionwise. - -If you wish to add an unnumbered environment, please use the syntax - -\spnewtheorem* - -\spnewtheorem*{}{}{}{} - -## 6 References - -There are three options for citing references: - -– arabic numbers, i.e. [1], [3–5], [4–6,9], – labels, i.e. [CE1], [AB1,XY2], – author/year system, (Smith et al. 2000), (Miller 1999a, 12; Brown 2018). - -- – arabic numbers, i.e. [1], [3–5], [4–6,9], -- – labels, i.e. [CE1], [AB1,XY2], -- – author/year system, (Smith et al. 2000), (Miller 1999a, 12; Brown 2018). - -We prefer citations with arabic numbers, i.e. the usage of \bibitem without an optional parameter. If you want to use the author/year system, you can use the class option citeauthoryear , i.e. - -citeauthoryear - -\documentclass[citeauthoryear]{llncs} - -Please note that this option does not automatically change your citations to the author/year style. It basically redefines the \bibitem command to take the publication year as an optional parameter that is displayed instead of an arabic number. Author name(s) and, if necessary , parentheses are to be typed manually. If your reference reads - -\bibitem[2016]{vdaalst:2016} van der Aalst, W.: Process Mining, 2nd ed. Springer, Heidelberg (2016) and is cited as follows: ... is shown by van der Aalst (\cite{vdaalst:2016}) the resulting text will be: “. .. is shown by van der Aalst (2016).” - -We encourage you to use Bib TE TEX EX for typesetting your references. For for matting the bibliography according to Springer’s standard (for mathematics, physical sciences, and computer science), please use the bibliography style file splncs04.bst that comes with the llncs document class. You simply need to add \bibliographystyle{splncs04} to your document. DOIs should be pro vided in the doi field of your .bib database. Bib TE TEX EX will then automatically add them to your references. Please note that we do not provide an option to implement - -splncs04.bst - -\doi If you do not use Bib TE TEX EX, you can include a DOI with the \doi command: - -- \doi If you do not use Bib TE TEX EX, you can include a DOI with the \doi command: \doi{} - -\doi{} - -The DOI will be expanded to the URL https://doi.org/ in accordance with the CrossRef guidelines. - -## 7 Obsolete Class Options - -The document class contains several cl ass options that have become ob llncs solete over the years. We only mention them for completeness: - -- orivec – The llncs document class changes the for matting of vectors coded with \vec to boldface italics. If you absolutely need the original LA LAT ATE EX design for TEX vectors, i.e. an arrow above the related variable, you can restore it with the orivec option. -- – All theorem-like environments share one counter, i.e. Theorem 1, Lemma 2, Corollary 3, etc. - -envcountsame - -- – All theorem-like environments are numbered per section, i.e. the related counters are reset to 1 in every section. - -envcountreset - -- – All theorem-like environments are nu mbered per section, and the section number added to the individual counter, i.e. Theorem 1.2, Lemma 2.2, etc. - -envcountsect - -- – This option produces the “open” bibliography style, in which each block starts on a new line, and succeeding lines in a block are indented by \bibindent . - -openbib - -- oribibl – This option restores the original LA LAT ATE TEX EX definitions for the bibliography and the \cite mechanism that some Bib TE EX applications rely on. TEX diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi.pdf.md b/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi.pdf.md deleted file mode 100644 index 3c0ca03e..00000000 --- a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi.pdf.md +++ /dev/null @@ -1,20 +0,0 @@ -## Aux-Loss-Based Layer 9 - - - -- Wikipedia (en) Gihb -- DM Mathematics - - - -- Wikipedia (en) Gihb () Github DM Mathematics - - - -- Wikipedia (en) Gihb -- DM Mathematics - - - -- Wikipedia (en) Gihb -- DM Mathematics diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_1-6.pdf.md b/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_1-6.pdf.md deleted file mode 100644 index 21b10ab4..00000000 --- a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_1-6.pdf.md +++ /dev/null @@ -1,3 +0,0 @@ -## Aux-Loss-Based Layer 1 - - diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_7-12.pdf.md b/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_7-12.pdf.md deleted file mode 100644 index 64e8bb00..00000000 --- a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_7-12.pdf.md +++ /dev/null @@ -1,11 +0,0 @@ -## Aux-Loss-Based Layer 7 - - - -Wikipedia (en) Github DM Mathematics 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 - -Wikipedia (en) Github DM Mathematics 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 - -Wikipedia (en) Github DM Mathematics 1 2 11 12 14 17 21 22 24 27 41 42 - -Wikipedia (en) Github DM Mathematics 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 diff --git a/tests/pdf_snapshots/mets_gbs/sources/32044009881525_select.tar.gz.md b/tests/pdf_snapshots/mets_gbs/sources/32044009881525_select.tar.gz.md deleted file mode 100644 index 5f2e2f41..00000000 --- a/tests/pdf_snapshots/mets_gbs/sources/32044009881525_select.tar.gz.md +++ /dev/null @@ -1,85 +0,0 @@ -recently become prevalent that he who speaks of military power is a " militarist . " This , how- reverse assertion ever , is as great a fallacy as the that he who talks of nothing but peace is a 66 pacifist . " - -Truth , even bitter truth , is better than the most high - minded fallacy . - -The author has visited Japan , Siberia , China , the Philippines , the Malay States , and Hawaii in 1919 and 1920 , and his personal impressions and investigations form the basis of the present book . The list of works which he has perused in the course of his investigation of the problem of the Pacific is hereto appended . - -The author wishes to acknowledge his debt to Admiral A. D. Bubnov , who has contributed Chapters VII - X . Admiral Bubnov took part in the Russo - Japanese War , was Professor of the Naval Staff College at Petrograd , and Chief of the Naval Section of the Staff of the Supreme Commander - in - Chief in the Great War . The Admiral is an authoritative student of the questions of naval strategy discussed in the chapters that belong to his pen . - -The author also has to thank Mr. C. Nabokoff , the late Russian Chargé d'Affaires in London , book . for undertaking the translation of his - -## 62 THE PROBLEM OF THE PACIFIC - -copper mines with up - to - date technical equip- ment in various provinces of Central China ¹ : — - -| | Provinces | | | . | Iron | . | Coal | . | Copper | | . | -|----------|-------------|------|-----|-----|--------|-----|--------|-----|----------|----|-----| -| Shensi | | | | | | 9 | | 34 | | 3 | | -| | | | ... | | | | | | | | | -| Shantung | | | . | | | 8 | | 29 | | - | | -| Hupeh | | | | | | 21 | | 10 | | 7 | | -| Chihli | | | | | | | 48 | | | 2 | | -| Ho | - Han | | | | | | | 28 | | | | -| Kiang | | - si | . | | | | | 14 | | | | -| Anh | - wei | | | | | | | 8 | | | | -| Hunan | | | | | | | | 3 | | | | -| Kiang | | - su | | | | | | 2 | | | | -| Sze | - chwan | | | | | | | | | 3 | | -| Kweichow | | | | | | | | | | 2 | | -| Yunnan | | | | | | | | | | 44 | | -| | | | | | | 20 | 177 | | | 61 | | - -It has been mentioned in one of the preceding chapters that Japanese industries needed iron . The desire to obtain the necessary supplies of iron is thus perfectly legitimate . Japan's endea- vour to acquire concessions for the production of iron and coal is not , therefore , a proof of the Imperialism of her policy . But , as the French saying goes , Le ton fait la chanson . Japan is trying to get hold of the entire iron industry of China . She is doing so by the veiled seizure of political and administrative control of the respective provinces of China . To Europe and America this is presented under the guise of the nebulous formula of 66 special interests in the regions of China adjacent to Japan . " Man- churia and Shantung are first in that list . When Japan succeeds , she will have deprived China - -1 These data relate to 1915 . - -## 252 THE PROBLEM OF THE PACIFIC - -France may lay down new tonnage in the years 1927 , 1929 , and 1931 , as provided in Part 3 , Section II . - -Ships which may be retained by Italy . - -| | Ships | | which | | may | be | retained | by | Italy | . | | | -|----------|---------|-----------|----------|---------|-------|------|------------|------|----------|---------|------|-----| -| | | | | | | | | | | Tonnage | | | -| | Name | . | | | | | | | ( metric | | tons | ) . | -| Andrea | | Doria | | | | | | | | 22,700 | | | -| | | | | .. | | | | | | | | | -| Caio | Duilio | | | | | | | | | 22,700 | | | -| Conte | | Di | Cavour | | | | | | | 22,500 | | | -| Giulio | | Cesare | | | | | | | | 22,500 | | | -| Leonardo | | | da | Vinci | | | | | | 22,500 | | | -| Dante | | Alighieri | | | | | | | | 19,500 | | | -| Roma | | | | | | | | | | 12,600 | | | -| Napoli | | | | | | | | | | 12,600 | | | -| | | .. | | | | | | | | | | | -| Vittorio | | | Emanuele | | | | | | | 12,600 | | | -| Regina | | Elena | | | | | | | | 12,600 | | | -| | | | Total | tonnage | | | | | | 182,800 | | | -| | | | | | | | | .. | | | | | - -Italy may lay down new tonnage in the years 1927 , 1929 and 1931 , as provided in Part 3 , Section II . - -| | Ships | which | may | be | retained | by | Japan | | . | | -|-----------|---------|---------|---------|------|------------|------|---------|---------|-----|----| -| | Name | . | | | | | | Tonnage | | . | -| Mutsu | | | | | | | | 33,800 | | | -| | | .. | | | | | | | | | -| Nagato | | | | | | | | 33,800 | | | -| Hiuga | | | | | | | | 31,260 | | | -| Ise | | | | | | | | 31,260 | | | -| Yamashiro | | | | | | | | 30,600 | | | -| Fu | - So | .. | | | | | | 30,600 | | | -| Kirishima | | | | | | | | 27,500 | | | -| Haruna | | | | | | | | 27,500 | | | -| | | .. | | | | | .. | | | | -| Hiyei | | | | | | | | 27,500 | | | -| | | .. | | | | | .. | | | | -| Kon | - go | .. | | | | | | 27,500 | | | -| | | Total | tonnage | | | | | 301,320 | | | - -- Part 2. — RULES FOR SCRAPPING VESSELs of War . The following rules shall be observed for the scrapping of vessels of war which are to be disposed of in accordance with Articles II and III . -- I. A vessel to be scrapped must be placed in such condition that it cannot be put to combative use . -- II . This result must be finally effected in any one of the following ways : -- ( a ) Permanent sinking of the vessel ; -- ( b ) Breaking the vessel up . This shall always involve the destruction or removal of all machinery , boilers and armour , and all deck , side and bottom plating ; diff --git a/tests/pdf_snapshots/odf/sources/odf_presentation_01.odp.pdf.md b/tests/pdf_snapshots/odf/sources/odf_presentation_01.odp.pdf.md deleted file mode 100644 index 8afd37aa..00000000 --- a/tests/pdf_snapshots/odf/sources/odf_presentation_01.odp.pdf.md +++ /dev/null @@ -1,11 +0,0 @@ -## Class1 ● - -False ● True ● C ● Test Table Slide False ● True ● False ● False ● False True ● ● ● B A ● ● ● Class2 ● - - - -- • • S - -Item B • tem A I • S ome info: - -- I diff --git a/tests/pdf_snapshots/odf/sources/text_document_02.odt.pdf.md b/tests/pdf_snapshots/odf/sources/text_document_02.odt.pdf.md deleted file mode 100644 index f5ecb267..00000000 --- a/tests/pdf_snapshots/odf/sources/text_document_02.odt.pdf.md +++ /dev/null @@ -1,18 +0,0 @@ -## Title - -## heading level 1.0 - -Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since 1966. - -## Heading level 2: A - -Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. - -| Merged row | Cell 1.3 | Cell 1.4 | Cell 1.5 | Cell 1.6 | Cell 1.7 | -|--------------|-----------------|------------|------------|------------|------------| -| | Merged cell 2x2 | | | Merged | | -| | | | | column | | - - - - diff --git a/tests/pdf_snapshots/odf/sources/text_document_03.odt.pdf.md b/tests/pdf_snapshots/odf/sources/text_document_03.odt.pdf.md deleted file mode 100644 index 324441dd..00000000 --- a/tests/pdf_snapshots/odf/sources/text_document_03.odt.pdf.md +++ /dev/null @@ -1,70 +0,0 @@ -## Table with rich cells - -| Column A | | | Column B | | | | | | | | | -|----------------------------------------|----|--------------|---------------------------|----|-----|--------|-----|--------|-------------------|----|----| -| This is a list: | | | This is a formatted list: | | | | | | | | | -| | • | A First | | • | B | First | | | | | | -| | • | A Second | | • | B | Second | | | | | | -| | • | A Third | | • | B | Third | | | | | | -| First Paragraph | | | This is simple text with | | | | | | bold | | | -| | | | | | | | | | | , | | -| | | | strikethrough | | | | and | italic | formatting with x | | 2 | -| Second Paragraph | | | and H | | 2 O | | | | | | | -| Third paragraph before a numbered list | | | | | | | | | | | | -| | 1. | Number one | | | | | | | | | | -| | 2. | Number two | | | | | | | | | | -| | 3. | Number three | | | | | | | | | | -| This is a paragraph | | | | | | | | | | | | -| This is another paragraph | | | | | | | | | | | | - -## Table with nested table - -Before table - -| Column A | | | Column B | | | | | -|------------------------|--------|--------|------------------|--------|-----|--------|--------| -| Simple cell upper left | | | Simple cell with | bold | and | italic | text | -| A | B | C | Rich cell | | | | | -| Cell 1 | Cell 2 | Cell 3 | A nested table | | | | | -| | | | A | B | | | C | -| | | | Cell 1 | Cell 2 | | | Cell 3 | - -After table with bold underline strikethrough , and italic formatting - -## Table with pictures - -| Column A | Column B | -|------------------|------------| -| Only text | | -| Text and picture | | - -## Lists with same numId in different cells - -| • | Cell 1 item 1 | -|-----|-----------------| -| • | Cell 1 item 2 | -| • | Cell 2 item 1 | -| • | Cell 2 item 2 | - -## Lists with different numIds in different cells - -| • | Cell 1 item 1 | | -|-----|-----------------|---------------| -| • | Cell 1 item 2 | | -| | • | Cell 2 item 1 | -| | • | Cell 2 item 2 | - -## Multiple columns with lists - -| • | R1C1 item 1 | • | R1C2 item 1 | -|-----|---------------|-----|---------------| -| • | R1C1 item 2 | • | R1C2 item 2 | -| • | R2C1 item 1 | • | R2C2 item 1 | -| • | R2C1 item 2 | • | R2C2 item 2 | - -## Mixed content - list and regular text in different cells - -| • | List item 1 | -|-----------------------------|---------------| -| • | List item 2 | -| Regular text in second cell | | diff --git a/tests/pdf_snapshots/pdf/sources/2203.01017v2.pdf.md b/tests/pdf_snapshots/pdf/sources/2203.01017v2.pdf.md deleted file mode 100644 index 2fdf3fe0..00000000 --- a/tests/pdf_snapshots/pdf/sources/2203.01017v2.pdf.md +++ /dev/null @@ -1,424 +0,0 @@ -# TableFormer: Table Structure Understanding with Transformers. - -Ahmed Nassar, Nikolaos Livathinos, Maksym Lysak, Peter Staar IBM Research - -{ ahn,nli,mly,taa } @zurich.ibm.com - -## Abstract - -Tables organize valuable content in a concise and com pact representation. This content is extremely valuable for systems such as search engines, Knowledge Graph’s, etc, since they enhance their predictive capabilities. Unfortu nately, tables come in a large variety of shapes and sizes. Furthermore, they can have complex column/row-header configurations, multiline rows, different variety of separa tion lines, missing entries, etc. As such, the correct iden tification of the table-structure from an image is a non trivial task. In this paper, we present a new table-structure identification model. The latter improves the latest end-to end deep learning model (i.e. encoder-dual-decoder from PubTabNet) in two significant ways. First, we introduce a new object detection decoder for table-cells. In this way, we can obtain the content of the table-cells from program matic PDF’s directly from the PDF source and avoid the training of the custom OCR decoders. This architectural change leads to more accurate table-content extraction and allows us to tackle non-english tables. Second, we replace the LSTM decoders with transformer based decoders. This upgrade improves significantly the previous state-of-the-art tree-editing-distance-score (TEDS) from 91% to 98.5% on simple tables and from 88.7% to 95% on complex tables. - -## 1. Introduction - -The occurrence of tables in documents is ubiquitous. They often summarise quantitative or factual data, which is cumbersome to describe in verbose text but nevertheless ex tremely valuable. Unfortunately, this compact representa tion is often not easy to parse by machines. There are many implicit conventions used to obtain a compact table repre sentation. For example, tables often have complex column and row-headers in order to reduce duplicated cell content. Lines of different shapes and sizes are leveraged to separate content or indicate a tree structure. Additionally, tables can also have empty/missing table-entries or multi-row textual table-entries. Fig. 1 shows a table which presents all these issues. - -## a. Picture of a table: - - - -| | | 1 | -|----|----|-----| -| | 3 | | -| 2 | | | - -- b. Red-annotation of bounding boxes, Blue-predictions by TableFormer - - - -- c. Structure predicted by TableFormer: - -| 0 | | 1 | | 2 | | 1 | | -|-----|----|-----|----|-----|----|-----|----| -| 3 | | 4 | 3 | 5 | 6 | | 7 | -| | | 9 | | 10 | 11 | | 12 | -| 8 | 2 | 13 | | 14 | 15 | | 16 | -| | | 17 | | 18 | 19 | | 20 | - -Figure 1: Picture of a table with subtle, complex features such as (1) multi-column headers, (2) cell with multi-row text and (3) cells with no content. Image from PubTabNet evaluation set, filename: ‘PMC2944238 004 02’. - -Recently, significant progress has been made with vi sion based approaches to extract tables in documents. For the sake of completeness, the issue of table extraction from documents is typically decomposed into two separate chal lenges, i.e. (1) finding the location of the table(s) on a document-page and (2) finding the structure of a given table in the document. - -The first problem is called table-location and has been previously addressed [ 30 38 19 21 23 26 8 ] with state of-the-art object-detection networks (e.g. YOLO and later , , , , , , on Mask-RCNN [ 9 ]). For all practical purposes, it can be - -considered as a solved problem, given enough ground-truth data to train on. - -The second problem is called table-structure decompo sition. The latter is a long standing problem in the com munity of document understanding [ 6 , 4 , 14 ]. Contrary to the table-location problem, there are no commonly used ap proaches that can easily be re-purposed to solve this prob lem. Lately, a set of new model-architectures has been pro posed by the community to address table-structure decom position [ 37 36 18 20 ]. All these models have some weak , , , nesses (see Sec. 2 ). The common denominator here is the reliance on textual features and/or the inability to provide the bounding box of each table-cell in the original image. - -In this paper, we want to address these weaknesses and present a robust table-structure decomposition algorithm. The design criteria for our model are the following. First, we want our algorithm to be language agnostic. In this way, we can obtain the structure of any table, irregardless of the language. Second, we want our algorithm to leverage as much data as possible from the original PDF document. For programmatic PDF documents, the text-cells can often be extracted much faster and with higher accuracy compared to OCR methods. Last but not least, we want to have a di rect link between the table-cell and its bounding box in the image. - -To meet the design criteria listed above, we developed a new model called TableFormer and a synthetically gener 1 ated table structure dataset called SynthTabNet . In partic ular, our contributions in this work can be summarised as follows: - -- • We propose TableFormer , a transformer based model that predicts tables structure and bounding boxes for the table content simultaneously in an end-to-end ap proach. -- • Across all benchmark datasets TableFormer signif icantly outperforms existing state-of-the-art metrics, while being much more efficient in training and infer ence to existing works. -- We present SynthTabNet a synthetically generated • dataset, with various appearance styles and complex ity. -- • An augmented dataset based on PubTabNet [ 37 ], FinTabNet [ 36 ], and TableBank [ 17 ] with generated ground-truth for reproducibility. - -The paper is structured as follows. In Sec. 2 , we give a brief overview of the current state-of-the-art. In Sec. 3 we describe the datasets on which we train. In Sec. 4 , we , introduce the TableFormer model-architecture and describe - -1 https://github.com/IBM/SynthTabNet - -its results & performance in Sec. 5 . As a conclusion, we de scribe how this new model-architecture can be re-purposed for other tasks in the computer-vision community. - -## 2. Previous work and State of the Art - -Identifying the structure of a table has been an outstand ing problem in the document-parsing community, that mo tivates many organised public challenges [ 6 , 4 , 14 ]. The difficulty of the problem can be attributed to a number of factors. First, there is a large variety in the shapes and sizes of tables. Such large variety requires a flexible method. This is especially true for complex column- and row head ers, which can be extremely intricate and demanding. A second factor of complexity is the lack of data with regard to table-structure. Until the publication of PubTabNet [ 37 ], there were no large datasets (i.e. > 100 K tables) that pro vided structure information. This happens primarily due to the fact that tables are notoriously time-consuming to an notate by hand. However, this has definitely changed in re cent years with the deliverance of PubTabNet [ 37 ], FinTab Net [ 36 ], TableBank [ 17 ] etc. - -Before the rising popularity of deep neural networks, the community relied heavily on heuristic and/or statistical methods to do table structure identification [ 3 7 11 5 13 28 ]. Although such methods work well on constrained ta , , , , , bles [ 12 ], a more data-driven approach can be applied due to the advent of convolutional neural networks (CNNs) and the availability of large datasets. To the best-of-our knowl edge, there are currently two different types of network ar chitecture that are being pursued for state-of-the-art table structure identification. - -Image-to-Text networks : In this type of network, one predicts a sequence of tokens starting from an encoded image. Such sequences of tokens can be HTML table tags [ 37 , 17 ] or LaTeX symbols[ 10 ]. The choice of sym bols is ultimately not very important, since one can be trans formed into the other. There are however subtle variations in the Image-to-Text networks. The easiest network archi tectures are “image-encoder → text-decoder” (IETD), sim ilar to network architectures that try to provide captions to images [ 32 ]. In these IETD networks, one expects as output the LaTeX/HTML string of the entire table, i.e. the sym bols necessary for creating the table with the content of the table. Another approach is the “image-encoder → dual de coder” (IEDD) networks. In these type of networks, one has two consecutive decoders with different purposes. The first decoder is the tag-decoder , i.e. it only produces the HTM L/LaTeX tags which construct an empty table. The second content-decoder uses the encoding of the image in combi nation with the output encoding of each cell-tag (from the tag-decoder ) to generate the textual content of each table cell. The network architecture of IEDD is certainly more elaborate, but it has the advantage that one can pre-train the - -tag-decoder which is constrained to the table-tags. - -In practice, both network architectures (IETD and IEDD) require an implicit, custom trained object-character recognition (OCR) to obtain the content of the table-cells. In the case of IETD, this OCR engine is implicit in the de coder similar to [ 24 ]. For the IEDD, the OCR is solely em bedded in the content-decoder. This reliance on a custom, implicit OCR decoder is of course problematic. OCR is a well known and extremely tough problem, that often needs custom training for each individual language. However, the limited availability for non-english content in the current datasets, makes it impractical to apply the IETD and IEDD methods on tables with other languages. Additionally, OCR can be completely omitted if the tables originate from pro grammatic PDF documents with known positions of each cell. The latter was the inspiration for the work of this pa per. - -Graph Neural networks : Graph Neural networks (GNN’s) take a radically different approach to table structure extraction. Note that one table cell can consti tute out of multiple text-cells. To obtain the table-structure, one creates an initial graph, where each of the text-cells becomes a node in the graph similar to [ 33 , 34 , 2 ]. Each node is then associated with en embedding vector coming from the encoded image, its coordinates and the encoded text. Furthermore, nodes that represent adjacent text-cells are linked. Graph Convolutional Networks (GCN’s) based methods take the image as an input, but also the position of the text-cells and their content [ 18 ]. The purpose of a GCN is to transform the input graph into a new graph, which re places the old links with new ones. The new links then represent the table-structure. With this approach, one can avoid the need to build custom OCR decoders. However, the quality of the reconstructed structure is not comparable to the current state-of-the-art [ 18 ]. - -Hybrid Deep Learning-Rule-Based approach : A pop ular current model for table-structure identification is the use of a hybrid Deep Learning-Rule-Based approach similar to [ 27 29 ]. In this approach, one first detects the position of the table-cells with object detection (e.g. YoloVx or Mask , RCNN), then classifies the table into different types (from its images) and finally uses different rule-sets to obtain its table-structure. Currently, this approach achieves state of-the-art results, but is not an end-to-end deep-learning method. As such, new rules need to be written if different types of tables are encountered. - -## 3. Datasets - -We rely on large-scale datasets such as PubTabNet [ 37 ], FinTabNet [ 36 ], and TableBank [ 17 ] datasets to train and evaluate our models. These datasets span over various ap pearance styles and content. We also introduce our own synthetically generated SynthTabNet dataset to fix an im - - - -Figure 2: Distribution of the tables across different table dimensions in PubTabNet + FinTabNet datasets - -balance in the previous datasets. - -The PubTabNet dataset contains 509k tables delivered as annotated PNG images. The annotations consist of the table structure represented in HTML format, the tokenized text and its bounding boxes per table cell. Fig. 1 shows the ap pearance style of PubTabNet. Depending on its complexity, a table is characterized as “simple” when it does not contain row spans or column spans, otherwise it is “complex”. The dataset is divided into Train and Val splits (roughly 98% and 2%). The Train split consists of 54% simple and 46% com plex tables and the Val split of 51% and 49% respectively. The FinTabNet dataset contains 112k tables delivered as single-page PDF documents with mixed table structures and text content. Similarly to the PubTabNet, the annotations of FinTabNet include the table structure in HTML, the to kenized text and the bounding boxes on a table cell basis. The dataset is divided into Train, Test and Val splits (81%, 9.5%, 9.5%), and each one is almost equally divided into simple and complex tables (Train: 48% simple, 52% com plex, Test: 48% simple, 52% complex, Test: 53% simple, 47% complex). Finally the TableBank dataset consists of 145k tables provided as JPEG images. The latter has anno tations for the table structure, but only few with bounding boxes of the table cells. The entire dataset consists of sim ple tables and it is divided into 90% Train, 3% Test and 7% Val splits. - -Due to the heterogeneity across the dataset formats, it was necessary to combine all available data into one homog enized dataset before we could train our models for practi cal purposes. Given the size of PubTabNet, we adopted its annotation format and we extracted and converted all tables as PNG images with a resolution of 72 dpi. Additionally, we have filtered out tables with extreme sizes due to small - -amount of such tables, and kept only those ones ranging between 1*1 and 20*10 (rows/columns). - -The availability of the bounding boxes for all table cells is essential to train our models. In order to distinguish be tween empty and non-empty bounding boxes, we have in troduced a binary class in the annotation. Unfortunately, the original datasets either omit the bounding boxes for whole tables (e.g. TableBank) or they narrow their scope only to non-empty cells. Therefore, it was imperative to introduce a data pre-processing procedure that generates the missing bounding boxes out of the annotation information. This pro cedure first parses the provided table structure and calcu lates the dimensions of the most fine-grained grid that cov ers the table structure. Notice that each table cell may oc cupy multiple grid squares due to row or column spans. In case of PubTabNet we had to compute missing bounding boxes for 48% of the simple and 69% of the complex ta bles. Regarding FinTabNet, 68% of the simple and 98% of the complex tables require the generation of bounding boxes. - -As it is illustrated in Fig. 2 , the table distributions from all datasets are skewed towards simpler structures with fewer number of rows/columns. Additionally, there is very limited variance in the table styles, which in case of Pub TabNet and FinTabNet means one styling format for the majority of the tables. Similar limitations appear also in the type of table content, which in some cases (e.g. FinTab Net) is restricted to a certain domain. Ultimately, the lack of diversity in the training dataset damages the ability of the models to generalize well on unseen data. - -Motivated by those observations we aimed at generating a synthetic table dataset named SynthTabNet . This approach offers control over: 1) the size of the dataset, 2) the table structure, 3) the table style and 4) the type of content. The complexity of the table structure is described by the size of the table header and the table body, as well as the percentage of the table cells covered by row spans and column spans. A set of carefully designed styling templates provides the basis to build a wide range of table appearances. Lastly, the table content is generated out of a curated collection of text corpora. By controlling the size and scope of the synthetic datasets we are able to train and evaluate our models in a variety of different conditions. For example, we can first generate a highly diverse dataset to train our models and then evaluate their performance on other synthetic datasets which are focused on a specific domain. - -In this regard, we have prepared four synthetic datasets, each one containing 150k examples. The corpora to gener ate the table text consists of the most frequent terms appear ing in PubTabNet and FinTabNet together with randomly generated text. The first two synthetic datasets have been fine-tuned to mimic the appearance of the original datasets but encompass more complicated table structures. The third - -| | Tags Bbox Size Format | | | -|--------------------|-------------------------|----|-----------| -| PubTabNet | ✓ | ✓ | 509k PNG | -| FinTabNet | ✓ | ✓ | 112k PDF | -| TableBank | ✓ | ✗ | 145k JPEG | -| Combined-Tabnet(*) | ✓ | ✓ | 400k PNG | -| Combined(**) | ✓ | ✓ | 500k PNG | -| SynthTabNet | ✓ | ✓ | 600k PNG | - -Table 1: Both “Combined-Tabnet” and ”Combined Tabnet” are variations of the following: (*) The Combined Tabnet dataset is the processed combination of PubTabNet and Fintabnet. (**) The combined dataset is the processed combination of PubTabNet, Fintabnet and TableBank. - -one adopts a colorful appearance with high contrast and the last one contains tables with sparse content. Lastly, we have combined all synthetic datasets into one big unified syn thetic dataset of 600k examples. - -Tab. 1 summarizes the various attributes of the datasets. - -## 4. The TableFormer model - -Given the image of a table, TableFormer is able to pre dict: 1) a sequence of tokens that represent the structure of a table, and 2) a bounding box coupled to a subset of those tokens. The conversion of an image into a sequence of to kens is a well-known task [ 35 16 ]. While attention is often , used as an implicit method to associate each token of the sequence with a position in the original image, an explicit association between the individual table-cells and the image bounding boxes is also required. - -## 4.1. Model architecture. - -We now describe in detail the proposed method, which is composed of three main components, see Fig. 4 . Our CNN Backbone Network encodes the input as a feature vec tor of predefined length. The input feature vector of the encoded image is passed to the Structure Decoder to pro duce a sequence of HTML tags that represent the structure of the table. With each prediction of an HTML standard data cell (‘ < td > ’) the hidden state of that cell is passed to the Cell BBox Decoder. As for spanning cells, such as row or column span, the tag is broken down to ‘ < ’, ‘rowspan= ’ or ‘colspan= ’, with the number of spanning cells (attribute), and ‘ > ’. The hidden state attached to ‘ < ’ is passed to the Cell BBox Decoder. A shared feed forward network (FFN) receives the hidden states from the Structure Decoder, to provide the final detection predictions of the bounding box coordinates and their classification. - -CNN Backbone Network. A ResNet-18 CNN is the backbone that receives the table image and encodes it as a vector of predefined length. The network has been modified by removing the linear and pooling layer, as we are not per - - - -Figure 3: TableFormer takes in an image of the PDF and creates bounding box and HTML structure predictions that are synchronized. The bounding boxes grabs the content from the PDF and inserts it in the structure. - - - -Figure 4: Given an input image of a table, the Encoder pro duces fixed-length features that represent the input image. The features are then passed to both the Structure Decoder and Cell BBox Decoder . During training, the Structure Decoder receives ‘tokenized tags’ of the HTML code that represent the table structure. Afterwards, a transformer en coder and decoder architecture is employed to produce fea tures that are received by a linear layer, and the Cell BBox Decoder. The linear layer is applied to the features to predict the tags. Simultaneously, the Cell BBox Decoder selects features referring to the data cells (‘ < td > ’, ‘ < ’) and passes them through an attention network, an MLP, and a linear layer to predict the bounding boxes. - -forming classification, and adding an adaptive pooling layer of size 28*28. ResNet by default downsamples the image resolution by 32 and then the encoded image is provided to both the Structure Decoder , and Cell BBox Decoder . - -Structure Decoder. The transformer architecture of this component is based on the work proposed in [ 31 ]. After extensive experimentation, the Structure Decoder is mod eled as a transformer encoder with two encoder layers and a transformer decoder made from a stack of 4 decoder lay ers that comprise mainly of multi-head attention and feed forward layers. This configuration uses fewer layers and heads in comparison to networks applied to other problems (e.g. “Scene Understanding”, “Image Captioning”), some thing which we relate to the simplicity of table images. - -The transformer encoder receives an encoded image from the CNN Backbone Network and refines it through a multi-head dot-product attention layer, followed by a Feed Forward Network. During training, the transformer de coder receives as input the output feature produced by the transformer encoder, and the tokenized input of the HTML ground-truth tags. Using a stack of multi-head attention lay ers, different aspects of the tag sequence could be inferred. This is achieved by each attention head on a layer operating in a different subspace, and then combining altogether their attention score. - -Cell BBox Decoder. Our architecture allows to simul taneously predict HTML tags and bounding boxes for each table cell without the need of a separate object detector end to end. This approach is inspired by DETR [ 1 ] which em ploys a Transformer Encoder, and Decoder that looks for a specific number of object queries (potential object detec tions). As our model utilizes a transformer architecture, the hidden state of the < td > ’ and ‘ < ’ HTML structure tags be come the object query. - -The encoding generated by the CNN Backbone Network along with the features acquired for every data cell from the Transformer Decoder are then passed to the attention net work. The attention network takes both inputs and learns to provide an attention weighted encoding. This weighted at - -tention encoding is then multiplied to the encoded image to produce a feature for each table cell. Notice that this is dif ferent than the typical object detection problem where im balances between the number of detections and the amount of objects may exist. In our case, we know up front that the produced detections always match with the table cells in number and correspondence. - -The output features for each table cell are then fed into the feed-forward network (FFN). The FFN consists of a Multi-Layer Perceptron (3 layers with ReLU activa tion function) that predicts the normalized coordinates for the bounding box of each table cell. Finally, the predicted bounding boxes are classified based on whether they are empty or not using a linear layer. - -Loss Functions. We formulate a multi-task loss Eq. 2 to train our network. The Cross-Entropy loss (denoted as l s ) is used to train the Structure Decoder which predicts the structure tokens. As for the Cell BBox Decoder it is trained with a combination of losses denoted as l box . l box consists of the generally used l 1 loss for object detection and the IoU loss ( l ) to be scale invariant as explained in [ 25 ]. In iou comparison to DETR, we do not use the Hungarian algo rithm [ 15 ] to match the predicted bounding boxes with the ground-truth boxes, as we have already achieved a one-to one match through two steps: 1) Our token input sequence is naturally ordered, therefore the hidden states of the table data cells are also in order when they are provided as in put to the Cell BBox Decoder , and 2) Our bounding boxes generation mechanism (see Sec. 3 ) ensures a one-to-one mapping between the cell content and its bounding box for all post-processed datasets. - -The loss used to train the TableFormer can be defined as following: - -l box = λ iou l iou + λ l 1 (1) l = λl + (1 − λ ) l box s - -where λ ∈ [0, 1], and λ , λ ∈ R are hyper-parameters. iou l 1 - -## 5. Experimental Results - -## 5.1. Implementation Details - -TableFormer uses ResNet-18 as the CNN Backbone Net work . The input images are resized to 448*448 pixels and the feature map has a dimension of 28*28. Additionally, we enforce the following input constraints: - -Image width and height ≤ 1024 pixels (2) Structural tags length ≤ 512 tokens. - -Although input constraints are used also by other methods, such as EDD, ours are less restrictive due to the improved - -runtime performance and lower memory footprint of Table Former. This allows to utilize input samples with longer sequences and images with larger dimensions. - -The Transformer Encoder consists of two “Transformer Encoder Layers”, with an input feature size of 512, feed forward network of 1024, and 4 attention heads. As for the Transformer Decoder it is composed of four “Transformer Decoder Layers” with similar input and output dimensions as the “Transformer Encoder Layers”. Even though our model uses fewer layers and heads than the default imple mentation parameters, our extensive experimentation has proved this setup to be more suitable for table images. We attribute this finding to the inherent design of table im ages, which contain mostly lines and text, unlike the more elaborate content present in other scopes (e.g. the COCO dataset). Moreover, we have added ResNet blocks to the inputs of the Structure Decoder and Cell BBox Decoder. This prevents a decoder having a stronger influence over the learned weights which would damage the other prediction task (structure vs bounding boxes), but learn task specific weights instead. Lastly our dropout layers are set to 0.5. - -For training, TableFormer is trained with 3 Adam opti mizers, each one for the CNN Backbone Network , Structure Decoder , and Cell BBox Decoder . Taking the PubTabNet as an example for our parameter set up, the initializing learn ing rate is 0.001 for 12 epochs with a batch size of 24, and λ set to 0.5. Afterwards, we reduce the learning rate to 0.0001, the batch size to 18 and train for 12 more epochs or convergence. - -TableFormer is implemented with PyTorch and Torchvi sion libraries [ 22 ]. To speed up the inference, the image undergoes a single forward pass through the CNN Back bone Network and transformer encoder. This eliminates the overhead of generating the same features for each decoding step. Similarly, we employ a ’caching’ technique to preform faster autoregressive decoding. This is achieved by storing the features of decoded tokens so we can reuse them for each time step. Therefore, we only compute the attention for each new tag. - -## 5.2. Generalization - -TableFormer is evaluated on three major publicly avail able datasets of different nature to prove the generalization and effectiveness of our model. The datasets used for eval uation are the PubTabNet, FinTabNet and TableBank which stem from the scientific, financial and general domains re spectively. - -We also share our baseline results on the challenging SynthTabNet dataset. Throughout our experiments, the same parameters stated in Sec. 5.1 are utilized. - -## 5.3. Datasets and Metrics - -The Tree-Edit-Distance-Based Similarity (TEDS) met ric was introduced in [ 37 ]. It represents the prediction, and ground-truth as a tree structure of HTML tags. This simi larity is calculated as: - -EditDist ( Ta , Tb Tb ) TEDS ( Ta Ta , Tb Tb ) = 1 − max ( | Ta | Ta | Tb | ) (3) Ta , Tb - -where Ta and Tb represent tables in tree structure HTML format. EditDist denotes the tree-edit distance, and Ta Tb | T | rep resents the number of nodes in T . - -## 5.4. Quantitative Analysis - -Structure. As shown in Tab. 2 , TableFormer outper forms all SOTA methods across different datasets by a large margin for predicting the table structure from an image. All the more, our model outperforms pre-trained methods. During the evaluation we do not apply any table filtering. We also provide our baseline results on the SynthTabNet dataset. It has been observed that large tables (e.g. tables that occupy half of the page or more) yield poor predictions. We attribute this issue to the image resizing during the pre processing step, that produces downsampled images with indistinguishable features. This problem can be addressed by treating such big tables with a separate model which ac cepts a large input image size. - -| | | | TEDS | | -|--------------------------------|-------------------------|----------------------------|--------|-------| -| | Model | | | | -| | | Dataset Simple Complex All | | | -| | EDD PTN 91.1 88.7 89.9 | | | | -| | GTE PTN - - 93.01 | | | | -| TableFormer PTN 98.5 95.0 | | | | 96.75 | -| | EDD FTN 88.4 92.08 90.6 | | | | -| | GTE FTN - - 87.14 | | | | -| GTE (FT) FTN - - 91.02 | | | | | -| TableFormer FTN 97.5 96.0 | | | | 96.8 | -| | EDD TB 86.0 - 86.0 | | | | -| TableFormer TB 89.6 - | | | | 89.6 | -| TableFormer STN 96.9 95.7 96.7 | | | | | - -Table 2: Structure results on PubTabNet (PTN), FinTabNet (FTN), TableBank (TB) and SynthTabNet (STN). - -FT: Model was trained on PubTabNet then finetuned. - -Cell Detection. Like any object detector, our Cell BBox Detector provides bounding boxes that can be improved with post-processing during inference. We make use of the grid-like structure of tables to refine the predictions. A de tailed explanation on the post-processing is available in the supplementary material. As shown in Tab. 3 , we evaluate - -Cell BBox Decoder accuracy for cells with a class la our bel of ‘content’ only using the PASCAL VOC mAP metric for pre-processing and post-processing. Note that we do not have post-processing results for SynthTabNet as images are only provided. To compare the performance of our pro posed approach, we’ve integrated TableFormer’s Cell BBox Decoder into EDD architecture. As mentioned previously, the Structure Decoder provides the Cell BBox Decoder with the features needed to predict the bounding box predictions. Therefore, the accuracy of the Structure Decoder directly influences the accuracy of the Cell BBox Decoder . If the Structure Decoder predicts an extra column, this will result in an extra column of predicted bounding boxes. - -| | Model Dataset mAP mAP (PP) | | -|--------------------------------|------------------------------|-----------| -| EDD+BBox PubTabNet 79.2 82.7 | | | -| TableFormer PubTabNet | | 82.1 86.8 | -| TableFormer SynthTabNet 87.7 - | | | - -Table 3: Cell Bounding Box detection results on PubTab Net, and FinTabNet. PP: Post-processing. - -Cell Content. In this section, we evaluate the entire pipeline of recovering a table with content. Here we put our approach to test by capitalizing on extracting content from the PDF cells rather than decoding from images. Tab. 4 shows the TEDs score of HTML code representing the structure of the table along with the content inserted in the data cell and compared with the ground-truth. Our method achieved a 5.3% increase over the state-of-the-art, and com mercial solutions. We believe our scores would be higher if the HTML ground-truth matched the extracted PDF cell content. Unfortunately, there are small discrepancies such as spacings around words or special characters with various unicode representations. - -| | | | TEDS | | -|----------------------------|------------------------|--------------------|--------|------| -| | Model | | | | -| | | Simple Complex All | | | -| | Tabula 78.0 57.8 67.9 | | | | -| Traprange 60.8 49.9 55.4 | | | | | -| | Camelot 80.0 66.0 73.0 | | | | -| Acrobat Pro 68.9 61.8 65.3 | | | | | -| | EDD 91.2 85.4 88.3 | | | | -| TableFormer 95.4 90.1 | | | | 93.6 | - -Table 4: Results of structure with content retrieved using cell detection on PubTabNet. In all cases the input is PDF documents with cropped tables. - -a. Red - PDF cells, Green - predicted bounding boxes, Blue - post-processed predictions matched to PDF cells Japanese language (previously unseen by TableFormer): Example table from FinTabNet: - -- a. Red - PDF cells, Green - predicted bounding boxes, Blue - post-processed predictions matched to PDF cells - -Japanese language (previously unseen by TableFormer): - - - -Text is aligned to match original for ease of viewing - -Figure 5: One of the benefits of TableFormer is that it is language agnostic, as an example, the left part of the illustration demonstrates TableFormer predictions on previously unseen language (Japanese). Additionally, we see that TableFormer is robust to variability in style and content, right side of the illustration shows the example of the TableFormer prediction from the FinTabNet dataset. - - - -Figure 6: An example of TableFormer predictions (bounding boxes and structure) from generated SynthTabNet table. - -## 6. Future Work & Conclusion - -## 5.5. Qualitative Analysis - -In this paper, we presented TableFormer an end-to-end transformer based approach to predict table structures and bounding boxes of cells from an image. This approach en ables us to recreate the table structure, and extract the cell content from PDF or OCR by using bounding boxes. Ad ditionally, it provides the versatility required in real-world scenarios when dealing with various types of PDF docu ments, and languages. Furthermore, our method outper forms all state-of-the-arts with a wide margin. Finally, we introduce “SynthTabNet” a challenging synthetically gen erated dataset that reinforces missing characteristics from other datasets. - -We showcase several visualizations for the different components of our network on various “complex” tables within datasets presented in this work in Fig. 5 and Fig. 6 As it is shown, our model is able to predict bounding boxes for all table cells, even for the empty ones. Additionally, our post-processing techniques can extract the cell content by matching the predicted bounding boxes to the PDF cells based on their overlap and spatial proximity. The left part of Fig. 5 demonstrates also the adaptability of our method to any language, as it can successfully extract Japanese text, although the training set contains only English content. We provide more visualizations including the intermediate steps in the supplementary material. Overall these illustra tions justify the versatility of our method across a diverse range of table appearances and content type. - -## References - -- [1] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to - -end object detection with transformers. In Andrea Vedaldi, Horst Bischof, Thomas Brox, and Jan-Michael Frahm, edi tors, Computer Vision – ECCV 2020 , pages 213–229, Cham, 2020. Springer International Publishing. 5 - -- [2] Zewen Chi, Heyan Huang, Heng-Da Xu, Houjin Yu, Wanx uan Yin, and Xian-Ling Mao. Complicated table structure recognition. arXiv preprint arXiv:1908.04729 , 2019. 3 -- [3] Bertrand Couasnon and Aurelie Lemaitre. Recognition of Ta bles and Forms , pages 647–677. Springer London, London, 2014. 2 -- [4] Herv e D ´ ´ ejean, Jean-Luc Meunier, Liangcai Gao, Yilun ´ ´ Huang, Yu Fang, Florian Kleber, and Eva-Maria Lang. IC DAR 2019 Competition on Table Detection and Recognition (cTDaR), Apr. 2019. http://sac.founderit.com/. 2 -- [5] Basilios Gatos, Dimitrios Danatsas, Ioannis Pratikakis, and Stavros J Perantonis. Automatic table detection in document images. In International Conference on Pattern Recognition and Image Analysis , pages 609–618. Springer, 2005. 2 -- [6] Max G obel, Tamir Hassan, Ermelinda Oro, and Giorgio Orsi. ¨ ¨ Icdar 2013 table competition. In 2013 12th International Conference on Document Analysis and Recognition , pages 1449–1453, 2013. 2 -- [7] EA Green and M Krishnamoorthy. Recognition of tables using table grammars. procs. In Symposium on Document Analysis and Recognition (SDAIR’95) , pages 261–277. 2 -- [8] Khurram Azeem Hashmi, Alain Pagani, Marcus Liwicki, Di dier Stricker, and Muhammad Zeshan Afzal. Castabdetec tors: Cascade network for table detection in document im ages with recursive feature pyramid and switchable atrous convolution. Journal of Imaging , 7(10), 2021. 1 -- [9] Kaiming He, Georgia Gkioxari, Piotr Dollar, and Ross Gir shick. Mask r-cnn. In Proceedings of the IEEE International Conference on Computer Vision (ICCV) , Oct 2017. 1 -- [10] Yelin He, X. Qi, Jiaquan Ye, Peng Gao, Yihao Chen, Bing cong Li, Xin Tang, and Rong Xiao. Pingan-vcgroup’s so lution for icdar 2021 competition on scientific table image recognition to latex. ArXiv , abs/2105.01846, 2021. 2 -- [11] Jianying Hu, Ramanujan S Kashi, Daniel P Lopresti, and Gordon Wilfong. Medium-independent table detection. In Document Recognition and Retrieval VII , volume 3967, pages 291–302. International Society for Optics and Photon ics, 1999. 2 -- [12] Matthew Hurst. A constraint-based approach to table struc ture derivation. In Proceedings of the Seventh International Conference on Document Analysis and Recognition - Volume 2 , ICDAR ’03, page 911, USA, 2003. IEEE Computer Soci ety. 2 -- [13] Thotreingam Kasar, Philippine Barlas, Sebastien Adam, Cl ement Chatelain, and Thierry Paquet. Learning to detect ´ ´ tables in scanned document images using line information. In 2013 12th International Conference on Document Analy sis and Recognition , pages 1185–1189. IEEE, 2013. 2 -- [14] Pratik Kayal, Mrinal Anand, Harsh Desai, and Mayank Singh. Icdar 2021 competition on scientific table image recognition to latex, 2021. 2 -- [15] Harold W Kuhn. The hungarian method for the assignment problem. Naval research logistics quarterly , 2(1-2):83–97, 1955. 6 -- [16] Girish Kulkarni, Visruth Premraj, Vicente Ordonez, Sag nik Dhar, Siming Li, Yejin Choi, Alexander C. Berg, and Tamara L. Berg. Babytalk: Understanding and generat ing simple image descriptions. IEEE Transactions on Pat tern Analysis and Machine Intelligence , 35(12):2891–2903, 2013. 4 -- [17] Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou, and Zhoujun Li. Tablebank: A benchmark dataset for table detection and recognition, 2019. 2 3 , -- [18] Yiren Li, Zheng Huang, Junchi Yan, Yi Zhou, Fan Ye, and Xianhui Liu. Gfte: Graph-based financial table extraction. In Alberto Del Bimbo, Rita Cucchiara, Stan Sclaroff, Gio vanni Maria Farinella, Tao Mei, Marco Bertini, Hugo Jair Escalante, and Roberto Vezzani, editors, Pattern Recogni tion. ICPR International Workshops and Challenges , pages 644–658, Cham, 2021. Springer International Publishing. 2 , 3 -- [19] Nikolaos Livathinos, Cesar Berrospi, Maksym Lysak, Vik tor Kuropiatnyk, Ahmed Nassar, Andre Carvalho, Michele Dolfi, Christoph Auer, Kasper Dinkla, and Peter Staar. Ro bust pdf document conversion using recurrent neural net works. Proceedings of the AAAI Conference on Artificial Intelligence , 35(17):15137–15145, May 2021. 1 -- [20] Rujiao Long, Wen Wang, Nan Xue, Feiyu Gao, Zhibo Yang, Yongpan Wang, and Gui-Song Xia. Parsing table structures in the wild. In Proceedings of the IEEE/CVF International Conference on Computer Vision , pages 944–952, 2021. 2 -- [21] Shubham Singh Paliwal, D Vishwanath, Rohit Rahul, Monika Sharma, and Lovekesh Vig. Tablenet: Deep learn ing model for end-to-end table detection and tabular data ex traction from scanned document images. In 2019 Interna tional Conference on Document Analysis and Recognition (ICDAR) , pages 128–133. IEEE, 2019. 1 -- [22] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, Alban Desmaison, Andreas Kopf, Edward Yang, Zachary DeVito, Martin Rai son, Alykhan Tejani, Sasank Chilamkurthy, Benoit Steiner, Lu Fang, Junjie Bai, and Soumith Chintala. Pytorch: An im perative style, high-performance deep learning library. In H. Wallach, H. Larochelle, A. Beygelzimer, F. d'Alch e-Buc, E. ´ ´ Fox, and R. Garnett, editors, Advances in Neural Informa tion Processing Systems 32 , pages 8024–8035. Curran Asso ciates, Inc., 2019. 6 -- [23] Devashish Prasad, Ayan Gadpal, Kshitij Kapadni, Manish Visave, and Kavita Sultanpure. Cascadetabnet: An approach for end to end table detection and structure recognition from image-based documents. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops , pages 572–573, 2020. 1 -- [24] Shah Rukh Qasim, Hassan Mahmood, and Faisal Shafait. Rethinking table recognition using graph neural networks. 2019 International Conference on Document Analysis and In Recognition (ICDAR) , pages 142–147. IEEE, 2019. 3 -- [25] Hamid Rezatofighi, Nathan Tsoi, JunYoung Gwak, Amir Sadeghian, Ian Reid, and Silvio Savarese. Generalized in tersection over union: A metric and a loss for bounding box regression. In Proceedings of the IEEE/CVF Conference on - -Computer Vision and Pattern Recognition , pages 658–666, 2019. 6 - -- [26] Sebastian Schreiber, Stefan Agne, Ivo Wolf, Andreas Den gel, and Sheraz Ahmed. Deepdesrt: Deep learning for detec tion and structure recognition of tables in document images. In 2017 14th IAPR International Conference on Document Analysis and Recognition (ICDAR) , volume 01, pages 1162– 1167, 2017. 1 -- [27] Sebastian Schreiber, Stefan Agne, Ivo Wolf, Andreas Den gel, and Sheraz Ahmed. Deepdesrt: Deep learning for de tection and structure recognition of tables in document im ages. In 2017 14th IAPR international conference on doc ument analysis and recognition (ICDAR) , volume 1, pages 1162–1167. IEEE, 2017. 3 -- [28] Faisal Shafait and Ray Smith. Table detection in heteroge neous documents. In Proceedings of the 9th IAPR Interna tional Workshop on Document Analysis Systems , pages 65– 72, 2010. 2 -- [29] Shoaib Ahmed Siddiqui, Imran Ali Fateh, Syed Tah seen Raza Rizvi, Andreas Dengel, and Sheraz Ahmed. Deeptabstr: Deep learning based table structure recognition. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 1403–1409. IEEE, 2019. 3 -- [30] Peter W J Staar, Michele Dolfi, Christoph Auer, and Costas Bekas. Corpus conversion service: A machine learning plat form to ingest documents at scale. In Proceedings of the 24th ACM SIGKDD , KDD ’18, pages 774–782, New York, NY, USA, 2018. ACM. 1 -- [31] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszko reit, Llion Jones, Aidan N Gomez, Ł ukasz Kaiser, and Il lia Polosukhin. Attention is all you need. In I. Guyon, U. V. Luxburg, S. Bengio, H. Wallach, R. Fergus, S. Vish wanathan, and R. Garnett, editors, Advances in Neural In formation Processing Systems 30 , pages 5998–6008. Curran Associates, Inc., 2017. 5 -- [32] Oriol Vinyals, Alexander Toshev, Samy Bengio, and Du mitru Erhan. Show and tell: A neural image caption gen erator. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR) , June 2015. 2 -- [33] Wenyuan Xue, Qingyong Li, and Dacheng Tao. Res2tim: reconstruct syntactic structures from table images. In 2019 International Conference on Document Analysis and Recog nition (ICDAR) , pages 749–755. IEEE, 2019. 3 -- [34] Wenyuan Xue, Baosheng Yu, Wen Wang, Dacheng Tao, and Qingyong Li. Tgrnet: A table graph reconstruction network for table structure recognition. arXiv preprint arXiv:2106.10598 , 2021. 3 -- [35] Quanzeng You, Hailin Jin, Zhaowen Wang, Chen Fang, and Jiebo Luo. Image captioning with semantic attention. In Proceedings of the IEEE conference on computer vision and pattern recognition , pages 4651–4659, 2016. 4 -- [36] Xinyi Zheng, Doug Burdick, Lucian Popa, Peter Zhong, and Nancy Xin Ru Wang. Global table extractor (gte): A frame work for joint table identification and cell structure recogni tion using visual context. Winter Conference for Applications in Computer Vision (WACV) , 2021. 2 , 3 -- [37] Xu Zhong, Elaheh ShafieiBavani, and Antonio Ji meno Yepes. Image-based table recognition: Data, model, - -and evaluation. In Andrea Vedaldi, Horst Bischof, Thomas Brox, and Jan-Michael Frahm, editors, Computer Vision – ECCV 2020 , pages 564–580, Cham, 2020. Springer Interna tional Publishing. 2 3 7 , , - -- [38] Xu Zhong, Jianbin Tang, and Antonio Jimeno Yepes. Pub laynet: Largest dataset ever for document layout analysis. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 1015–1022, 2019. 1 - -## TableFormer: Table Structure Understanding with Transformers Supplementary Material - -## TableFormer: Table Structure Understanding with Transformers - -Supplementary Material - -## 1. Details on the datasets - -## 1.1. Data preparation - -As a first step of our data preparation process, we have calculated statistics over the datasets across the following dimensions: (1) table size measured in the number of rows and columns, (2) complexity of the table, (3) strictness of the provided HTML structure and (4) completeness (i.e. no omitted bounding boxes). A table is considered to be simple if it does not contain row spans or column spans. Addition ally, a table has a strict HTML structure if every row has the same number of columns after taking into account any row or column spans. Therefore a strict HTML structure looks always rectangular. However, HTML is a lenient encoding format, i.e. tables with rows of different sizes might still be regarded as correct due to implicit display rules. These implicit rules leave room for ambiguity, which we want to avoid. As such, we prefer to have ”strict” tables, i.e. tables where every row has exactly the same length. - -We have developed a technique that tries to derive a missing bounding box out of its neighbors. As a first step, we use the annotation data to generate the most fine-grained grid that covers the table structure. In case of strict HTML tables, all grid squares are associated with some table cell and in the presence of table spans a cell extends across mul tiple grid squares. When enough bounding boxes are known for a rectangular table, it is possible to compute the geo metrical border lines between the grid rows and columns. Eventually this information is used to generate the missing bounding boxes. Additionally, the existence of unused grid squares indicates that the table rows have unequal number of columns and the overall structure is non-strict. The gen eration of missing bounding boxes for non-strict HTML ta bles is ambiguous and therefore quite challenging. Thus, we have decided to simply discard those tables. In case of PubTabNet we have computed missing bounding boxes for 48% of the simple and 69% of the complex tables. Regard ing FinTabNet, 68% of the simple and 98% of the complex tables require the generation of bounding boxes. - -Figure 7 illustrates the distribution of the tables across different dimensions per dataset. - -## 1.2. Synthetic datasets - -Aiming to train and evaluate our models in a broader spectrum of table data we have synthesized four types of datasets. Each one contains tables with different appear - -ances in regard to their size, structure, style and content. Every synthetic dataset contains 150k examples, summing up to 600k synthetic examples. All datasets are divided into Train, Test and Val splits (80%, 10%, 10%). - -The process of generating a synthetic dataset can be de composed into the following steps: - -- 1. Prepare styling and content templates: The styling templates have been manually designed and organized into groups of scope specific appearances (e.g. financial data, marketing data, etc.) Additionally, we have prepared cu rated collections of content templates by extracting the most frequently used terms out of non-synthetic datasets (e.g. PubTabNet, FinTabNet, etc.). -- 2. Generate table structures: The structure of each syn thetic dataset assumes a horizontal table header which po tentially spans over multiple rows and a table body that may contain a combination of row spans and column spans. However, spans are not allowed to cross the header - body boundary. The table structure is described by the parame ters: Total number of table rows and columns, number of header rows, type of spans (header only spans, row only spans, column only spans, both row and column spans), maximum span size and the ratio of the table area covered by spans. -- 3. Generate content: Based on the dataset theme , a set of suitable content templates is chosen first. Then, this content can be combined with purely random text to produce the synthetic content. -- 4. Apply styling templates: Depending on the domain of the synthetic dataset, a set of styling templates is first manually selected. Then, a style is randomly selected to format the appearance of the synthesized table. -- 5. Render the complete tables: The synthetic table is finally rendered by a web browser engine to generate the bounding boxes for each table cell. A batching technique is utilized to optimize the runtime overhead of the rendering process. - -## 2. Prediction post-processing for PDF docu ments - -Although TableFormer can predict the table structure and the bounding boxes for tables recognized inside PDF docu ments, this is not enough when a full reconstruction of the original table is required. This happens mainly due the fol lowing reasons: - - - -Figure 7: Distribution of the tables across different dimensions per dataset. Simple vs complex tables per dataset and split, strict vs non strict html structures per dataset and table complexity, missing bboxes per dataset and table complexity. - -- • TableFormer output does not include the table cell con tent. -- • There are occasional inaccuracies in the predictions of the bounding boxes. - -However, it is possible to mitigate those limitations by combining the TableFormer predictions with the informa tion already present inside a programmatic PDF document. More specifically, PDF documents can be seen as a se quence of PDF cells where each cell is described by its con tent and bounding box. If we are able to associate the PDF cells with the predicted table cells, we can directly link the PDF cell content to the table cell structure and use the PDF bounding boxes to correct misalignments in the predicted table cell bounding boxes. - -Here is a step-by-step description of the prediction post processing: - -- 1. Get the minimal grid dimensions - number of rows and columns for the predicted table structure. This represents the most granular grid for the underlying table structure. -- 2. Generate pair-wise matches between the bounding boxes of the PDF cells and the predicted cells. The Intersec tion Over Union (IOU) metric is used to evaluate the quality of the matches. -- 3. Use a carefully selected IOU threshold to designate the matches as “good” ones and “bad” ones. -- 3.a. If all IOU scores in a column are below the thresh old, discard all predictions (structure and bounding boxes) for that column. -- 4. Find the best-fitting content alignment for the pre dicted cells with good IOU per each column. The alignment of the column can be identified by the following formula: - -alignment = arg min { D c } c (4) D c = max { x c } − min { x c } - -where c is one of { left, centroid, right } and x is the x coordinate for the corresponding point. c - -- 5. Use the alignment computed in step 4, to compute the median x -coordinate for all table columns and the me - -dian cell size for all table cells. The usage of median dur ing the computations, helps to eliminate outliers caused by occasional column spans which are usually wider than the normal. - -- 6. Snap all cells with bad IOU to their corresponding median x -coordinates and cell sizes. -- 7. Generate a new set of pair-wise matches between the corrected bounding boxes and PDF cells. This time use a modified version of the IOU metric, where the area of the intersection between the predicted and PDF cells is divided by the PDF cell area. In case there are multiple matches for the same PDF cell, the prediction with the higher score is preferred. This covers the cases where the PDF cells are smaller than the area of predicted or corrected prediction cells. -- 8. In some rare occasions, we have noticed that Table Former can confuse a single column as two. When the post processing steps are applied, this results with two predicted columns pointing to the same PDF column. In such case we must de-duplicate the columns according to highest to tal column intersection score. -- 9. Pick up the remaining orphan cells. There could be cases, when after applying all the previous post-processing steps, some PDF cells could still remain without any match to predicted cells. However, it is still possible to deduce the correct matching for an orphan PDF cell by mapping its bounding box on the geometry of the grid. This mapping decides if the content of the orphan cell will be appended to an already matched table cell, or a new table cell should be created to match with the orphan. -- 9a. Compute the top and bottom boundary of the hori zontal band for each grid row (min/max y coordinates per row). -- 9b. Intersect the orphan’s bounding box with the row bands, and map the cell to the closest grid row. -- 9c. Compute the left and right boundary of the vertical band for each grid column (min/max x coordinates per col umn). -- 9d. Intersect the orphan’s bounding box with the column bands, and map the cell to the closest grid column. -- 9e. If the table cell under the identified row and column is not empty, extend its content with the content of the or - -phan cell. - -9f. Otherwise create a new structural cell and match it wit the orphan cell. - -Aditional images with examples of TableFormer predic tions and post-processing can be found below. - - - -Figure 8: Example of a table with multi-line header. - - - -Figure 9: Example of a table with big empty distance be tween cells. - - - -Figure 10: Example of a complex table with empty cells. - - - - - -Figure 11: Simple table with different style and empty cells. - - - -Figure 12: Simple table predictions and post processing. - - - -Figure 13: Table predictions example on colorful table. - -Figure 14: Example with multi-line text. - - - -Figure 15: Example with triangular table. - -Figure 16: Example of how post-processing helps to restore mis-aligned bounding boxes prediction artifact. - - - -Figure 17: Example of long table. End-to-end example from initial PDF cells to prediction of bounding boxes, post process ing and prediction of structure. diff --git a/tests/pdf_snapshots/pdf/sources/2206.01062.pdf.md b/tests/pdf_snapshots/pdf/sources/2206.01062.pdf.md deleted file mode 100644 index 08e62400..00000000 --- a/tests/pdf_snapshots/pdf/sources/2206.01062.pdf.md +++ /dev/null @@ -1,330 +0,0 @@ -Birgit Pfitzmann IBM Research Rueschlikon, Switzerland bpf@zurich.ibm.com - -Ahmed S. Nassar IBM Research Rueschlikon, Switzerland ahn@zurich.ibm.com - -## ABSTRACT - -Accurate document layout analysis is a key requirement for high quality PDF document conversion. With the recent availability of public, large ground-truth datasets such as PubLayNet and DocBank, deep-learning models have proven to be very effective at layout detection and segmentation. While these datasets are of adequate size to train such models, they severely lack in layout variability since they are sourced from scientific article repositories such as PubMed and arXiv only. Consequently, the accuracy of the layout segmentation drops significantly when these models are applied on more challenging and diverse layouts. In this paper, we present DocLayNet, t, a new, publicly available, document-layout annotation dataset in COCO format. It contains 80863 manually annotated pages from diverse data sources to represent a wide variability in layouts. For each PDF page, the layout annotations provide labelled bounding-boxes with a choice of 11 distinct classes. DocLayNet also provides a subset of double- and triple-annotated pages to determine the inter-annotator agreement. In multiple experiments, we provide baseline accuracy scores (in mAP) for a set of popular object detection models. We also demonstrate that these models fall approximately 10% behind the inter-annotator agreement. Fur thermore, we provide evidence that DocLayNet is of sufficient size. Lastly, we compare models trained on PubLayNet, DocBank and DocLayNet, showing that layout predictions of the DocLayNet trained models are more robust and thus the preferred choice for general-purpose document-layout analysis. - -## CCS CONCEPTS - -• Information systems → Document structure ; • Applied com puting → Document analysis ; • Computing methodologies → Machine learning ; Computer vision ; Object detection ; - -Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for third-party components of this work must be honored. For all other uses, contact the owner/author(s). - -KDD ’22, August 14–18, 2022, Washington, DC, USA - -© 2022 Copyright held by the owner/author(s). - -ACM ISBN 978-1-4503-9385-0/22/08. - -https://doi.org/10.1145/3534678.3539043 - -# DocLayNet: A Large Human-Annotated Dataset for Document-Layout Analysis - -Michele Dolfi IBM Research Rueschlikon, Switzerland dol@zurich.ibm.com - -Christoph Auer IBM Research Rueschlikon, Switzerland cau@zurich.ibm.com - -Peter Staar IBM Research Rueschlikon, Switzerland taa@zurich.ibm.com - - - - - - - - - - - -Figure 1: Four examples of complex page layouts across dif ferent document categories - -## KEYWORDS - -PDF document conversion, layout segmentation, object-detection, data set, Machine Learning - -## ACM Reference Format: - -Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar. 2022. DocLayNet: A Large Human-Annotated Dataset for Document Layout Analysis. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD ’22), August 14–18, 2022, Wash ington, DC, USA. ACM, New York, NY, USA, 9 pages. https://doi.org/10.1145/ 3534678.3539043 - -KDD ’22, August 14–18, 2022, Washington, DC, USA Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar - -## 1 INTRODUCTION - -Despite the substantial improvements achieved with machine-learning (ML) approaches and deep neural networks in recent years, docu ment conversion remains a challenging problem, as demonstrated by the numerous public competitions held on this topic [ 1 – 4 ]. The challenge originates from the huge variability in PDF documents regarding layout, language and formats (scanned, programmatic or a combination of both). Engineering a single ML model that can be applied on all types of documents and provides high-quality layout segmentation remains to this day extremely challenging [ ]. 5 To highlight the variability in document layouts, we show a few example documents from the DocLayNet dataset in Figure 1. - -A key problem in the process of document conversion is to under stand the structure of a single document page, i.e. which segments of text should be grouped together in a unit. To train models for this task, there are currently two large datasets available to the com munity, PubLayNet [ 6 ] and DocBank [ 7 ]. They were introduced in 2019 and 2020 respectively and significantly accelerated the im plementation of layout detection and segmentation models due to their sizes of 300K and 500K ground-truth pages. These sizes were achieved by leveraging an automation approach. The benefit of au tomated ground-truth generation is obvious: one can generate large ground-truth datasets at virtually no cost. However, the automation introduces a constraint on the variability in the dataset, because corresponding structured source data must be available. PubLayNet and DocBank were both generated from scientific document repos itories (PubMed and arXiv), which provide XML or LA LAT ATE TEX EX sources. Those scientific documents present a limited variability in their layouts, because they are typeset in uniform templates provided by the publishers. Obviously, documents such as technical manuals, annual company reports, legal text, government tenders, etc. have very different and partially unique layouts. As a consequence, the layout predictions obtained from models trained on PubLayNet or DocBank is very reasonable when applied on scientific documents. However, for more artistic or free-style layouts, we see sub-par prediction quality from these models, which we demonstrate in Section 5. - -In this paper, we present the DocLayNet dataset. It provides page by-page layout annotation ground-truth using bounding-boxes for 11 distinct class labels on 80863 unique document pages, of which a fraction carry double- or triple-annotations. DocLayNet is similar in spirit to PubLayNet and DocBank and will likewise be made available to the public 1 in order to stimulate the document-layout analysis community. It distinguishes itself in the following aspects: - -- (1) Human Annotation : In contrast to PubLayNet and DocBank, we relied on human annotation instead of automation ap proaches to generate the data set. -- (2) Large Layout Variability : We include diverse and complex layouts from a large variety of public sources. -- (3) Detailed Label Set : We define 11 class labels to distinguish layout features in high detail. PubLayNet provides 5 labels; DocBank provides 13, although not a superset of ours. -- (4) Redundant Annotations : A fraction of the pages in the Do cLayNet data set carry more than one human annotation. - -1 https://developer.ibm.com/exchanges/data/all/doclaynet - -- This enables experimentation with annotation uncertainty and quality control analysis. -- (5) Pre-defined Train-, Test- & Validation-set : Like DocBank, we provide fixed train-, test- & validation-sets to ensure propor tional representation of the class-labels. Further, we prevent leakage of unique layouts across sets, which has a large effect on model accuracy scores. - -All aspects outlined above are detailed in Section 3. In Section 4, we will elaborate on how we designed and executed this large-scale human annotation campaign. We will also share key insights and lessons learned that might prove helpful for other parties planning to set up annotation campaigns. - -In Section 5, we will present baseline accuracy numbers for a variety of object detection methods (Faster R-CNN, Mask R-CNN and YOLOv5) trained on DocLayNet. We further show how the model performance is impacted by varying the DocLayNet dataset size, reducing the label set and modifying the train/test-split. Last but not least, we compare the performance of models trained on PubLayNet, DocBank and DocLayNet and demonstrate that a model trained on DocLayNet provides overall more robust layout recovery. - -## 2 RELATED WORK - -While early approaches in document-layout analysis used rule based algorithms and heuristics [ 8 ], the problem is lately addressed with deep learning methods. The most common approach is to lever age object detection models [ 9 – 15 ]. In the last decade, the accuracy and speed of these models has increased dramatically. Furthermore, most state-of-the-art object detection methods can be trained and applied with very little work, thanks to a standardisation effort of the ground-truth data format [ 16 ] and common deep-learning frameworks [ ]. Reference data sets such as PubLayNet [ ] and 17 6 DocBank provide their data in the commonly accepted COCO for mat [16]. - -Lately, new types of ML models for document-layout analysis have emerged in the community [ 18 – 21 ]. These models do not approach the problem of layout analysis purely based on an image representation of the page, as computer vision methods do. Instead, they combine the text tokens and image representation of a page in order to obtain a segmentation. While the reported accuracies appear to be promising, a broadly accepted data format which links geometric and textual features has yet to establish. - -## 3 THE DOCLAYNET DATASET - -DocLayNet contains 80863 PDF pages. Among these, 7059 carry two instances of human annotations, and 1591 carry three. This amounts to 91104 total annotation instances. The annotations provide lay out information in the shape of labeled, rectangular bounding boxes. We define 11 distinct labels for layout features, namely Cap tion Footnote Formula List-item Page-footer, Page-header, Picture Section-header, , , Table Text, , t, and Title , . Our reasoning for picking this r, r, , r, , particular label set is detailed in Section 4. - -In addition to open intellectual property constraints for the source documents, we required that the documents in DocLayNet adhere to a few conditions. Firstly, we kept scanned documents - - - -Figure 2: Distribution of DocLayNet pages across document categories. - -to a minimum, since they introduce difficulties in annotation (see Section 4). As a second condition, we focussed on medium to large documents ( > 10 pages) with technical content, dense in complex tables, figures, plots and captions. Such documents carry a lot of information value, but are often hard to analyse with high accuracy due to their challenging layouts. Counterexamples of documents not included in the dataset are receipts, invoices, hand-written documents or photographs showing “text in the wild". - -The pages in DocLayNet can be grouped into six distinct cate gories, namely Financial Reports Manuals Scientific Articles Laws & Regulations Patents and Government Tenders , , . Each document cate , gory was sourced from various repositories. For example, Financial , Reports contain both free-style format annual reports 2 which ex pose company-specific, artistic layouts as well as the more formal SEC filings. The two largest categories ( Financial Reports and Man uals ) contain a large amount of free-style layouts in order to obtain maximum variability. In the other four categories, we boosted the variability by mixing documents from independent providers, such as different government websites or publishers. In Figure 2, we show the document categories contained in DocLayNet with their respective sizes. - -We did not control the document selection with regard to lan guage. The vast majority of documents contained in DocLayNet (close to 95%) are published in English language. However, Do cLayNet also contains a number of documents in other languages such as German (2.5%), French (1.0%) and Japanese (1.0%). While the document language has negligible impact on the performance of computer vision methods such as object detection and segmenta tion models, it might prove challenging for layout analysis methods which exploit textual features. - -To ensure that future benchmarks in the document-layout analy sis community can be easily compared, we have split up DocLayNet into pre-defined train-, test- and validation-sets. In this way, we can avoid spurious variations in the evaluation scores due to random splitting in train-, test- and validation-sets. We also ensured that less frequent labels are represented in train and test sets in equal proportions. - -2 e.g. AAPL from https://www.annualreports.com/ - -Table 1 shows the overall frequency and distribution of the labels among the different sets. Importantly, we ensure that subsets are only split on full-document boundaries. This avoids that pages of the same document are spread over train, test and validation set, which can give an undesired evaluation advantage to models and lead to overestimation of their prediction accuracy. We will show the impact of this decision in Section 5. - -In order to accommodate the different types of models currently in use by the community, we provide DocLayNet in an augmented COCO format [ 16 ]. This entails the standard COCO ground-truth file (in JSON format) with the associated page images (in PNG format, 1025 × 1025 pixels). Furthermore, custom fields have been added to each COCO record to specify document category, original document filename and page number. In addition, we also provide the original PDF pages, as well as sidecar files containing parsed PDF text and text-cell coordinates (in JSON). All additional files are linked to the primary page images by their matching filenames. - -Despite being cost-intense and far less scalable than automation, human annotation has several benefits over automated ground truth generation. The first and most obvious reason to leverage human annotations is the freedom to annotate any type of doc ument without requiring a programmatic source. For most PDF documents, the original source document is not available. The lat ter is not a hard constraint with human annotation, but it is for automated methods. A second reason to use human annotations is that the latter usually provide a more natural interpretation of the page layout. The human-interpreted layout can significantly devi ate from the programmatic layout used in typesetting. For example, “invisible” tables might be used solely for aligning text paragraphs on columns. Such typesetting tricks might be interpreted by au tomated methods incorrectly as an actual table, while the human annotation will interpret it correctly as Text or other styles. The same applies to multi-line text elements, when authors decided to space them as “invisible” list elements without bullet symbols. A third reason to gather ground-truth through human annotation is to estimate a “natural” upper bound on the segmentation accuracy. As we will show in Section 4, certain documents featuring complex layouts can have different but equally acceptable layout interpre tations. This natural upper bound for segmentation accuracy can be found by annotating the same pages multiple times by different people and evaluating the inter-annotator agreement. Such a base line consistency evaluation is very useful to define expectations for a good target accuracy in trained deep neural network models and avoid overfitting (see Table 1). On the flip side, achieving high annotation consistency proved to be a key challenge in human annotation, as we outline in Section 4. - -## 4 ANNOTATION CAMPAIGN - -The annotation campaign was carried out in four phases. In phase one, we identified and prepared the data sources for annotation. In phase two, we determined the class labels and how annotations should be done on the documents in order to obtain maximum con sistency. The latter was guided by a detailed requirement analysis and exhaustive experiments. In phase three, we trained the annota tion staff and performed exams for quality assurance. In phase four, - -Table 1: DocLayNet dataset overview. Along with the frequency of each class label, we present the relative occurrence (as % of row “Total”) in the train, test and validation sets. The inter-annotator agreement is computed as the mAP@0.5-0.95 metric between pairwise annotations from the triple-annotated pages, from which we obtain accuracy ranges. - -| | | | | | % of Total | | triple inter-annotator mAP @ 0.5-0.95 (%) | -|----------------|---------|-------|--------------------|-------------------|--------------|--------------------------------------------|---------------------------------------------| -| class label | Count | | Train Test Val | | | All Fin Man Sci Law Pat Ten | | -| Caption | | 22524 | | 2.04 1.77 2.32 | | 84-89 40-61 86-92 94-99 95-99 69-78 n/a | | -| Footnote | | 6318 | | 0.60 0.31 0.58 | | 83-91 n/a 100 62-88 85-94 n/a 82-97 | | -| Formula | | 25027 | | 2.25 1.90 2.96 | | 83-85 n/a n/a 84-87 86-96 n/a n/a | | -| List-item | 185660 | | | 17.19 13.34 15.82 | | 87-88 74-83 90-92 97-97 81-85 75-88 93-95 | | -| Page-footer | | 70878 | | 6.51 5.58 6.00 | | 93-94 88-90 95-96 100 92-97 100 96-98 | | -| Page-header | | 58022 | | 5.10 6.70 5.06 | | 85-89 66-76 90-94 98-100 91-92 97-99 81-86 | | -| Picture | 45976 | | | 4.21 2.78 5.31 | | 69-71 56-59 82-86 69-82 80-95 66-71 59-76 | | -| Section-header | 142884 | | | 12.60 15.77 12.85 | | 83-84 76-81 90-92 94-95 87-94 69-73 78-86 | | -| Table | | 34733 | | 3.20 2.27 3.60 | | 77-81 75-80 83-86 98-99 58-80 79-84 70-85 | | -| Text | 510377 | | | 45.82 49.28 45.00 | | 84-86 81-86 88-93 89-93 87-92 71-79 87-95 | | -| Title | | 5071 | | 0.47 0.30 0.50 | | 60-72 24-63 50-63 94-100 82-96 68-79 24-56 | | -| Total | 1107470 | | 941123 99816 66531 | | | 82-83 71-74 79-81 89-94 86-91 71-76 68-85 | | - - - -include publication repositories such as arXiv 3 , government offices, company websites as well as data directory services for financial reports and patents. Scanned documents were excluded wherever possible because they can be rotated or skewed. This would not allow us to perform annotation with rectangular bounding-boxes and therefore complicate the annotation process. - -Preparation work included uploading and parsing the sourced PDF documents in the Corpus Conversion Service (CCS) [ 22 ], a cloud-native platform which provides a visual annotation interface and allows for dataset inspection and analysis. The annotation in terface of CCS is shown in Figure 3. The desired balance of pages between the different document categories was achieved by se lective subsampling of pages with certain desired properties. For example, we made sure to include the title page of each document and bias the remaining page selection to those with figures or tables. The latter was achieved by leveraging pre-trained object detection models from PubLayNet, which helped us estimate how many figures and tables a given page contains. - -Phase 2: Label selection and guideline. We reviewed the col lected documents and identified the most common structural fea tures they exhibit. This was achieved by identifying recurrent layout elements and lead us to the definition of 11 distinct class labels. These 11 class labels are Caption Footnote Formula List-item Page , , , , footer, r, Page-header, r, Picture , Section-header, r, Table , Text, t, and Title . Critical factors that were considered for the choice of these class labels were (1) the overall occurrence of the label, (2) the specificity of the label, (3) recognisability on a single page (i.e. no need for context from previous or next page) and (4) overall coverage of the page. Specificity ensures that the choice of label is not ambiguous, while coverage ensures that all meaningful items on a page can be annotated. We refrained from class labels that are very specific to a document category, such as Abstract in the Scientific Articles category. We also avoided class labels that are tightly linked to the semantics of the text. Labels such as Author and Affiliation , as seen in DocBank, are often only distinguishable by discriminating on - -Figure 3: Corpus Conversion Service annotation user inter face. The PDF page is shown in the background, with over laid text-cells (in darker shades). The annotation boxes can be drawn by dragging a rectangle over each segment with the respective label from the palette on the right. - -we distributed the annotation workload and performed continuous quality controls. Phase one and two required a small team of experts only. For phases three and four, a group of 40 dedicated annotators were assembled and supervised. - -Phase 1: Data selection and preparation. Our inclusion cri teria for documents were described in Section 3. A large effort went into ensuring that all documents are free to use. The data sources - -3 https://arxiv.org/ - -the textual content of an element, which goes beyond visual layout recognition, in particular outside the Scientific Articles category. - -At first sight, the task of visual document-layout interpretation appears intuitive enough to obtain plausible annotations in most cases. However, during early trial-runs in the core team, we ob served many cases in which annotators use different annotation styles, especially for documents with challenging layouts. For ex ample, if a figure is presented with subfigures, one annotator might draw a single figure bounding-box, while another might annotate each subfigure separately. The same applies for lists, where one might annotate all list items in one block or each list item sep arately. In essence, we observed that challenging layouts would be annotated in different but plausible ways. To illustrate this, we show in Figure 4 multiple examples of plausible but inconsistent annotations on the same pages. - -Obviously, this inconsistency in annotations is not desirable for datasets which are intended to be used for model training. To min imise these inconsistencies, we created a detailed annotation guide line. While perfect consistency across 40 annotation staff members is clearly not possible to achieve, we saw a huge improvement in annotation consistency after the introduction of our annotation guideline. A few selected, non-trivial highlights of the guideline are: - -- (1) Every list-item is an individual object instance with class label List-item . This definition is different from PubLayNet and DocBank, where all list-items are grouped together into object. one List -- (2) A List-item is a paragraph with hanging indentation. Single line elements can qualify as List-item if the neighbour ele ments expose hanging indentation. Bullet or enumeration symbols are not a requirement. -- (3) For every Caption , there must be exactly one corresponding Picture Table or . -- (4) Connected sub-pictures are grouped together in one Picture object. -- (5) Formula numbers are included in a Formula object. -- (6) Emphasised text (e.g. in italic or bold) at the beginning of a paragraph is not considered a Section-header, r, unless it appears exclusively on its own line. - -The complete annotation guideline is over 100 pages long and a detailed description is obviously out of scope for this paper. Never theless, it will be made publicly available alongside with DocLayNet for future reference. - -Phase 3: Training. After a first trial with a small group of peo ple, we realised that providing the annotation guideline and a set of random practice pages did not yield the desired quality level for lay out annotation. Therefore we prepared a subset of pages with two different complexity levels, each with a practice and an exam part. 974 pages were reference-annotated by one proficient core team member. Annotation staff were then given the task to annotate the same subsets (blinded from the reference). By comparing the an notations of each staff member with the reference annotations, we could quantify how closely their annotations matched the reference. Only after passing two exam levels with high annotation quality, staff were admitted into the production phase. Practice iterations - - - -Figure 4: Examples of plausible annotation alternatives for the same page. Criteria in our annotation guideline can re solve cases A to C, while the case D remains ambiguous. - -were carried out over a timeframe of 12 weeks, after which 8 of the 40 initially allocated annotators did not pass the bar. - -Phase 4: Production annotation. The previously selected 80K pages were annotated with the defined 11 class labels by 32 annota tors. This production phase took around three months to complete. All annotations were created online through CCS, which visualises the programmatic PDF text-cells as an overlay on the page. The page annotation are obtained by drawing rectangular bounding-boxes, as shown in Figure 3. With regard to the annotation practices, we implemented a few constraints and capabilities on the tooling level. First, we only allow non-overlapping, vertically oriented, rectangu lar boxes. For the large majority of documents, this constraint was sufficient and it speeds up the annotation considerably in compar ison with arbitrary segmentation shapes. Second, annotator staff were not able to see each other’s annotations. This was enforced by design to avoid any bias in the annotation, which could skew the numbers of the inter-annotator agreement (see Table 1). We wanted - -Table 2: Prediction performance (mAP@0.5-0.95) of object detection networks on DocLayNet test set. The MRCNN (Mask R-CNN) and FRCNN (Faster R-CNN) models with ResNet-50 or ResNet-101 backbone were trained based on the network architectures from the detectron2 model zoo (Mask R-CNN R50, R101-FPN 3x, Faster R-CNN R101-FPN 3x), with default configurations. The YOLO implementation utilized was YOLOv5x6 [13]. All models were initialised us ing pre-trained weights from the COCO 2017 dataset. - -| | human | MRCNN FRCNN YOLO | -|----------------|---------|---------------------| -| | | R50 R101 R101 v5x6 | -| Caption | 84-89 | 68.4 71.5 70.1 77.7 | -| Footnote | 83-91 | 70.9 71.8 73.7 77.2 | -| Formula | 83-85 | 60.1 63.4 63.5 66.2 | -| List-item | 87-88 | 81.2 80.8 81.0 86.2 | -| Page-footer | 93-94 | 61.6 59.3 58.9 61.1 | -| Page-header | 85-89 | 71.9 70.0 72.0 67.9 | -| Picture | 69-71 | 71.7 72.7 72.0 77.1 | -| Section-header | 83-84 | 67.6 69.3 68.4 74.6 | -| Table | 77-81 | 82.2 82.9 82.2 86.3 | -| Text | 84-86 | 84.6 85.8 85.4 88.1 | -| Title | 60-72 | 76.7 80.4 79.9 82.7 | -| All | 82-83 | 72.4 73.5 73.4 76.8 | - -to avoid this at any cost in order to have clear, unbiased baseline numbers for human document-layout annotation. Third, we in troduced the feature of snapping boxes around text segments to obtain a pixel-accurate annotation and again reduce time and effort. The CCS annotation tool automatically shrinks every user-drawn box to the minimum bounding-box around the enclosed text-cells for all purely text-based segments, which excludes only Table and Picture . For the latter, we instructed annotation staff to minimise inclusion of surrounding whitespace while including all graphical lines. A downside of snapping boxes to enclosed text cells is that some wrongly parsed PDF pages cannot be annotated correctly and need to be skipped. Fourth, we established a way to flag pages as rejected for cases where no valid annotation according to the label guidelines could be achieved. Example cases for this would be PDF pages that render incorrectly or contain layouts that are impossible to capture with non-overlapping rectangles. Such rejected pages are not contained in the final dataset. With all these measures in place, experienced annotation staff managed to annotate a single page in a typical timeframe of 20s to 60s, depending on its complexity. - -## 5 EXPERIMENTS - -The primary goal of DocLayNet is to obtain high-quality ML models capable of accurate document-layout analysis on a wide variety of challenging layouts. As discussed in Section 2, object detection models are currently the easiest to use, due to the standardisation of ground-truth data in COCO format [ 16 ] and the availability of general frameworks such as detectron2 [ 17 ]. Furthermore, baseline numbers in PubLayNet and DocBank were obtained using standard object detection models such as Mask R-CNN and Faster R-CNN. As such, we will relate to these object detection methods in this - - - -Figure 5: Prediction performance (mAP@0.5-0.95) of a Mask R-CNN network with ResNet50 backbone trained on increas ing fractions of the DocLayNet dataset. The learning curve flattens around the 80% mark, indicating that increasing the size of the DocLayNet dataset with similar data will not yield significantly better predictions. - -paper and leave the detailed evaluation of more recent methods mentioned in Section 2 for future work. - -In this section, we will present several aspects related to the performance of object detection models on DocLayNet. Similarly as in PubLayNet, we will evaluate the quality of their predictions using mean average precision (mAP) with 10 overlaps that range from 0.5 to 0.95 in steps of 0.05 (mAP@0.5-0.95). These scores are computed by leveraging the evaluation code provided by the COCO API [16]. - -## Baselines for Object Detection - -In Table 2, we present baseline experiments (given in mAP) on Mask R-CNN [ 12 ], Faster R-CNN [ 11 ], and YOLOv5 [ 13 ]. Both training and evaluation were performed on RGB images with dimensions of 1025 × 1025 pixels. For training, we only used one annotation in case of redundantly annotated pages. As one can observe, the variation in mAP between the models is rather low, but overall between 6 and 10% lower than the mAP computed from the pairwise human annotations on triple-annotated pages. This gives a good indication that the DocLayNet dataset poses a worthwhile challenge for the research community to close the gap between human recognition and ML approaches. It is interesting to see that Mask R-CNN and Faster R-CNN produce very comparable mAP scores, indicating that pixel-based image segmentation derived from bounding-boxes does not help to obtain better predictions. On the other hand, the more recent Yolov5x model does very well and even out-performs humans on selected labels such as Text, t, Table and Picture . This is not entirely surprising, as Text, Table and Picture are abundant and the most visually distinctive in a document. t, - -Table 3: Performance of a Mask R-CNN R50 network in mAP@0.5-0.95 scores trained on DocLayNet with different class label sets. The reduced label sets were obtained by ei ther down-mapping or dropping labels. - -| Class-count | 11 6 5 4 | -|----------------|----------------------------| -| Caption | 68 Text Text Text | -| Footnote | 71 Text Text Text | -| Formula | 60 Text Text Text | -| List-item | 81 Text 82 Text | -| Page-footer | 62 62 - - | -| Page-header | 72 68 - - | -| Picture | 72 72 72 72 | -| Section-header | 68 67 69 68 | -| Table | 82 83 82 82 | -| Text | 85 84 84 84 | -| Title | 77 Sec.-h. Sec.-h. Sec.-h. | -| Overall | 72 73 78 77 | - -## Learning Curve - -One of the fundamental questions related to any dataset is if it is “large enough”. To answer this question for DocLayNet, we per formed a data ablation study in which we evaluated a Mask R-CNN model trained on increasing fractions of the DocLayNet dataset. As can be seen in Figure 5, the mAP score rises sharply in the be ginning and eventually levels out. To estimate the error-bar on the metrics, we ran the training five times on the entire data-set. This resulted in a 1% error-bar, depicted by the shaded area in Figure 5. In the inset of Figure 5, we show the exact same data-points, but with a logarithmic scale on the x-axis. As is expected, the mAP score increases linearly as a function of the data-size in the inset. The curve ultimately flattens out between the 80% and 100% mark, with the 80% mark falling within the error-bars of the 100% mark. This provides a good indication that the model would not improve significantly by yet increasing the data size. Rather, it would prob ably benefit more from improved data consistency (as discussed in Section 3), data augmentation methods [ ], or the addition of 23 more document categories and styles. - -## Impact of Class Labels - -The choice and number of labels can have a significant effect on the overall model performance. Since PubLayNet, DocBank and DocLayNet all have different label sets, it is of particular interest to understand and quantify this influence of the label set on the model performance. We investigate this by either down-mapping labels into more common ones (e.g. Caption Text ) or excluding them → from the annotations entirely. Furthermore, it must be stressed that all mappings and exclusions were performed on the data be fore model training. In Table 3, we present the mAP scores for a Mask R-CNN R50 network on different label sets. Where a label is down-mapped, we show its corresponding label, otherwise it was excluded. We present three different label sets, with 6, 5 and 4 different labels respectively. The set of 5 labels contains the same labels as PubLayNet. However, due to the different definition of - -Table 4: Performance of a Mask R-CNN R50 network with document-wise and page-wise split for different label sets. Naive page-wise split will result in ~ 10% point improve ment. - -| Class-count | | 11 | | 5 | -|----------------|----------|------|----------|-----| -| Split | Doc Page | | Doc Page | | -| Caption | 68 83 | | | | -| Footnote | 71 84 | | | | -| Formula | 60 66 | | | | -| List-item | 81 88 | | 82 88 | | -| Page-footer | 62 89 | | | | -| Page-header | 72 90 | | | | -| Picture | 72 82 | | 72 82 | | -| Section-header | 68 83 | | 69 83 | | -| Table | 82 89 | | 82 90 | | -| Text | 85 91 | | 84 90 | | -| Title | 77 81 | | | | -| All | 72 84 | | 78 87 | | - -lists in PubLayNet (grouped list-items) versus DocLayNet (separate list-items), the label set of size 4 is the closest to PubLayNet, in the assumption that the List is down-mapped to Text in PubLayNet. The results in Table 3 show that the prediction accuracy on the remaining class labels does not change significantly when other classes are merged into them. The overall macro-average improves by around 5%, in particular when Page-footer and Page-header are excluded. - -## Impact of Document Split in Train and Test Set - -Many documents in DocLayNet have a unique styling. In order to avoid overfitting on a particular style, we have split the train-, test- and validation-sets of DocLayNet on document boundaries, i.e. every document contributes pages to only one set. To the best of our knowledge, this was not considered in PubLayNet or DocBank. To quantify how this affects model performance, we trained and evaluated a Mask R-CNN R50 model on a modified dataset version. Here, the train-, test- and validation-sets were obtained by a ran domised draw over the individual pages. As can be seen in Table 4, the difference in model performance is surprisingly large: page wise splitting gains 10% in mAP over the document-wise splitting. ˜ Thus, random page-wise splitting of DocLayNet can easily lead to accidental overestimation of model performance and should be avoided. - -## Dataset Comparison - -Throughout this paper, we claim that DocLayNet’s wider variety of document layouts leads to more robust layout detection models. In Table 5, we provide evidence for that. We trained models on each of the available datasets (PubLayNet, DocBank and DocLayNet) and evaluated them on the test sets of the other datasets. Due to the different label sets and annotation styles, a direct comparison is not possible. Hence, we focussed on the common labels among the datasets. Between PubLayNet and DocLayNet, these are Picture , - -KDD ’22, August 14–18, 2022, Washington, DC, USA Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar - -Table 5: Prediction Performance (mAP@0.5-0.95) of a Mask R-CNN R50 network across the PubLayNet, DocBank & Do cLayNet data-sets. By evaluating on common label classes of each dataset, we observe that the DocLayNet-trained model has much less pronounced variations in performance across all datasets. - -| | | | | Testing on | -|-----------------|-------------|------------|------------|--------------| -| | Training on | labels | PLN DB DLN | | -| | | Figure | 96 43 23 | | -| | | Sec-header | 87 - 32 | | -| PubLayNet (PLN) | | Table | 95 24 49 | | -| | | Text | 96 - 42 | | -| | | total | 93 34 30 | | -| | | Figure | 77 71 31 | | -| DocBank (DB) | | Table | 19 65 22 | | -| | | total | 48 68 27 | | -| | | Figure | 67 51 72 | | -| | | Sec-header | 53 - 68 | | -| DocLayNet (DLN) | | Table | 87 43 82 | | -| | | Text | 77 - 84 | | -| | | total | 59 47 78 | | - -Section-header, Table and Text. t. Before training, we either mapped r, or excluded DocLayNet’s other labels as specified in table 3, and also PubLayNet’s List to Text. t. Note that the different clustering of lists (by list-element vs. whole list objects) naturally decreases the mAP score for Text. t. - -For comparison of DocBank with DocLayNet, we trained only and Table clusters of each dataset. We had to exclude on Picture Text because successive paragraphs are often grouped together into a single object in DocBank. This paragraph grouping is incompatible with the individual paragraphs of DocLayNet. As can be seen in Table 5, DocLayNet trained models yield better performance com pared to the previous datasets. It is noteworthy that the models trained on PubLayNet and DocBank perform very well on their own test set, but have a much lower performance on the foreign datasets. While this also applies to DocLayNet, the difference is far less pronounced. Thus we conclude that DocLayNet trained models are overall more robust and will produce better results for challenging, unseen layouts. - -## Example Predictions - -To conclude this section, we illustrate the quality of layout predic tions one can expect from DocLayNet-trained models by providing a selection of examples without any further post-processing ap plied. Figure 6 shows selected layout predictions on pages from the test-set of DocLayNet. Results look decent in general across docu ment categories, however one can also observe mistakes such as overlapping clusters of different classes, or entirely missing boxes due to low confidence. - -## 6 CONCLUSION - -In this paper, we presented the DocLayNet dataset. It provides the document conversion and layout analysis research community a new and challenging dataset to improve and fine-tune novel ML methods on. In contrast to many other datasets, DocLayNet was created by human annotation in order to obtain reliable layout ground-truth on a wide variety of publication- and typesetting styles. Including a large proportion of documents outside the scien tific publishing domain adds significant value in this respect. - -From the dataset, we have derived on the one hand reference metrics for human performance on document-layout annotation (through double and triple annotations) and on the other hand eval uated the baseline performance of commonly used object detection methods. We also illustrated the impact of various dataset-related aspects on model performance through data-ablation experiments, both from a size and class-label perspective. Last but not least, we compared the accuracy of models trained on other public datasets and showed that DocLayNet trained models are more robust. - -To date, there is still a significant gap between human and ML accuracy on the layout interpretation task, and we hope that this work will inspire the research community to close that gap. - -## REFERENCES - -- [1] Max Göbel, Tamir Hassan, Ermelinda Oro, and Giorgio Orsi. Icdar 2013 table competition. In 2013 12th International Conference on Document Analysis and Recognition , pages 1449–1453, 2013. -- [2] Christian Clausner, Apostolos Antonacopoulos, and Stefan Pletschacher. Ic dar2017 competition on recognition of documents with complex layouts - rdcl2017. In 2017 14th IAPR International Conference on Document Analysis and Recognition (ICDAR) , volume 01, pages 1404–1410, 2017. -- [3] Hervé Déjean, Jean-Luc Meunier, Liangcai Gao, Yilun Huang, Yu Fang, Florian Kleber, and Eva-Maria Lang. ICDAR 2019 Competition on Table Detection and Recognition (cTDaR), April 2019. http://sac.founderit.com/. -- [4] Antonio Jimeno Yepes, Peter Zhong, and Douglas Burdick. Competition on scientific literature parsing. In Proceedings of the International Conference on Document Analysis and Recognition , ICDAR, pages 605–617. LNCS 12824, Springer Verlag, sep 2021. -- [5] Logan Markewich, Hao Zhang, Yubin Xing, Navid Lambert-Shirzad, Jiang Zhexin, Roy Lee, Zhi Li, and Seok-Bum Ko. Segmentation for document layout analysis: not dead yet. International Journal on Document Analysis and Recognition (IJDAR) , pages 1–11, 01 2022. -- [6] Xu Zhong, Jianbin Tang, and Antonio Jimeno-Yepes. Publaynet: Largest dataset ever for document layout analysis. In Proceedings of the International Conference on Document Analysis and Recognition , ICDAR, pages 1015–1022, sep 2019. -- [7] Minghao Li, Yiheng Xu, Lei Cui, Shaohan Huang, Furu Wei, Zhoujun Li, and Ming Zhou. Docbank: A benchmark dataset for document layout analysis. In Proceedings of the 28th International Conference on Computational Linguistics , COLING, pages 949–960. International Committee on Computational Linguistics, dec 2020. -- [8] Riaz Ahmad, Muhammad Tanvir Afzal, and M. Qadir. Information extraction from pdf sources based on rule-based system using integrated formats. In SemWe bEval@ESWC, C, 2016. -- [9] Ross B. Girshick, Jeff Donahue, Trevor Darrell, and Jitendra Malik. Rich feature hierarchies for accurate object detection and semantic segmentation. In IEEE Conference on Computer Vision and Pattern Recognition , CVPR, pages 580–587. IEEE Computer Society, jun 2014. -- [10] Ross B. Girshick. Fast R-CNN. In 2015 IEEE International Conference on Computer Vision , ICCV, pages 1440–1448. IEEE Computer Society, dec 2015. -- [11] Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun. Faster r-cnn: Towards real-time object detection with region proposal networks. IEEE Transactions on Pattern Analysis and Machine Intelligence , 39(6):1137–1149, 2017. -- [12] Kaiming He, Georgia Gkioxari, Piotr Dollár, and Ross B. Girshick. Mask R-CNN. In IEEE International Conference on Computer Vision , ICCV, pages 2980–2988. IEEE Computer Society, Oct 2017. -- [13] Glenn Jocher, Alex Stoken, Ayush Chaurasia, Jirka Borovec, NanoCode012, TaoXie, Yonghye Kwon, Kalen Michael, Liu Changyu, Jiacong Fang, Abhiram V, Laughing, tkianai, yxNONG, Piotr Skalski, Adam Hogan, Jebastin Nadar, imyhxy, Lorenzo Mammana, Alex Wang, Cristi Fati, Diego Montes, Jan Hajek, Laurentiu - - - -Text Caption List Item Formula Table Picture Section Header Page Header Page Footer Title - -Diaconu, Mai Thanh Minh, Marc, albinxavi, fatih, oleg, and wanghao yang. ul tralytics/yolov5: v6.0 - yolov5n nano models, roboflow integration, tensorflow export, opencv dnn support, October 2021. - -- [14] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to-end object detection with transformers. CoRR , abs/2005.12872, 2020. -- [15] Mingxing Tan, Ruoming Pang, and Quoc V. Le. Efficientdet: Scalable and efficient object detection. CoRR , abs/1911.09070, 2019. -- [16] Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Gir shick, James Hays, Pietro Perona, Deva Ramanan, Piotr Dollár, and C. Lawrence Zitnick. Microsoft COCO: common objects in context, 2014. -- [17] Yuxin Wu, Alexander Kirillov, Francisco Massa, Wan-Yen Lo, and Ross Girshick. Detectron2, 2019. -- [18] Nikolaos Livathinos, Cesar Berrospi, Maksym Lysak, Viktor Kuropiatnyk, Ahmed Nassar, Andre Carvalho, Michele Dolfi, Christoph Auer, Kasper Dinkla, and Peter W. J. Staar. Robust pdf document conversion using recurrent neural networks. In Proceedings of the 35th Conference on Artificial Intelligence , AAAI, pages 15137– 15145, feb 2021. -- [19] Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, and Ming Zhou. Layoutlm: Pre-training of text and layout for document image understanding. In Proceedings of the 26th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining , KDD, pages 1192–1200, New York, USA, 2020. Asso ciation for Computing Machinery. - -Figure 6: Example layout predictions on selected pages from the DocLayNet test-set. (A, D) exhibit favourable results on coloured backgrounds. (B, C) show accurate list-item and paragraph differentiation despite densely-spaced lines. (E) demon strates good table and figure distinction. (F) shows predictions on a Chinese patent with multiple overlaps, label confusion and missing boxes. - -- [20] Shoubin Li, Xuyan Ma, Shuaiqun Pan, Jun Hu, Lin Shi, and Qing Wang. Vtlayout: Fusion of visual and text features for document layout analysis, 2021. -- [21] Peng Zhang, Can Li, Liang Qiao, Zhanzhan Cheng, Shiliang Pu, Yi Niu, and Fei Wu. Vsr: A unified framework for document layout analysis combining vision, semantics and relations, 2021. -- [22] Peter W J Staar, Michele Dolfi, Christoph Auer, and Costas Bekas. Corpus conversion service: A machine learning platform to ingest documents at scale. In Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining , KDD, pages 774–782. ACM, 2018. -- [23] Connor Shorten and Taghi M. Khoshgoftaar. A survey on image data augmenta tion for deep learning. Journal of Big Data , 6(1):60, 2019. diff --git a/tests/pdf_snapshots/pdf/sources/2305.03393v1-pg9.pdf.md b/tests/pdf_snapshots/pdf/sources/2305.03393v1-pg9.pdf.md deleted file mode 100644 index c6a477f6..00000000 --- a/tests/pdf_snapshots/pdf/sources/2305.03393v1-pg9.pdf.md +++ /dev/null @@ -1,30 +0,0 @@ -order to compute the TED score. Inference timing results for all experiments were obtained from the same machine on a single core with AMD EPYC 7763 CPU @2.45 GHz. - -## 5.1 Hyper Parameter Optimization - -We have chosen the PubTabNet data set to perform HPO, since it includes a highly diverse set of tables. Also we report TED scores separately for simple and complex tables (tables with cell spans). Results are presented in Table. 1. It is evident that with OTSL, our model achieves the same TED score and slightly better mAP scores in comparison to HTML. However OTSL yields a 2x speed up in the inference runtime over HTML. - -Table 1. HPO performed in OTSL and HTML representation on the same transformer-based TableFormer [9] architecture, trained only on PubTabNet [22]. Ef fects of reducing the # of layers in encoder and decoder stages of the model show that smaller models trained on OTSL perform better, especially in recognizing complex table structures, and maintain a much higher mAP score than the HTML counterpart. - -| | # | | # | | | TEDs | | mAP | Inference | | -|------------|-----|------------|-----|----------|--------|---------|-------|--------|-------------|------| -| | | | | Language | | | | (0.75) | time (secs) | | -| enc-layers | | dec-layers | | | simple | complex | all | | | | -| | | | | OTSL | 0.965 | 0.934 | 0.955 | 0.88 | | 2.73 | -| | 6 | | 6 | | | | | | | | -| | | | | HTML | 0.969 | 0.927 | 0.955 | 0.857 | | 5.39 | -| | | | | OTSL | 0.938 | 0.904 | 0.927 | 0.853 | | 1.97 | -| | 4 | | 4 | | | | | | | | -| | | | | HTML | 0.952 | 0.909 | 0.938 | 0.843 | | 3.77 | -| | | | | OTSL | 0.923 | 0.897 | 0.915 | 0.859 | | 1.91 | -| | 2 | | 4 | | | | | | | | -| | | | | HTML | 0.945 | 0.901 | 0.931 | 0.834 | | 3.81 | -| | | | | OTSL | 0.952 | 0.92 | 0.942 | 0.857 | | 1.22 | -| | 4 | | 2 | | | | | | | | -| | | | | HTML | 0.944 | 0.903 | 0.931 | 0.824 | | 2 | - -## 5.2 Quantitative Results - -We picked the model parameter configuration that produced the best prediction quality (enc=6, dec=6, heads=8) with PubTabNet alone, then independently trained and evaluated it on three publicly available data sets: PubTabNet (395k samples), FinTabNet (113k samples) and PubTables-1M (about 1M samples). Performance results are presented in Table. 2. It is clearly evident that the model trained on OTSL outperforms HTML across the board, keeping high TEDs and mAP scores even on di ffi cult financial tables (FinTabNet) that contain sparse and large tables. - -Additionally, the results show that OTSL has an advantage over HTML when applied on a bigger data set like PubTables-1M and achieves significantly improved scores. Finally, OTSL achieves faster inference due to fewer decoding steps which is a result of the reduced sequence representation. diff --git a/tests/pdf_snapshots/pdf/sources/2305.03393v1.pdf.md b/tests/pdf_snapshots/pdf/sources/2305.03393v1.pdf.md deleted file mode 100644 index d19b1793..00000000 --- a/tests/pdf_snapshots/pdf/sources/2305.03393v1.pdf.md +++ /dev/null @@ -1,208 +0,0 @@ -# Optimized Table Tokenization for Table Structure Recognition - -Maksym Lysak [0000 − 0002 − 3723 − 6960] , Ahmed Nassar [0000 − 0002 − 9468 − 0822] Nikolaos Livathinos [0000 − 0001 − 8513 − 3491] , Christoph Auer [0000 − 0001 − 5761 − 0422] , [0000 0002 8088 0823] , and Peter Staar − − − - -IBM Research {mly,ahn,nli,cau,taa}@zurich.ibm.com - -Abstract. Extracting tables from documents is a crucial task in any document conversion pipeline. Recently, transformer-based models have demonstrated that table-structure can be recognized with impressive ac curacy using Image-to-Markup-Sequence (Im2Seq) approaches. Taking only the image of a table, such models predict a sequence of tokens (e.g. in HTML, LaTeX) which represent the structure of the table. Since the token representation of the table structure has a significant impact on the accuracy and run-time performance of any Im2Seq model, we inves tigate in this paper how table-structure representation can be optimised. We propose a new, optimised table-structure language (OTSL) with a minimized vocabulary and specific rules. The benefits of OTSL are that it reduces the number of tokens to 5 (HTML needs 28+) and shortens the sequence length to half of HTML on average. Consequently, model accuracy improves significantly, inference time is halved compared to HTML-based models, and the predicted table structures are always syn tactically correct. This in turn eliminates most post-processing needs. Popular table structure data-sets will be published in OTSL format to the community. - -Keywords: Table Structure Recognition · Data Representation · Trans formers · Optimization. - -## 1 Introduction - -Tables are ubiquitous in documents such as scientific papers, patents, reports, manuals, specification sheets or marketing material. They often encode highly valuable information and therefore need to be extracted with high accuracy. Unfortunately, tables appear in documents in various sizes, styling and struc ture, making it difficult to recover their correct structure with simple analyt ical methods. Therefore, accurate table extraction is achieved these days with machine-learning based methods. - -In modern document understanding systems [1,15], table extraction is typi cally a two-step process. Firstly, every table on a page is located with a bounding box, and secondly, their logical row and column structure is recognized. As of - -Fig. 1. Comparison between HTML and OTSL table structure representation: (A) table-example with complex row and column headers, including a 2D empty span, (B) minimal graphical representation of table structure using rectangular layout, (C) HTML representation, (D) OTSL representation. This example demonstrates many of the key-features of OTSL, namely its reduced vocabulary size (12 versus 5 in this case), its reduced sequence length (55 versus 30) and a enhanced internal structure (variable token sequence length per row in HTML versus a fixed length of rows in OTSL). - - - -today, table detection in documents is a well understood problem, and the latest state-of-the-art (SOTA) object detection methods provide an accuracy compa rable to human observers [7,8,10,14,23]. On the other hand, the problem of table structure recognition (TSR) is a lot more challenging and remains a very active area of research, in which many novel machine learning algorithms are being explored [3,4,5,9,11,12,13,14,17,18,21,22]. - -Recently emerging SOTA methods for table structure recognition employ transformer-based models, in which an image of the table is provided to the net work in order to predict the structure of the table as a sequence of tokens. These image-to-sequence (Im2Seq) models are extremely powerful, since they allow for a purely data-driven solution. The tokens of the sequence typically belong to a markup language such as HTML, Latex or Markdown, which allow to describe table structure as rows, columns and spanning cells in various configurations. In Figure 1, we illustrate how HTML is used to represent the table-structure of a particular example table. Public table-structure data sets such as PubTab Net [22], and FinTabNet [21], which were created in a semi-automated way from paired PDF and HTML sources (e.g. PubMed Central), popularized primarily the use of HTML as ground-truth representation format for TSR. - -While the majority of research in TSR is currently focused on the develop ment and application of novel neural model architectures, the table structure representation language (e.g. HTML in PubTabNet and FinTabNet) is usually adopted as is for the sequence tokenization in Im2Seq models. In this paper, we aim for the opposite and investigate the impact of the table structure rep resentation language with an otherwise unmodified Im2Seq transformer-based architecture. Since the current state-of-the-art Im2Seq model is TableFormer [9], we select this model to perform our experiments. - -The main contribution of this paper is the introduction of a new optimised ta ble structure language (OTSL), specifically designed to describe table-structure in an compact and structured way for Im2Seq models. OTSL has a number of key features, which make it very attractive to use in Im2Seq models. Specifically, compared to other languages such as HTML, OTSL has a minimized vocabulary which yields short sequence length, strong inherent structure (e.g. strict rectan gular layout) and a strict syntax with rules that only look backwards. The latter allows for syntax validation during inference and ensures a syntactically correct table-structure. These OTSL features are illustrated in Figure 1, in comparison to HTML. - -The paper is structured as follows. In section 2, we give an overview of the latest developments in table-structure reconstruction. In section 3 we review the current HTML table encoding (popularised by PubTabNet and FinTabNet) and discuss its flaws. Subsequently, we introduce OTSL in section 4, which in cludes the language definition, syntax rules and error-correction procedures. In section 5, we apply OTSL on the TableFormer architecture, compare it to Table Former models trained on HTML and ultimately demonstrate the advantages of using OTSL. Finally, in section 6 we conclude our work and outline next potential steps. - -## 2 Related Work - -Approaches to formalize the logical structure and layout of tables in electronic documents date back more than two decades [16]. In the recent past, a wide variety of computer vision methods have been explored to tackle the prob lem of table structure recognition, i.e. the correct identification of columns, rows and spanning cells in a given table. Broadly speaking, the current deep learning based approaches fall into three categories: object detection (OD) meth ods, Graph-Neural-Network (GNN) methods and Image-to-Markup-Sequence (Im2Seq) methods. Object-detection based methods [11,12,13,14,21] rely on table structure annotation using (overlapping) bounding boxes for training, and pro duce bounding-box predictions to define table cells, rows, and columns on a table image. Graph Neural Network (GNN) based methods [3,6,17,18], as the name suggests, represent tables as graph structures. The graph nodes represent the content of each table cell, an embedding vector from the table image, or geomet ric coordinates of the table cell. The edges of the graph define the relationship between the nodes, e.g. if they belong to the same column, row, or table cell. - -Other work [20] aims at predicting a grid for each table and deciding which cells must be merged using an attention network. Im2Seq methods cast the problem as a sequence generation task [4,5,9,22], and therefore need an internal table structure representation language, which is often implemented with standard markup languages (e.g. HTML, LaTeX, Markdown). In theory, Im2Seq methods have a natural advantage over the OD and GNN methods by virtue of directly predicting the table-structure. As such, no post-processing or rules are needed in order to obtain the table-structure, which is necessary with OD and GNN approaches. In practice, this is not entirely true, because a predicted sequence of table-structure markup does not necessarily have to be syntactically correct. Hence, depending on the quality of the predicted sequence, some post-processing needs to be performed to ensure a syntactically valid (let alone correct) sequence. - -Within the Im2Seq method, we find several popular models, namely the encoder-dual-decoder model (EDD) [22], TableFormer [9], Tabsplitter[2] and Ye et. al. [19]. EDD uses two consecutive long short-term memory (LSTM) decoders to predict a table in HTML representation. The tag decoder predicts a sequence of HTML tags. For each decoded table cell ( ), the attention is passed to the cell decoder to predict the content with an embedded OCR approach. The latter makes it susceptible to transcription errors in the cell content of the table. TableFormer address this reliance on OCR and uses two transformer decoders for HTML structure and cell bounding box prediction in an end-to-end architecture. The predicted cell bounding box is then used to extract text tokens from an originating (digital) PDF page, circumventing any need for OCR. TabSplitter [2] proposes a compact double-matrix representation of table rows and columns to do error detection and error correction of HTML structure sequences based on predictions from [19]. This compact double-matrix representation can not be used directly by the Img2seq model training, so the model uses HTML as an intermediate form. Chi et. al. [4] introduce a data set and a baseline method using bidirectional LSTMs to predict LaTeX code. Kayal [5] introduces Gated ResNet transformers to predict LaTeX code, and a separate OCR module to extract content. - -Im2Seq approaches have shown to be well-suited for the TSR task and allow a full end-to-end network design that can output the final table structure without pre- or post-processing logic. Furthermore, Im2Seq models have demonstrated to deliver state-of-the-art prediction accuracy [9]. This motivated the authors to investigate if the performance (both in accuracy and inference time) can be further improved by optimising the table structure representation language. We believe this is a necessary step before further improving neural network architectures for this task. - -## 3 Problem Statement - -All known Im2Seq based models for TSR fundamentally work in similar ways. Given an image of a table, the Im2Seq model predicts the structure of the table by generating a sequence of tokens. These tokens originate from a finite vocab- - -ulary and can be interpreted as a table structure. For example, with the HTML tokens
and , one can construct simple table structures without any spanning cells. In reality though, one needs , , , , at least 28 HTML tokens to describe the most common complex tables observed in real-world documents [21,22], due to a variety of spanning cells definitions in the HTML token vocabulary. - -Fig. 2. Frequency of tokens in HTML and OTSL as they appear in PubTabNet. - - - -Obviously, HTML and other general-purpose markup languages were not de signed for Im2Seq models. As such, they have some serious drawbacks. First, the token vocabulary needs to be artificially large in order to describe all plausible tabular structures. Since most Im2Seq models use an autoregressive approach, they generate the sequence token by token. Therefore, to reduce inference time, a shorter sequence length is critical. Every table-cell is represented by at least two tokens ( and ). Furthermore, when tokenizing the HTML struc ture, one needs to explicitly enumerate possible column-spans and row-spans as words. In practice, this ends up requiring 28 different HTML tokens (when including column- and row-spans up to 10 cells) just to describe every table in the PubTabNet dataset. Clearly, not every token is equally represented, as is depicted in Figure 2. This skewed distribution of tokens in combination with variable token row-length makes it challenging for models to learn the HTML structure. - -Additionally, it would be desirable if the representation would easily allow an early detection of invalid sequences on-the-go, before the prediction of the entire table structure is completed. HTML is not well-suited for this purpose as the verification of incomplete sequences is non-trivial or even impossible. - -In a valid HTML table, the token sequence must describe a 2D grid of table cells, serialised in row-major ordering, where each row and each column have the same length (while considering row- and column-spans). Furthermore, every opening tag in HTML needs to be matched by a closing tag in a correct hierar chical manner. Since the number of tokens for each table row and column can vary significantly, especially for large tables with many row- and column-spans, it is complex to verify the consistency of predicted structures during sequence - -generation. Implicitly, this also means that Im2Seq models need to learn these complex syntax rules, simply to deliver valid output. - -In practice, we observe two major issues with prediction quality when train ing Im2Seq models on HTML table structure generation from images. On the one hand, we find that on large tables, the visual attention of the model often starts to drift and is not accurately moving forward cell by cell anymore. This manifests itself in either in an increasing location drift for proposed table-cells in later rows on the same column or even complete loss of vertical alignment, as illustrated in Figure 5. Addressing this with post-processing is partially possible, but clearly undesired. On the other hand, we find many instances of predictions with structural inconsistencies or plain invalid HTML output, as shown in Fig ure 6, which are nearly impossible to properly correct. Both problems seriously impact the TSR model performance, since they reflect not only in the task of pure structure recognition but also in the equally crucial recognition or matching of table cell content. - -## 4 Optimised Table Structure Language - -To mitigate the issues with HTML in Im2Seq-based TSR models laid out before, we propose here our Optimised Table Structure Language (OTSL). OTSL is designed to express table structure with a minimized vocabulary and a simple set of rules, which are both significantly reduced compared to HTML. At the same time, OTSL enables easy error detection and correction during sequence generation. We further demonstrate how the compact structure representation and minimized sequence length improves prediction accuracy and inference time in the TableFormer architecture. - -## 4.1 Language Definition - -In Figure 3, we illustrate how the OTSL is defined. In essence, the OTSL defines only 5 tokens that directly describe a tabular structure based on an atomic 2D grid. - -The OTSL vocabulary is comprised of the following tokens: - -- "C" cell - a new table cell that either has or does not have cell content – -- – "L" cell - left-looking cell , merging with the left neighbor cell to create a span -- "U" cell - up-looking cell , merging with the upper neighbor cell to create a – span -- "X" cell - cross cell , to merge with both left and upper neighbor cells – -- "NL" - new-line , switch to the next row. – - -A notable attribute of OTSL is that it has the capability of achieving lossless conversion to HTML. - -Fig. 3. OTSL description of table structure: A - table example; B - graphical repre sentation of table structure; C - mapping structure on a grid; D - OTSL structure encoding; E - explanation on cell encoding - - - -## 4.2 Language Syntax - -The OTSL representation follows these syntax rules: - -- 1. Left-looking cell rule : The left neighbour of an "L" cell must be either another "L" cell or a "C" cell. -- 2. Up-looking cell rule : The upper neighbour of a "U" cell must be either another "U" cell or a "C" cell. -- 3. Cross cell rule : - -The left neighbour of an "X" cell must be either another "X" cell or a "U" cell, and the upper neighbour of an "X" cell must be either another "X" cell or an "L" cell. - -- 4. First row rule : Only "L" cells and "C" cells are allowed in the first row. -- 5. First column rule : Only "U" cells and "C" cells are allowed in the first column. -- 6. Rectangular rule : The table representation is always rectangular - all rows must have an equal number of tokens, terminated with "NL" token. - -The application of these rules gives OTSL a set of unique properties. First of all, the OTSL enforces a strictly rectangular structure representation, where every new-line token starts a new row. As a consequence, all rows and all columns have exactly the same number of tokens, irrespective of cell spans. Secondly, the OTSL representation is unambiguous: Every table structure is represented in one way. In this representation every table cell corresponds to a "C"-cell token, which in case of spans is always located in the top-left corner of the table cell definition. Third, OTSL syntax rules are only backward-looking. As a consequence, every predicted token can be validated straight during sequence generation by looking at the previously predicted sequence. As such, OTSL can guarantee that every predicted sequence is syntactically valid. - -These characteristics can be easily learned by sequence generator networks, as we demonstrate further below. We find strong indications that this pattern - -reduces significantly the column drift seen in the HTML based models (see Fig ure 5). - -## 4.3 Error-detection and -mitigation - -The design of OTSL allows to validate a table structure easily on an unfinished sequence. The detection of an invalid sequence token is a clear indication of a prediction mistake, however a valid sequence by itself does not guarantee pre diction correctness. Different heuristics can be used to correct token errors in an invalid sequence and thus increase the chances for accurate predictions. Such heuristics can be applied either after the prediction of each token, or at the end on the entire predicted sequence. For example a simple heuristic which can cor rect the predicted OTSL sequence on-the-fly is to verify if the token with the highest prediction confidence invalidates the predicted sequence, and replace it by the token with the next highest confidence until OTSL rules are satisfied. - -## 5 Experiments - -To evaluate the impact of OTSL on prediction accuracy and inference times, we conducted a series of experiments based on the TableFormer model (Figure 4) with two objectives: Firstly we evaluate the prediction quality and performance of OTSL vs. HTML after performing Hyper Parameter Optimization (HPO) on the canonical PubTabNet data set. Secondly we pick the best hyper-parameters found in the first step and evaluate how OTSL impacts the performance of TableFormer after training on other publicly available data sets (FinTabNet, PubTables-1M [14]). The ground truth (GT) from all data sets has been con verted into OTSL format for this purpose, and will be made publicly available. - -Fig. 4. Architecture sketch of the TableFormer model, which is a representative for the Im2Seq approach. - - - -We rely on standard metrics such as Tree Edit Distance score (TEDs) for table structure prediction, and Mean Average Precision (mAP) with 0.75 Inter section Over Union (IOU) threshold for the bounding-box predictions of table cells. The predicted OTSL structures were converted back to HTML format in - -order to compute the TED score. Inference timing results for all experiments were obtained from the same machine on a single core with AMD EPYC 7763 CPU @2.45 GHz. - -## 5.1 Hyper Parameter Optimization - -We have chosen the PubTabNet data set to perform HPO, since it includes a highly diverse set of tables. Also we report TED scores separately for simple and complex tables (tables with cell spans). Results are presented in Table. 1. It is evident that with OTSL, our model achieves the same TED score and slightly better mAP scores in comparison to HTML. However OTSL yields a 2x speed up in the inference runtime over HTML. - -Table 1. HPO performed in OTSL and HTML representation on the same transformer-based TableFormer [9] architecture, trained only on PubTabNet [22]. Ef fects of reducing the # of layers in encoder and decoder stages of the model show that smaller models trained on OTSL perform better, especially in recognizing complex table structures, and maintain a much higher mAP score than the HTML counterpart. - -| | # | | # | | | TEDs | | mAP | Inference | | -|------------|-----|------------|-----|----------|--------|---------|-------|--------|-------------|------| -| | | | | Language | | | | (0.75) | time (secs) | | -| enc-layers | | dec-layers | | | simple | complex | all | | | | -| | | | | OTSL | 0.965 | 0.934 | 0.955 | 0.88 | | 2.73 | -| | 6 | | 6 | | | | | | | | -| | | | | HTML | 0.969 | 0.927 | 0.955 | 0.857 | | 5.39 | -| | | | | OTSL | 0.938 | 0.904 | 0.927 | 0.853 | | 1.97 | -| | 4 | | 4 | | | | | | | | -| | | | | HTML | 0.952 | 0.909 | 0.938 | 0.843 | | 3.77 | -| | | | | OTSL | 0.923 | 0.897 | 0.915 | 0.859 | | 1.91 | -| | 2 | | 4 | | | | | | | | -| | | | | HTML | 0.945 | 0.901 | 0.931 | 0.834 | | 3.81 | -| | | | | OTSL | 0.952 | 0.92 | 0.942 | 0.857 | | 1.22 | -| | 4 | | 2 | | | | | | | | -| | | | | HTML | 0.944 | 0.903 | 0.931 | 0.824 | | 2 | - -## 5.2 Quantitative Results - -We picked the model parameter configuration that produced the best prediction quality (enc=6, dec=6, heads=8) with PubTabNet alone, then independently trained and evaluated it on three publicly available data sets: PubTabNet (395k samples), FinTabNet (113k samples) and PubTables-1M (about 1M samples). Performance results are presented in Table. 2. It is clearly evident that the model trained on OTSL outperforms HTML across the board, keeping high TEDs and mAP scores even on difficult financial tables (FinTabNet) that contain sparse and large tables. - -Additionally, the results show that OTSL has an advantage over HTML when applied on a bigger data set like PubTables-1M and achieves significantly improved scores. Finally, OTSL achieves faster inference due to fewer decoding steps which is a result of the reduced sequence representation. - -Table 2. TSR and cell detection results compared between OTSL and HTML on the PubTabNet [22], FinTabNet [21] and PubTables-1M [14] data sets using Table Former [9] (with enc=6, dec=6, heads=8). - -| | | | | TEDs | | | | Inference | | -|--------------|----------|----------|--------|---------|-------|-----------|-------|-------------|------| -| | Data set | Language | | | | mAP(0.75) | | time (secs) | | -| | | | simple | complex | all | | | | | -| | | OTSL | 0.965 | 0.934 | 0.955 | | 0.88 | | 2.73 | -| PubTabNet | | | | | | | | | | -| | | HTML | 0.969 | 0.927 | 0.955 | | 0.857 | | 5.39 | -| | | OTSL | 0.955 | 0.961 | 0.959 | | 0.862 | | 1.85 | -| FinTabNet | | | | | | | | | | -| | | HTML | 0.917 | 0.922 | 0.92 | | 0.722 | | 3.26 | -| | | OTSL | 0.987 | 0.964 | 0.977 | | 0.896 | | 1.79 | -| PubTables-1M | | | | | | | | | | -| | | HTML | 0.983 | 0.944 | 0.966 | | 0.889 | | 3.26 | - -## 5.3 Qualitative Results - -To illustrate the qualitative differences between OTSL and HTML, Figure 5 demonstrates less overlap and more accurate bounding boxes with OTSL. In Figure 6, OTSL proves to be more effective in handling tables with longer to ken sequences, resulting in even more precise structure prediction and bounding boxes. - -Fig. 5. The OTSL model produces more accurate bounding boxes with less over lap (E) than the HTML model (D), when predicting the structure of a sparse ta ble (A), at twice the inference speed because of shorter sequence length (B),(C). "PMC2807444_006_00.png" PubTabNet. μ - - - -Fig. 6. Visualization of predicted structure and detected bounding boxes on a complex table with many rows. The OTSL model (B) captured repeating pattern of horizontally merged cells from the GT (A), unlike the HTML model (C). The HTML model also didn’t complete the HTML sequence correctly and displayed a lot more of drift and overlap of bounding boxes. "PMC5406406_003_01.png" PubTabNet. - - - -## 6 Conclusion - -We demonstrated that representing tables in HTML for the task of table struc ture recognition with Im2Seq models is ill-suited and has serious limitations. Furthermore, we presented in this paper an Optimized Table Structure Language (OTSL) which, when compared to commonly used general purpose languages, has several key benefits. - -First and foremost, given the same network configuration, inference time for a table-structure prediction is about 2 times faster compared to the conventional HTML approach. This is primarily owed to the shorter sequence length of the OTSL representation. Additional performance benefits can be obtained with HPO (hyper parameter optimization). As we demonstrate in our experiments, models trained on OTSL can be significantly smaller, e.g. by reducing the number of encoder and decoder layers, while preserving comparatively good prediction quality. This can further improve inference performance, yielding 5-6 times faster inference speed in OTSL with prediction quality comparable to models trained on HTML (see Table 1). - -Secondly, OTSL has more inherent structure and a significantly restricted vo cabulary size. This allows autoregressive models to perform better in the TED metric, but especially with regards to prediction accuracy of the table-cell bound ing boxes (see Table 2). As shown in Figure 5, we observe that the OTSL dras tically reduces the drift for table cell bounding boxes at high row count and in sparse tables. This leads to more accurate predictions and a significant reduction in post-processing complexity, which is an undesired necessity in HTML-based Im2Seq models. Significant novelty lies in OTSL syntactical rules, which are few, simple and always backwards looking. Each new token can be validated only by analyzing the sequence of previous tokens, without requiring the entire sequence to detect mistakes. This in return allows to perform structural error detection and correction on-the-fly during sequence generation. - -## References - -- 1. Auer, C., Dolfi, M., Carvalho, A., Ramis, C.B., Staar, P.W.J.: Delivering doc ument conversion as a cloud service with high throughput and responsiveness. CoRR abs/2206.00785 (2022). https://doi.org/10.48550/arXiv.2206.00785 , https://doi.org/10.48550/arXiv.2206.00785 -- 2. Chen, B., Peng, D., Zhang, J., Ren, Y., Jin, L.: Complex table structure recognition in the wild using transformer and identity matrix-based augmentation. In: Porwal, U., Fornés, A., Shafait, F. (eds.) Frontiers in Handwriting Recognition. pp. 545– 561. Springer International Publishing, Cham (2022) -- 3. Chi, Z., Huang, H., Xu, H.D., Yu, H., Yin, W., Mao, X.L.: Complicated table structure recognition. arXiv preprint arXiv:1908.04729 (2019) -- 4. Deng, Y., Rosenberg, D., Mann, G.: Challenges in end-to-end neural scientific table recognition. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 894–901. IEEE (2019) -- 5. Kayal, P., Anand, M., Desai, H., Singh, M.: Tables to latex: structure and content extraction from scientific tables. International Journal on Document Analysis and Recognition (IJDAR) pp. 1–10 (2022) -- 6. Lee, E., Kwon, J., Yang, H., Park, J., Lee, S., Koo, H.I., Cho, N.I.: Table structure recognition based on grid shape graph. In: 2022 Asia-Pacific Signal and Information Processing Association Annual Summit and Conference (APSIPA ASC). pp. 1868– 1873. IEEE (2022) -- 7. Li, M., Cui, L., Huang, S., Wei, F., Zhou, M., Li, Z.: Tablebank: A benchmark dataset for table detection and recognition (2019) -- 8. Livathinos, N., Berrospi, C., Lysak, M., Kuropiatnyk, V., Nassar, A., Carvalho, A., Dolfi, M., Auer, C., Dinkla, K., Staar, P.: Robust pdf document conversion using recurrent neural networks. Proceedings of the AAAI Conference on Artificial Intelligence 35 (17), 15137–15145 (May 2021), https://ojs.aaai.org/index.php/ AAAI/article/view/17777 -- 9. Nassar, A., Livathinos, N., Lysak, M., Staar, P.: Tableformer: Table structure un derstanding with transformers. In: Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). pp. 4614–4623 (June 2022) -- 10. Pfitzmann, B., Auer, C., Dolfi, M., Nassar, A.S., Staar, P.W.J.: Doclaynet: A large human-annotated dataset for document-layout segmentation. In: Zhang, A., Rangwala, H. (eds.) KDD ’22: The 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, Washington, DC, USA, August 14 - 18, 2022. pp. 3743–3751. ACM (2022). https://doi.org/10.1145/3534678.3539043 https:// doi.org/10.1145/3534678.3539043 , -- 11. Prasad, D., Gadpal, A., Kapadni, K., Visave, M., Sultanpure, K.: Cascadetabnet: An approach for end to end table detection and structure recognition from image based documents. In: Proceedings of the IEEE/CVF conference on computer vision and pattern recognition workshops. pp. 572–573 (2020) -- 12. Schreiber, S., Agne, S., Wolf, I., Dengel, A., Ahmed, S.: Deepdesrt: Deep learning for detection and structure recognition of tables in document images. In: 2017 14th IAPR international conference on document analysis and recognition (ICDAR). vol. 1, pp. 1162–1167. IEEE (2017) -- 13. Siddiqui, S.A., Fateh, I.A., Rizvi, S.T.R., Dengel, A., Ahmed, S.: Deeptabstr: Deep learning based table structure recognition. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 1403–1409 (2019). https:// doi.org/10.1109/ICDAR.2019.00226 -- 14. Smock, B., Pesala, R., Abraham, R.: PubTables-1M: Towards comprehensive ta ble extraction from unstructured documents. In: Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). pp. 4634–4642 (June 2022) -- 15. Staar, P.W.J., Dolfi, M., Auer, C., Bekas, C.: Corpus conversion service: A ma chine learning platform to ingest documents at scale. In: Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Min ing. pp. 774–782. KDD ’18, Association for Computing Machinery, New York, NY, USA (2018). https://doi.org/10.1145/3219819.3219834 , https://doi.org/10. 1145/3219819.3219834 -- 16. Wang, X.: Tabular Abstraction, Editing, and Formatting. Ph.D. thesis, CAN (1996), aAINN09397 -- 17. Xue, W., Li, Q., Tao, D.: Res2tim: Reconstruct syntactic structures from table images. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 749–755. IEEE (2019) -- 18. Xue, W., Yu, B., Wang, W., Tao, D., Li, Q.: Tgrnet: A table graph reconstruc tion network for table structure recognition. In: Proceedings of the IEEE/CVF International Conference on Computer Vision. pp. 1295–1304 (2021) -- 19. Ye, J., Qi, X., He, Y., Chen, Y., Gu, D., Gao, P., Xiao, R.: Pingan-vcgroup’s solution for icdar 2021 competition on scientific literature parsing task b: Ta ble recognition to html (2021). https://doi.org/10.48550/ARXIV.2105.01848 , https://arxiv.org/abs/2105.01848 -- 20. Zhang, Z., Zhang, J., Du, J., Wang, F.: Split, embed and merge: An accurate table structure recognizer. Pattern Recognition 126 , 108565 (2022) -- 21. Zheng, X., Burdick, D., Popa, L., Zhong, X., Wang, N.X.R.: Global table extractor (gte): A framework for joint table identification and cell structure recognition using visual context. In: 2021 IEEE Winter Conference on Applications of Computer Vi sion (WACV). pp. 697–706 (2021). https://doi.org/10.1109/WACV48630.2021. 00074 -- 22. Zhong, X., ShafieiBavani, E., Jimeno Yepes, A.: Image-based table recognition: Data, model, and evaluation. In: Vedaldi, A., Bischof, H., Brox, T., Frahm, J.M. (eds.) Computer Vision – ECCV 2020. pp. 564–580. Springer International Pub lishing, Cham (2020) -- 23. Zhong, X., Tang, J., Yepes, A.J.: Publaynet: largest dataset ever for document lay out analysis. In: 2019 International Conference on Document Analysis and Recog nition (ICDAR). pp. 1015–1022. IEEE (2019) diff --git a/tests/pdf_snapshots/pdf/sources/multi_page.pdf.md b/tests/pdf_snapshots/pdf/sources/multi_page.pdf.md deleted file mode 100644 index fad77844..00000000 --- a/tests/pdf_snapshots/pdf/sources/multi_page.pdf.md +++ /dev/null @@ -1,87 +0,0 @@ -## The Evolution of the Word Processor - -The concept of the word processor predates modern computers and has evolved through several technological milestones. - -## Pre Digital Era (19th Early 20th Century) - - - -The origins of word processing can be traced back to the invention of the typewriter in the mid 19th century. Patented in 1868 by Christopher Latham Sholes, the typewriter revolutionized written communication by enabling people to produce legible, professi - onal documents more efficiently than handwriting. - -During this period, the term "word processing" didn't exist, but the typewriter laid the groundwork for future developments. Over time, advancements such as carbon paper (for copies) and the electric typewriter (introduced by IBM in 1935) improved the spee d and convenience of document creation. - -## The Birth of Word Processing (1960s 1970s) - - -The term "word processor" first emerged in the 1960s and referred to any system designed to streamline written communication and document production. Early word processors were not software programs but rather standalone machines. - -- • IBM MT/ST (Magnetic Tape/Selectric Typewriter) : Introduced in 1964, this machine combined IBM's Selectric typewriter with magnetic tape storage. It allowed users to record, edit, and replay typed content— an early example of digital text t— storage. -- • Wang Laboratories : In the 1970s, Wang introduced dedicated word processing machines. These devices, like the Wang 1200, featured small screens and floppy disks, making them revolutionary for their time. - -These machines were primarily used in offices, where secretarial pools benefited from their ability to make revisions without retyping entire documents. - -## The Rise of Personal Computers (1980s) - -The advent of personal computers in the late 1970s and early 1980s transformed word processing from a niche tool to an essential technology for businesses and individuals alike. - -- • WordStar (1978) : Developed for the CP/M operating system, WordStar was one of the first widely used word processing programs. It featured early examples of modern features like cut, copy, and paste. -- • Microsoft Word (1983) : Microsoft launched Word for MS - DOS in 1983, introducing a graphical user interface (GUI) and mouse support. Over the years, Microsoft Word became the industry standard for word processing. - -Other notable software from this era included WordPerfect, which was popular among legal professionals, and Apple’s MacWrite, which leveraged the Macintosh’s graphical capabilities. - -## The Modern Era (1990s Present) - - -By the 1990s, word processing software had become more sophisticated, with features like spell check, grammar check, templates, and collaborative tools. - -- • Microsoft Office Suite : Microsoft continued to dominate with its Office Suite, integrating Word with other productivity tools like Excel and PowerPoint. -- • OpenOffice and LibreOffice : Open - source alternatives emerged in the early 2000s, offering free and flexible word processing options. -- • Google Docs (2006) : The introduction of cloud based word processing revolutionized collaboration. Google Docs enabled real time editing and sharing, making it a staple - - for teams and remote work. - -## Future of Word Processing - -Today, word processors are more than just tools for typing. They integrate artificial intelligence for grammar and style suggestions (e.g., Grammarly), voice - to - text features, and advanced layout options. As AI continues to advance, word processors may evo lve into even more intuitive tools that predict user needs, automate repetitive tasks, and support richer multimedia integration. - -From the clunky typewriters of the 19th century to the AI - powered cloud tools of today, the word processor has come a long way. It remains an essential tool for communication and creativity, shaping how we write and share ideas. - -## Specialized Word Processing Tools - -In addition to general - purpose word processors, specialized tools have emerged to cater to specific industries and needs. These tools incorporate unique features tailored to their users' workflows: - -- • Academic and Technical Writing : Tools like LaTeX gained popularity among academics, scientists, and engineers. Unlike traditional word processors, LaTeX focuses on precise formatting, particularly for complex mathematical equations, scientific papers, and technical documents. It relies on a markup language to produce polished documents suitable for publishing. -- • Screenwriting Software : For screenwriters, tools like Final Draft and Celtx are specialized to handle scripts for film and television. These programs automate the formatting of dialogue, scene descriptions, and other elements unique to screenwriting. -- • Legal Document Processors : Word processors tailored for legal professionals, like WordPerfect, offered features such as redlining (early version tracking) and document comparison. Even today, many law firms rely on these tools due to their robust formatting options for contracts a nd legal briefs. - -## Key Features That Changed Word Processing - -The evolution of word processors wasn't just about hardware or software improvements — it was about the features that revolutionized how people wrote and edited. Some of these transformative features include: - -- 1. Undo/Redo : Introduced in the 1980s, the ability to undo mistakes and redo actions made experimentation and error correction much easier. -- 2. Spell Check and Grammar Check : By the 1990s, these became standard, allowing users to spot errors automatically. -- 3. Templates : Pre - designed formats for documents, such as resumes, letters, and invoices, helped users save time. -- 4. Track Changes : A game changer for collaboration, this feature allowed multiple - users to suggest edits while maintaining the original text. -- 5. Real - Time Collaboration : Tools like Google Docs and Microsoft 365 enabled multiple users to edit the same document simultaneously, forever changing teamwork dynamics. - -## The Cultural Impact of Word Processors - -The word processor didn't just change workplaces it changed culture. It democratized writing, enabling anyone with access to a computer to produce professional — quality - documents. This shift had profound implications for education, business, and creative fi elds: - -- • Accessibility : Writers no longer needed expensive publishing equipment or training in typesetting to create polished work. This accessibility paved the way for self publishing, blogging, and even fan fiction communities. f -- • Education : Word processors became a cornerstone of education, teaching students not only how to write essays but also how to use technology effectively. Features like bibliography generators and integrated research tools enhanced learning. -- Creative Writing : Writers gained powerful tools to organize their ideas. Programs • like Scrivener allowed authors to manage large projects, from novels to screenplays, with features like chapter outlines and character notes. - -## Word Processors in a Post Digital Era - - -As we move further into the 21st century, the role of the word processor continues to evolve: - -- 1. Artificial Intelligence : Modern word processors are leveraging AI to suggest content improvements. Tools like Grammarly, ProWritingAid, and even native features in Word now analyze tone, conciseness, and clarity. Some AI systems can even generate entire paragraphs or rewrite sen tences. -- 2. Integration with Other Tools : Word processors are no longer standalone. They integrate with task managers, cloud storage, and project management platforms. For instance, Google Docs syncs with Google Drive, while Microsoft Word integrates seamlessly with OneDrive and Teams. -- 3. Voice Typing : Speech text capabilities have made word processing more - to - accessible, particularly for those with disabilities. Tools like Dragon NaturallySpeaking and built - in options in Google Docs and Microsoft Word have made dictation mainstream. -- : Word processing has expanded beyond text. Modern tools 4. Multimedia Documents allow users to embed images, videos, charts, and interactive elements, transforming simple documents into rich multimedia experiences. -- 5. Cross Platform Accessibility : Thanks to cloud computing, documents can now be - accessed and edited across devices. Whether you're on a desktop, tablet, or smartphone, you can continue working seamlessly. - -## A Glimpse Into the Future - -The word processor's future lies in adaptability and intelligence. Some exciting possibilities include: - -- Fully AI Assisted Writing : Imagine a word processor that understands your writing • - style, drafts emails, or creates entire essays based on minimal input. -- • Immersive Interfaces : As augmented reality (AR) and virtual reality (VR) technology advance, users may be able to write and edit in 3D spaces, collaborating in virtual environments. -- • Hyper - Personalization : Word processors could offer dynamic suggestions based on industry specific needs, user habits, or even regional language variations. - - -The journey of the word processor— from clunky typewriters to AI powered platforms r— - — reflects humanity’s broader technological progress. What began as a tool to simply replace handwriting has transformed into a powerful ally for creativity, communication, and collaboration. As technology continues to advance, the word processor will undoubtedly remain at the heart of how we express ideas and connect with one another. diff --git a/tests/pdf_snapshots/pdf/sources/redp5110_sampled.pdf.md b/tests/pdf_snapshots/pdf/sources/redp5110_sampled.pdf.md deleted file mode 100644 index e01ce4e5..00000000 --- a/tests/pdf_snapshots/pdf/sources/redp5110_sampled.pdf.md +++ /dev/null @@ -1,361 +0,0 @@ -Implement roles and separation of duties - -Leverage row permissions on the database - -Protect columns by defining column masks - -ibm.com /redbooks - - - -# Row and Column Access Control Support in IBM DB2 for i - - - -Jim Bainbridge Hernando Bedoya Rob Bestgen Mike Cain Dan Cruikshank Jim Denton Doug Mack Tom McKinley Kent Milligan - -Red paper - -## Contents - - - -IBM Systems Lab Services and Training Solution Brief - - - -## Highlights - --               --                     --       !   " #  --  ! #      " "       - - - -Power Services - -## DB2 for i Center of Excellence - -Expert help to achieve your business requirements - -## We build confident, satisfied clients - -No one else has the vast consulting experiences, skills sharing and renown service offerings to do what we can do for you. - -Because no one else is IBM. - -With combined experiences and direct access to development groups, we’re the experts in IBM DB2® for i. The DB2 for i Center of Excellence (CoE) can help you achieve—perhaps reexamine and exceed—your business requirements and gain more confidence and satisfaction in IBM product data management products and solutions. - -## Who we are, some of what we do - -Global CoE engagements cover topics including: - -- Database performance and scalability r -- r Advanced SQL knowledge and skills transfer -- r Business intelligence and analytics -- DB2 Web Query r -- r Query/400 modernization for better reporting and analysis capabilities -- r Database modernization and re-engineering -- Data-centric architecture and design r -- r Extremely large database and overcoming limits to growth -- r ISV education and enablement - -## Preface - -This IBM® Redpaper™ publication provides information about the IBM i 7.2 feature of IBM DB2® for i Row and Column Access Control (RCAC). It offers a broad description of the function and advantages of co ntrolling access to data in a comprehensive and transparent way. This publication helps you understand th e capabilities of RCAC an d provides examples of defining, creating, and implementing the row permissions and column masks in a relational database environment. - -This paper is intended for database engineers, data-centric application developers, and security officers who want to design and implement RCAC as a part of their data control and governance policy. A solid background in IB M i object level security, DB2 for i relational database concepts, and SQL is assumed. - -## Authors - -This paper was produced by the IBM DB2 for i Center of Excellence team in partnership with the International Technical Support Organization (ITSO), Rochester, Minnesota US. - - - -Jim Bainbridge is a senior DB2 consultant on the DB2 for i Center of Excellence team in the IBM Lab Services and Training organization. His primary role is training and implementation services for IBM DB2 Web Query for i and business analytics. Jim began his career with IBM 30 years ago in the IBM Rochester Development Lab, where he developed cooperative processing products that paired IBM PCs with IBM S/36 and AS/.400 systems. In the years since, Jim has held numerous technical roles, including independent software vendors technical support on a broad range of IBM technologies and products, and supporting customers in the IBM Executive Briefing Center and IBM Project Office. - - - -Hernando Bedoya is a Senior IT Specialist at STG Lab Services and Training in Rochester, Minnesota. He writes extensively and teaches IBM classes worldwide in all areas of DB2 for i. Before jo ining STG Lab Services, he worked in the ITSO for nine years writing multiple IBM Redbooks® publications. He also worked for IBM Colombia as an IBM AS/400® IT Specialist doing presales support for the Andean countries. He has 28 years of experience in the computing field and has taught database classes in Colombian universities. He holds a Master’s degree in Computer Science from EAFIT, Colombia. His areas of expertise are database technology, performance, and data warehousing. Hernando can be contacted at hbedoya@us.ibm.com . - - - -## 1 - -## Securing and protecting IBM DB2 data - -Recent news headlines are fille d with reports of data breache s and cyber-attacks impacting global businesses of all sizes. The Identity Theft Resource Center 1 reports that almost 5000 data breaches have occurred since 2005, expo sing over 600 million records of data. The financial cost of these data breaches is skyr ocketing. Studies from the Ponemon Institute 2 revealed that the average cost of a data breach increased in 2013 by 15% globally and resulted in a brand equity loss of $9.4 million per attack. The aver age cost that is incurred for each lost record containing sensitive information increased more than 9% to $145 per record. - -Businesses must make a seriou s effort to secure their data and recognize that securing information assets is a cost of doing business. In many parts of the world and in many industries, securing the data is required by law and subject to audits. Data security is no longer an option; it is a requirement. - -This chapter describes how you can secure and protect data in DB2 for i. The following topics are covered in this chapter: - --  Security fundamentals --  Current state of IBM i security --  DB2 for i security controls - -1 http://www.idtheftcenter.org - -2 http://www.ponemon.org / - -## 1.1 Security fundamentals - -Before reviewing database security techniques, there are two fundamental steps in securing information assets that must be described: - --  First, and most important, is the definition of a company's security policy. y. Without a security policy, there is no definition of what are acceptable practices for using, accessing, and storing information by who, what, when, where, and how. A security policy should minimally address three things: confidentiality, integrity, and availability. - -The monitoring and assessment of adherence to the security policy determines whether your security strategy is working. Often, IBM security consultants are asked to perform security assessments for companies without regard to the security policy. Although these assessments can be useful for observing how the system is defined and how data is being accessed, they cannot determine the level of security without a security policy. Without a security policy, it really is no t an assessment as much as it is a baseline for monitoring the changes in the security settings that are captured. - -A security policy is what defines whether the system and its settings are secure (or not). - --  The second fundamental in securing data assets is the use of resource security. y. If implemented properly, resource security prevents data breaches from both internal and external intrusions. Resource security controls are closely tied to the part of the security policy that defines who should have access to what information resources. A hacker might be good enough to get through your company firewalls and sift his way through to your system, but if they do not have explicit access to your database, the hacker cannot compromise your information assets. - -With your eyes now open to the importance of securing information assets, the rest of this chapter reviews the methods that are available for securing database resources on IBM i. - -## 1.2 Current state of IBM i security - -Because of the inherently secure nature of IBM i, many clients rely on the default system settings to protect their business data that is stored in DB2 for i. In most cases, this means no data protection because the default setting for the Create default public authority (QCRTAUT) system value is *CHANGE. - -Even more disturbing is that many IBM i clients remain in this state, despite the news headlines and the significant costs that are involved with databases being compromised. This default security configuration makes it quite challenging to implement basic security policies. A tighter implementation is required if you really want to protect one of your company’s most valuable assets, which is the data. - -Traditionally, IBM i applications have employed menu-based security to counteract this default configuration that gives all users access to the data. The theory is that data is protected by the menu options controlling what database op erations that the user can perform. This approach is ineffective, even if the user profile is restricted from running interactive commands. The reason is that in today's connected world there are a multitude of interfaces into the system, from web browsers to PC clients, that bypass application menus. If there are no object-level controls, users of these newer interfaces have an open door to your data. - -Many businesses are trying to limit data access to a need-to-know basis. This security goal means that users should be given access only to the minimum set of data that is required to perform their job. Often, users with object-lev el access are given access to row and column values that are beyond what their business ta sk requires because that object-level security provides an all-or-nothing solution. For example, object-level controls allow a manager to access data about all employees. Most security policies limit a manager to accessing data only for the employees that they manage. - -## 1.3.1 Existing row and column control - -Some IBM i clients have tried augmenting the all-or-nothing object-level security with SQL views (or logical files) and application lo gic, as shown in Figure 1-2. However, application-based logic is easy to bypass with all of the different data access interfaces that are provided by the IBM i operating system, such as Open Database Connectivity (ODBC) and System i Navigator. - -Using SQL views to limit access to a subset of the data in a table also has its own set of challenges. First, there is the complexity of managing all of the SQL view objects that are used for securing data access. Second, scaling a view-based security solution can be difficult as the amount of data grows and the number of users increases. - -Even if you are willing to live with these perf ormance and management issues, a user with *ALLOBJ access still can directly access all of th e data in the underlying DB2 table and easily bypass the security controls that are built into an SQL view. - - - -Figure 1-2 Existing row and column controls - -## 2.1.6 Change Function Usage CL command - -The following CL commands can be used to work with, display, or change function usage IDs: - --  Work Function Usage ( WRKFCNUSG ) --  Change Function Usage ( CHGFCNUSG ) --  Display Function Usage ( DSPFCNUSG ) - -For example, the following CHGFCNUSG command shows granting authorization to user HBEDOYA to administer and manage RCAC rules: - -CHGFCNUSG FCNID(QIBM_DB_SECADM) USER(HBEDOYA) USAGE(*ALLOWED) - -## 2.1.7 Verifying function usage IDs for RCAC with the FUNCTION_USAGE view - -The FUNCTION_USAGE view contains function usage configuration details. Table 2-1 describes the columns in the FUNCTION_USAGE view. - -Table 2-1 FUNCTION_USAGE view - -| Column name Data type Description | | | | -|---------------------------------------------|-----------|--------------------------------------------------------------|-----------------------------------------| -| FUNCTION_ID VARCHAR(30) ID of the function. | | | | -| USER_NAME VARCHAR(10) Name of the user pr | | | ofile that has a usage setting for this | -| | function. | | | -| USAGE VARCHAR(7) Usage setting: | | | | -| |  | ALLOWED: The user profile is allowed to use the function. | | -| |  | DENIED: The user profile is not allowed to use the function. | | -| USER_TYPE VARCHAR(5) Type of user profile: | | | | -| |  | USER: The user profile is a user. | | -| |  | GROUP: The user profile is a group. | | - -To discover who has authorization to define and manage RCAC, you can use the query that is shown in Example 2-1. - -Example 2-1 Query to determine who has authority to define and manage RCAC - -| SELECT function_id, | | -|------------------------------------|------------| -| | user_name, | -| | usage, | -| | user_type | -| FROM function_usage | | -| WHERE function_id=’QIBM_DB_SECADM’ | | -| ORDER BY user_name; | | - -## 2.2 Separation of duties - -Separation of duties helps businesses comply with industry regulations or organizational requirements and simplifies the management of authorities. Separation of duties is commonly used to prevent fraudulent activities or errors by a single person. It provides the ability for administrative functions to be divided across i ndividuals without overl apping responsibilities, so that one user does not possess unlimited authority, such as with the *ALLOBJ authority. - -For example, assume that a business has assigned the duty to manage security on IBM i to Theresa. Before release IBM i 7.2, to grant privileges, Theresa had to have the same privileges Theresa was granting to others. Therefore, to grant *USE privileges to the PAYROLL table, Theresa had to have *OBJMGT and *USE authority (or a higher level of authority, such as *ALLOBJ). This requirement allowed Theresa to access the data in the PAYROLL table even though Theresa's job description was only to manage its security. - -In IBM i 7.2, the QIBM_DB_SECADM function usage grants authorities, revokes authorities, changes ownership, or changes the primary group without giving access to the object or, in the case of a database table, to the data that is in the table or allowing other operations on the table. - -QIBM_DB_SECADM function usage can be granted only by a user with *SECADM special authority and can be given to a user or a group. - -QIBM_DB_SECADM also is responsible for admi nistering RCAC, which restricts which rows a user is allowed to access in a table and whether a user is allowed to see information in certain columns of a table. - -A preferred practice is that the RCAC administrator has the QIBM_DB_SECADM function usage ID, but absolutely no other data privileges. The result is that the RCAC administrator can deploy and maintain the RCAC constructs, but cannot grant themselves unauthorized access to data itself. - -Table 2-2 shows a comparison of the different function usage IDs and *JOBCTL authority to the different CL commands and DB2 for i tools. - -Table 2-2 Comparison of the different function usage IDs and *JOBCTL authority - -| User action | | | | | | QIBM_DB_SECADM | QIBM_DB_SQLADM | QIBM_DB_SYSMON | | -|-----------------------------------------------------------------------------|------------------------------------------|----------|--------------------------------------------------------|-----------------------------------|---------|------------------|------------------|------------------|--------------| -| | | | | | *JOBCTL | | | | No Authority | -| SET CURRENT DEGREE | | | (SQL statement) | | XX | | | | | -| CHGQRYA | command targeting a different user's job | | | | XX | | | | | -| STRDBMON | or | ENDDBMON | commands targeting a different user's job | | XX | | | | | -| STRDBMON | or | ENDDBMON | commands targeting a job that matches the current user | | X XXX | | | | | -| QUSRJOBI() API format 900 or System | | | | i Navigator's SQL Details for Job | X XX | | | | | -| Visual Explain within Run SQL scripts | | | | | X XXX | | | | | -| Visual Explain outside of Run SQL scripts | | | | | XX | | | | | -| ANALYZE PLAN CACHE procedure | | | | | XX | | | | | -| DUMP PLAN CACHE procedure | | | | | XX | | | | | -| MODIFY PLAN CACHE procedure | | | | | XX | | | | | -| MODIFY PLAN CACHE PROPERTIES procedure (currently does not check authority) | | | | | XX | | | | | -| CHANGE PLAN CACHE SIZE procedure (currently does not check authority) | | | | | XX | | | | | - -The SQL CREATE PERMISSION statement that is shown in Figure 3-1 is used to define and initially enable or disable the row access rules. - - - -Figure 3-1 CREATE PER ERMISSION SQL statement - -## Column mask - -A column mask is a database object that manifests a column value access control rule for a specific column in a specific table. It uses a CASE expression that describes what you see when you access the column. For example, a teller can see only the last four digits of a tax identification number. - -Table 3-1 summarizes these special registers and their values. - -Table 3-1 Special registers and their corresponding values - -| Special register Co | | rresponding value | | | | -|-----------------------------------------------|--------------------------------------------------------|---------------------|----------------|-----------------------------------|----------------------------------------------| -| USER or | The effective user of the th | | | read excluding adopted authority. | | -| SESSION_USER | | | | | | -| CURRENT_USER The effective user of the thread | | | | | including adopted authority. When no adopted | -| | authority is present, this has the same value as USER. | | | | | -| SYSTEM_USER The authorization ID | | | that initiated | | the connection. | - -Figure 3-5 shows the difference in the special register values when an adopted authority is used: - --  A user connects to the server using the user profile ALICE. --  USER and CURRENT USER initially have the same value of ALICE. -- ALICE calls an SQL procedure that is named proc1, which is owned by user profile JOE  and was created to adopt JOE's authority when it is called. --  While the procedure is running, the special register USER still contains the value of ALICE because it excludes any adopted authority. The special register CURRENT USER contains the value of JOE because it includes any adopted authority. -- When proc1 ends, the session reverts to its original state with both USER and CURRENT  USER having the value of ALICE. - - - -Figure 3-5 Special registers and adopted authority - -## 3.2.2 Built-in global variables - -Built-in global variables are provided with the database manager and are used in SQL statements to retrieve scalar values that are associated with the variables. - -IBM DB2 for i supports nine different built-in global variables that are read only and maintained by the system. These global variables can be used to identify attributes of the database connection and used as part of the RCAC logic. - -Table 3-2 lists the nine built-in global variables. - -Table 3-2 Built-in global variables - -| Global variable Type Description | | | | | -|------------------------------------------------------------------------------------|----------------------------------|---------------------------------------|------------------------------------------|---------------------------| -| CLIENT_HOST VARCHAR(255) Host | name of the current client | | | as returned by the system | -| CLIENT_IPADDR VARCHAR(128) IP address of the | | | current client as returned by the system | | -| CLIENT_PORT INTEGER Port used by the current client to communicate with the server | | | | | -| PACKAGE_NAME VARCHAR(128) Name of the currently running package | | | | | -| PACKAGE_SCHEMA VARCHAR(128) Schema name of the currently running package | | | | | -| PACKAGE_VERSION VARCHAR(64) Version identi | | fier of the currently running package | | | -| ROUTINE_SCHEMA VARCHAR(128) Schema name of the currently running routine | | | | | -| ROUTINE_SPECIFIC_NAME VARCHAR(128) Name | of the currently running routine | | | | -| ROUTINE_TYPE CHAR(1) Type of the currently running routine | | | | | - -## 3.3 VERIFY_GROUP_FOR_USER function - -The VERIFY_GROUP_FOR_USER function was added in IBM i 7.2. Although it is primarily intended for use with RCAC permissions and masks, it can be used in other SQL statements. The first parameter must be one of these th ree special registers: SESSION_USER, USER, or CURRENT_USER. The second and subsequent parameters are a list of user or group profiles. Each of these values must be 1 - 10 characters in length. These values are not validated for their existence, which means that you can specify the names of user profiles that do not exist without receiving any kind of error. - -If a special register value is in the list of user profiles or it is a member of a group profile included in the list, the function returns a long integer value of 1. Otherwise, it returns a value of 0. It never returns the null value. - -Here is an example of using th e VERIFY_GROUP_FOR_USER function: - -- 1. There are user profiles for MGR, JANE, JUDY, and TONY. -- 2. The user profile JANE specifies a group profile of MGR. -- 3. If a user is connected to the server using user profile JANE, all of the following function invocations return a value of 1: - -VERIFY_GROUP_FOR_USER (CURRENT_USER, 'MGR') VERIFY_GROUP_FOR_USER (CURRENT_USER, 'JANE', 'MGR') VERIFY_GROUP_FOR_USER (CURRENT_USER, 'JANE', 'MGR', 'STEVE') - -The following function invocation returns a value of 0: - -VERIFY_GROUP_FOR_USER (CURRENT_USER, 'JUDY', 'TONY') - -RETURN CASE WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'HR', 'EMP' ) = 1 THEN EMPLOYEES . DATE_OF_BIRTH WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'MGR' ) = 1 AND SESSION_USER = EMPLOYEES . USER_ID THEN EMPLOYEES . DATE_OF_BIRTH WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'MGR' ) = 1 AND SESSION_USER <> EMPLOYEES . USER_ID THEN ( 9999 || '-' || MONTH ( EMPLOYEES . DATE_OF_BIRTH ) || '-' || DAY (EMPLOYEES.DATE_OF_BIRTH )) ELSE NULL END ENABLE ; - -- 2. The other column to mask in this example is the TAX_ID information. In this example, the rules to enforce include the following ones: -- – Human Resources can see the unmasked TAX_ID of the employees. -- – Employees can see only their own unmasked TAX_ID. -- – Managers see a masked version of TAX_ID with the first five characters replaced with the X character (for example, XXX-XX-1234). -- TAX_ID as masked, for example, XXX-XX-XXXX. – Any other person sees the entire TA - -To implement this column mask, run the SQL statement that is shown in Example 3-9. - -Example 3-9 Creating a mask on the TAX_ID column - -CREATE MASK HR_SCHEMA.MASK_TAX_ID_ON_EMPLOYEES ON HR_SCHEMA.EMPLOYEES AS EMPLOYEES FOR COLUMN TAX_ID RETURN CASE WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'HR' ) = 1 THEN EMPLOYEES . TAX_ID WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'MGR' ) = 1 AND SESSION_USER = EMPLOYEES . USER_ID THEN EMPLOYEES . TAX_ID WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'MGR' ) = 1 AND SESSION_USER <> EMPLOYEES . USER_ID THEN ( 'XXX-XX-' CONCAT QSYS2 . SUBSTR ( EMPLOYEES . TAX_ID , 8 , 4 ) ) WHEN VERIFY_GROUP_FOR_USER ( SESSION_USER , 'EMP' ) = 1 THEN EMPLOYEES . TAX_ID ELSE 'XXX-XX-XXXX' END ENABLE ; - -- 3. Figure 3-10 shows the masks that are created in the HR_SCHEMA. - - - -Figure 3-10 Column masks shown in System i Navigator - -## 3.6.6 Activating RCAC - -Now that you have created the row permission and the two column masks, RCAC must be activated. The row permission and the two column masks are enabled (last clause in the scripts), but now you must activate RCAC on the table. To do so, complete the following steps: - -- 1. Run the SQL statements that are shown in Example 3-10. - -Example 3-10 Activating RCAC on the EMPLOYEES table - - - -- 2. Look at the definitio n of the EMPLOYEE table, as shown in Figure 3-11. To do this, from the main navigation pane of System i Navigator, click Schemas  HR_SCHEMA  Tables , right-click the EMPLOYEES table, and click Definition . - - - -Figure 3-11 Selecting the EMPL OYEES table from System i Navigator - -- 2. Figure 4-68 shows the Visual Explain of the same SQL statement, but with RCAC enabled. It is clear that the implementation of the SQL statement is more complex because the row permission rule becomes part of the WHERE clause. - - - -Figure 4-68 Visual Explain with RCAC enabled - -- 3. Compare the advised indexes that are provided by the Optimizer without RCAC and with RCAC enabled. Figure 4-69 shows the index advice for the SQL statement without RCAC enabled. The index being advised is for the ORDER BY clause. - - - -Figure 4-69 Index advice with no RCAC - -THEN C . CUSTOMER_TAX_ID WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'TELLER' ) = 1 THEN ( 'XXX-XX-' CONCAT QSYS2 . SUBSTR ( C . CUSTOMER_TAX_ID , 8 , 4 ) ) WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'CUSTOMER' ) = 1 THEN C . CUSTOMER_TAX_ID ELSE 'XXX-XX-XXXX' END ENABLE ; CREATE MASK BANK_SCHEMA.MASK_DRIVERS_LICENSE_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C FOR COLUMN CUSTOMER_DRIVERS_LICENSE_NUMBER RETURN CASE WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'ADMIN' ) = 1 THEN C . CUSTOMER_DRIVERS_LICENSE_NUMBER WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'TELLER' ) = 1 THEN C . CUSTOMER_DRIVERS_LICENSE_NUMBER WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'CUSTOMER' ) = 1 THEN C . CUSTOMER_DRIVERS_LICENSE_NUMBER ELSE '*************' END ENABLE ; CREATE MASK BANK_SCHEMA.MASK_LOGIN_ID_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C FOR COLUMN CUSTOMER_LOGIN_ID RETURN CASE WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'ADMIN' ) = 1 THEN C . CUSTOMER_LOGIN_ID WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'CUSTOMER' ) = 1 THEN C . CUSTOMER_LOGIN_ID ELSE '*****' END ENABLE ; CREATE MASK BANK_SCHEMA.MASK_SECURITY_QUESTION_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C FOR COLUMN CUSTOMER_SECURITY_QUESTION RETURN CASE WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'ADMIN' ) = 1 THEN C . CUSTOMER_SECURITY_QUESTION WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'CUSTOMER' ) = 1 THEN C . CUSTOMER_SECURITY_QUESTION ELSE '*****' END ENABLE ; CREATE MASK BANK_SCHEMA.MASK_SECURITY_QUESTION_ANSWER_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C FOR COLUMN CUSTOMER_SECURITY_QUESTION_ANSWER RETURN CASE WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'ADMIN' ) = 1 THEN C . CUSTOMER_SECURITY_QUESTION_ANSWER WHEN QSYS2 . VERIFY_GROUP_FOR_USER ( SESSION_USER , 'CUSTOMER' ) = 1 THEN C . CUSTOMER_SECURITY_QUESTION_ANSWER ELSE '*****' END ENABLE ; ALTER TABLE BANK_SCHEMA.CUSTOMERS ACTIVATE ROW ACCESS CONTROL ACTIVATE COLUMN ACCESS CONTROL ; - -# Row and Column Access Control Support in IBM DB2 for i - -Implement roles and separation of duties - -This IBM Redpaper publication provid es information about the IBM i 7.2 feature of IBM DB2 for i Row and Column Access Control (RCAC). It offers a broad description of the function and advantages of controlling access to data in a comprehensive and transparent way. This publication helps you understand the capabilities of RCAC and provides examples of defining, creating, and implementing the row permissions and column masks in a relational database environment. - -Leverage row permissions on the database - -This paper is intended for database engineers, data-centric application developers, and security officers who want to design and implement RCAC as a part of their data control and governance policy. A solid background in IBM i object level security, DB2 for i relational database concepts, and SQL is assumed. - -Protect columns by defining column masks - - - - - -INTERNATIONAL TECHNICAL SUPPORT ORGANIZATION - -## BUILDING TECHNICAL INFORMATION BASED ON PRACTICAL EXPERIENCE - -IBM Redbooks are developed by the IBM International Technical Support Organization. Experts from IBM, Customers and Partners from around the world create timely technical information based on realistic scenarios. Specific recommendations are provided to help you implement IT solutions more effectively in your environment. - -For more information: ibm.com /redbooks diff --git a/tests/pdf_snapshots/pdf/sources/right_to_left_01.pdf.md b/tests/pdf_snapshots/pdf/sources/right_to_left_01.pdf.md deleted file mode 100644 index ccf6c7c4..00000000 --- a/tests/pdf_snapshots/pdf/sources/right_to_left_01.pdf.md +++ /dev/null @@ -1,3 +0,0 @@ -## تحسين اإلنتاجية وحل المشكالت من خالل البرمجة بلغة Python و ة R - -من األدوات القوية التي يمكن أن تعزز اإلنتاجية وتساعد في إيجاد حلول فعالة Python و ة R تعتبر البرمجة بلغة ميزات فريدة تجعلها مثالية لتحليل البيانات، مما يسهل على المحللين والعلماء Python و R للمشكالت. يمتلك كل من لديك عقلية تحليلية، فإن استخدام هذه اللغات يمكن أن يسهم إجراء تحليالت معقدة بطريقة سريعة وفعالة. إذا كان بشكل كبير في تحسين نتائج العمل . عندما يجتمع التفكير التحليلي مع مهارات البرمجة، يصبح من الممكن معالجة كميات هائلة من البيانات واستخراج عمليات تحليلية متقدمة، مثل النمذجة لتنفيذ Python و R األنماط والتوجهات منها. يمكن للمبرمجين استخدام قة قة د ثر كثر كث أ ت ا ر ا قر قر ذ خا تخا تخ ا لى إ ضا ي ًضا ًض ي ض أ ي د يؤ يؤ ن أ كن مكن يمك يم بل بل ، قت قت لو لو ا فر فر يو يو قط فقط فق يس ليس لي ا هذ هذ ة ير بير كبي لكب لك ا ت نا نا يا بيا لبي لب ا يل ليل حلي تحل تح و ية ئية ئي صا حصا حص إل ا لى ت نا نا يا . بيا لبي لب ا على عل مة ئمة ئم قا قا ت جا جا تا نتا تنت ستن ست ا على عل ء ً نا بنا بن . لى لى من التطبيقات، من التحليل مكتبات وأدوات غنية تدعم مجموعة واسعة من Python R عالوة على ذلك، توفر كل من البياني إلى التعلم اآللي. يمكن للمستخدمين االستفادة من هذه المكتبات لتطوير حلول مبتكرة للمشكالت المختلفة. على و أدوات قوية للرسم R إلدارة البيانات بكفاءة، بينما توفر Python في ة pandas سبيل المثال، يمكن استخدام مكتبة حصائي، مما يجعلها مثالية للباحثين والمحللين البياني والتحليل اإل . مع عقلية تحليلية إلى تحسين اإلنتاجية وتوفير حلول مبتكرة في النهاية، يمكن أن تؤدي البرمجة بلغة للمشكالت المعقدة. إن القدرة على تحليل البيانات بشكل فعال وتطبيق األساليب البرمجية المناسبة يمكن أن تكون لها Python و ة R ها تأثيرات إيجابية بعيدة المدى على األداء الشخصي والمهني diff --git a/tests/pdf_snapshots/pdf/sources/right_to_left_02.pdf.md b/tests/pdf_snapshots/pdf/sources/right_to_left_02.pdf.md deleted file mode 100644 index c9b548e4..00000000 --- a/tests/pdf_snapshots/pdf/sources/right_to_left_02.pdf.md +++ /dev/null @@ -1,9 +0,0 @@ - - -فإن الحكومة المصرية تضع صوو عييهاوخ لوال المر اوة الم ب باوة وعليه، هودا تكايف السيد رئيس الجماورية لاخ بخلعمل ياى تح يق يدد من األ وخت، وضع ماف بهخء اإلنسخن المصري ياى رعس قخئموة األولويوخ ياى رعساخ : لخصوة فووا مجوخحت الصووحة واللعاوويل، العمول ياووى تح يوق معوودحت نمووو قويوووة ومسووولدامة و وووخماة فوووا عذاوووف ال لخيوووخت، و ووو ا الح وووخ ياوووى وة، محوددات األمون ال ووما المصوري فوا ضووء اللحوديخت اإلقايميوة والدوليوة وخت ومواصواة واوود تلووير الماوخر ة السيخسوية، واسولمرار ملخبعوة ما وخ األمووون واحسووول رار ومكخفحوووة اإلرهوووخ ، تلووووير ما وووخت ال خفوووة والوووويا الوووو،ها، والبلوووخ الوووديها المعلووودل ياوووى الهحوووو الووو ي يرسووو م وووخهيل الموا،هة والسام المجلمعا . - -- 2024 ) ووف ًخ لمخ سبق، يسولاد برنوخما الحكوموة المصورية لوال ال لور : تح يق عربعة عهدا اسلراتيجية رئيسة، وها ياى الهحو اآلتا ( 2026 - -قرار تحقيق اظستقر مايــــــــة اممــــــــن بنـــــاء ا تصـــــاع بنـــاء ا نســـا السياســــــــــــــــــــــــي القومي المصـر تنابســــــــــــــــــــــي المصـــــــــــــــــــر - -د باوكل تجدر اإل خر إلى عنه قد تل تحديد مسولادفخت البرنوخما بخحسولهخ وتوصووويخت واسوووخت الحووووار ، 2023 رئووويس ياوووى مسووولادفخت ر يوووة مصووور كايوة، الوو،ها، ومسولادفخت الوو ارات، والبرنوخما الوو،ها ليصوا خت الايكا ومبلاف احسلراتيجيخت الو،هية . diff --git a/tests/pdf_snapshots/pdf/sources/right_to_left_03.pdf.md b/tests/pdf_snapshots/pdf/sources/right_to_left_03.pdf.md deleted file mode 100644 index 6d9275d4..00000000 --- a/tests/pdf_snapshots/pdf/sources/right_to_left_03.pdf.md +++ /dev/null @@ -1,23 +0,0 @@ -## داخلی ی کاال - نامه پذيرش در بازار اصلی اميد - -| | | | 1403 | / 09 | / 19 | | | | | | | | تاريخ ارائه مدارک | | | -|----|-------------------------|---------------------|--------|--------------|--------|-----|---------|------|------------------------------------------|--------|----|----------------------------|---------------------|--------------|-------| -| | | | 1403 | / 10 | / 04 | | | | | | | | | تاريخ پذيرش | | -| | | | | 436 | | | | | | | | کميته عرضه | | شماره جلسه ک | | -| | | | 1403 | / 10 | / 05 | | | | | | | | تاريخ درج اميدنامه | | | -| | | بورس | رمون ب | آ کارگزاری آ | | | | | | | | | | مشاور پذيرش | | -| | جهانی | | های | اساس قيمت | | بر | | | نحوة تعيين قيمت پايه پس از پذيرش کاال در | | | | | | | -| | | | | | | | | | | | | | | | بورس | -| تن | 4 7.500 | از توليد ساليانه يا | | | | % 5 | 0 حداقل | فروش | | / فروش | کل | / حداقل درصد عرضه از توليد | | | | -| | | | | | | | | | | | | | | | داخلی | -| | آخرين محموله قابل تحويل | | | | | | 5 % | | | | | | خطای مجاز تحويل | | | - - - - - -## شرکت بورس کاالی ايران - -## کاال استاندارد کا - 2 - 5 - -## پذيرش در بورس - 3 diff --git a/tests/pdf_snapshots/pdf/sources/skipped_1page.pdf.md b/tests/pdf_snapshots/pdf/sources/skipped_1page.pdf.md deleted file mode 100644 index 381e8b76..00000000 --- a/tests/pdf_snapshots/pdf/sources/skipped_1page.pdf.md +++ /dev/null @@ -1,72 +0,0 @@ -- 보안분 안분 - - - - - - - - - - - -## 스마트 데이터 컪비스 훟심 컴퓨팅 보안 기술 - - - - - - - - - -엣지컴퓨팅 (Edge Computing) - -차세대 AI (Next AI) - -(DATA) - - - - - - - - - - - -차세대 AI (Next AI) - - - -## 젊기몒 인터페이스 몋에컪픦 캏오윦이캏맞지 기술 - - - - - - - -웨어러블 컨트롤 인터페이스 - -데이터 (DATA) - -(Wearable Control ) Interfaces) - -## [그림 4-5] 8대 미래 유망 보안기술 도출 - - - -묾푷 차세대 비체(1A7)킹 방지읊 퓒 칺몮 대픟 기술 - -(Hyper-Connected k) yp Networking) - -(DATA) - -(4D Printing) - -ICT 기술변화에 따른 미래 보안기술 전망 보고서 84 - -- - AI 기술을 활용해 오탐율을 줄이고, 빠른 분석 탐지를 넘어 자동적인 격리까지 제공하는 방향으로 진화 -- - 각종 사이버위협에 대한 하나의 기법 또는 알고리즘이 아닌, 침해 대응의 각 요소별로 최적화된 알고리즘과 기법, 이전에 설명한 학습 방법을 지원하고 이를 통합할 수 있는 기술 필요 diff --git a/tests/pdf_snapshots/pdf/sources/skipped_2pages.pdf.md b/tests/pdf_snapshots/pdf/sources/skipped_2pages.pdf.md deleted file mode 100644 index 129c9d27..00000000 --- a/tests/pdf_snapshots/pdf/sources/skipped_2pages.pdf.md +++ /dev/null @@ -1,78 +0,0 @@ -- 보안분 안분 - - - - - -## [그림 4-3] 미래 보안기술 도출 과정 - - - - - - - - - - - -## 스마트 데이터 컪비스 훟심 컴퓨팅 보안 기술 - - - - - - - - - -엣지컴퓨팅 (Edge Computing) - -차세대 AI (Next AI) - -(DATA) - - - - - - - - - - - -차세대 AI (Next AI) - - - -## 젊기몒 인터페이스 몋에컪픦 캏오윦이캏맞지 기술 - - - - - - - -웨어러블 컨트롤 인터페이스 - -데이터 (DATA) - -(Wearable Control ) Interfaces) - -## [그림 4-5] 8대 미래 유망 보안기술 도출 - - - -묾푷 차세대 비체(1A7)킹 방지읊 퓒 칺몮 대픟 기술 - -(Hyper-Connected k) yp Networking) - -(DATA) - -(4D Printing) - -ICT 기술변화에 따른 미래 보안기술 전망 보고서 84 - -- - AI 기술을 활용해 오탐율을 줄이고, 빠른 분석 탐지를 넘어 자동적인 격리까지 제공하는 방향으로 진화 -- - 각종 사이버위협에 대한 하나의 기법 또는 알고리즘이 아닌, 침해 대응의 각 요소별로 최적화된 알고리즘과 기법, 이전에 설명한 학습 방법을 지원하고 이를 통합할 수 있는 기술 필요 diff --git a/tests/pdf_snapshots/pdf/sources/table_mislabeled_as_picture.pdf.md b/tests/pdf_snapshots/pdf/sources/table_mislabeled_as_picture.pdf.md deleted file mode 100644 index b2f3b250..00000000 --- a/tests/pdf_snapshots/pdf/sources/table_mislabeled_as_picture.pdf.md +++ /dev/null @@ -1,99 +0,0 @@ -| „ | They work in parallel to State funded private practitioners who take assignments to | | | | -|-----|---------------------------------------------------------------------------------------|------------------|-------------------------------------------------------|----| -| | represent people eligible for legal aid | | | | -| „ | They coordinate appointments of private practitioners (ex officio, or panel appoint | | | | -| | | | |  | -| | ments) to legal aid cases | | | | -| „ | They supervise, coach or mentor private practitioners who take legal aid cases | | | | -| „ | They conduct or organize training sessions for staff lawyers/paralegals | | | | -| „ | They conduct or organize training sessions for all providers of legal aid, including | | | | -| | both staff and private lawyers/paralegals | | | | -| „ | Other | (Please specify) | | | -| | | | _____________________________________________________ | | -| „ | Not applicable, there is no institutional legal aid provider | | | | - -- „ They work in parallel to State funded private practitioners who take assignments to represent people eligible for legal aid -- „ They coordinate appointments of private practitioners (ex officio, or panel appoint  ments) to legal aid cases -- „ They supervise, coach or mentor private practitioners who take legal aid cases -- „ They conduct or organize training sessions for staff lawyers/paralegals -- „ They conduct or organize training sessions for all providers of legal aid, including both staff and private lawyers/paralegals -- „ Other (Please specify) _____________________________________________________ -- „ Not applicable, there is no institutional legal aid provider -- 23. If your country has an institutional legal aid provider (e.g. public defender), what is the maximum caseload per lawyer at one time? - -| 23. | If your country has an institutional legal aid provider (e.g. public defender), what is | | | -|-------|-------------------------------------------------------------------------------------------|-----------------------------|----------------------------------| -| | the maximum caseload per lawyer at one time? | | | -| | | | at the national (federal) level | -| | _______ | | | -| | | | at the regional (district) level | -| | _______ | | | -| | | | at the local (municipal) level | -| | _______ | | | -| | „ | There is no such limitation | | - -- at the national (federal) level _______ -- at the regional (district) level _______ -- at the local (municipal) level _______ -- „ There is no such limitation -- 24. If your country has an institutional legal aid provider (e.g. public defender), do the staff lawyers coordinate to uniformly challenge common violations of national and international due process rights and human rights? -- „ Yes, at the national (federal) level -- „ Yes, at regional (district) level -- „ Yes, at the local (municipal) level -- „ No - -| 25. | If your country has an institutional legal aid provider (e.g. public defender), does it | | | -|-------|-------------------------------------------------------------------------------------------|--------------------------------------|----| -| | have specialized providers and/or units for representing child victims, child witness | |  | -| | es or suspected and accused children? | | | -| | „ | Yes, at the national (federal) level | | -| | „ | Yes, at regional (district) level | | -| | „ | Yes, at the local (municipal) level | | -| | „ | No | | - -- 25. If your country has an institutional legal aid provider (e.g. public defender), does it have specialized providers and/or units for representing child victims, child witness  es or suspected and accused children? -- „ Yes, at the national (federal) level -- Yes, at regional (district) level -- „ Yes, at the local (municipal) level -- 26. If your country allows legal aid services through university-based student law clinics, are there national guidelines on how students are supervised in providing legal aid services? (Please select all that apply) -- „ Yes, there are specific guidelines for non-lawyers providing legal aid services -- „ Yes, there are specific guidelines on faculty/student ratios -- „ No, it is up to the discretion of each university -- „ Don’t know -- „ There are no university-based student law clinics - -| 27. | If your country allows legal aid services through university-based student law clinics, | | | | | -|-------|-------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|------------------|-------------------------------------------------------|----| -| | what type of legal aid services is a student authorized to undertake? | | | | | -| | (Please select all that apply) | | | | | -| | „ | There is no limitation; they have the same authority as lawyers | | | | -| | „ | They can represent people in administrative or civil law hearings | | | | -| | „ | They can provide primary legal aid (legal advice) | | | | -| | „ | They can prepare legal documents | | | | -| | „ | They can represent people in court in civil and criminal matters | | | | -| | „ | They have the same authority as lawyers in criminal cases of low to mid gravity | | | | -| | „ | They can provide a full range of legal services in criminal cases regardless of gravity | | | | -| | „ | They can conduct mediation | | | | -| | „ | They are authorized to provide only those services that a faculty member or practic | | | | -| | | | | |  | -| | | ing lawyer supervises | | | | -| | „ | Don’t know | | | | -| | „ | Other | (Please specify) | | | -| | | | | _____________________________________________________ | | - -- 27. If your country allows legal aid services through university-based student law clinics, what type of legal aid services is a student authorized to undertake? (Please select all that apply) -- „ They can represent people in administrative or civil law hearings -- 28. Are specialized legal aid services provided focusing on specific disadvantaged popu  lation groups? If yes, please indicate to whom these services are provided, and whether they are provided by State-funded legal aid, civil society organizations, or both. - -(Please select all that apply) - -| | | State funded | | CSOs | -|----|------------------------------------------------|----------------|----|--------| -| | | legal aid | | | -| y | Persons with disabilities | | * | * | -| y | Children | | * | * | -| y | Women | | * | * | -| y | The elderly | | * | * | -| y | Migrants | | * | * | -| y | Refugees, asylum seekers, or stateless persons | | * | * | -| y | Internally displaced persons | | * | * | diff --git a/tests/pdf_snapshots/scanned/sources/nemotron_multipage.pdf.md b/tests/pdf_snapshots/scanned/sources/nemotron_multipage.pdf.md deleted file mode 100644 index 4f5a0595..00000000 --- a/tests/pdf_snapshots/scanned/sources/nemotron_multipage.pdf.md +++ /dev/null @@ -1,9 +0,0 @@ -Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package - -aeroseaeoe e o ona - -H W ep ps ws e. uu P po - -te oda nn na sm 88 ek da sdo bd p0 M - -e 60 a K C a p diff --git a/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_180.pdf.md b/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_180.pdf.md deleted file mode 100644 index f6184e5e..00000000 --- a/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_180.pdf.md +++ /dev/null @@ -1 +0,0 @@ -aeroseaeoe e o ona diff --git a/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_270.pdf.md b/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_270.pdf.md deleted file mode 100644 index 9ad4b33e..00000000 --- a/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_270.pdf.md +++ /dev/null @@ -1 +0,0 @@ -H W ep ps ws e. uu P po diff --git a/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_90.pdf.md b/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_90.pdf.md deleted file mode 100644 index ba425e59..00000000 --- a/tests/pdf_snapshots/scanned/sources/ocr_test_rotated_90.pdf.md +++ /dev/null @@ -1,3 +0,0 @@ -te oda nn na sm 88 ek da sdo bd p0 M - -e 60 a K C a p diff --git a/tests/pdf_snapshots/scanned/sources/sample_with_rotation_mismatch.pdf.md b/tests/pdf_snapshots/scanned/sources/sample_with_rotation_mismatch.pdf.md deleted file mode 100644 index 43218e15..00000000 --- a/tests/pdf_snapshots/scanned/sources/sample_with_rotation_mismatch.pdf.md +++ /dev/null @@ -1,33 +0,0 @@ - - -## THE SLEREXE COMPANY LIMITED - -SAPORSLANE-BOOLE-DORSET-BH258ER SAPORSLANE-BOOLE-DORSET-BH258ER - -SAPORSLANE-BOOLE-DORSET-BH258ER SAPORSLANE-BOOLE-DORSET-BH258ER TELEPHONEB0OLB(94513)51617-TELEX123456 TELEPHONEB0OLE(94513)51617-TELEX123456 - -TELEPHONEB0OLB(94513)51617-TELEX123456 TELEPHONEB0OLE(94513)51617-TELEX123456 - -18th January,1972. - -OurRef.35O/PJC/EAC - - - -Dr. P.N. Cundall, Mining Surveys Ltd., Holroyd Road, Reading, Berks. - -Dear Pete, - -Permit me to introduce you to the faciiity of facsimile transmlsslon. - -In facsimile a photocell is caused to perform a raster scan over the subject copy. The variations of print density on the document cause the photocell to generate an analogous electrical video signal. This signal is used to modulate a carrier, which is transmitted to a remote destinationover aradio or cablecommunicationslink. - -At the remote terminal, demodulation reconstructs the video signal, which is used to modulate the density of print produced by a printing device. This device is scanning in a raster scan synchronised with that at the transmitting terminal. As a result, a facsimile copy of the subject document is produced. - -Probably you have uses for this facility in your organisation. - -Yours sincerely, - - - -P.J.CROSS Group Leader - Facsimile Research diff --git a/tests/pdf_snapshots/tiff/sources/2206.01062.tif.md b/tests/pdf_snapshots/tiff/sources/2206.01062.tif.md deleted file mode 100644 index 2294745d..00000000 --- a/tests/pdf_snapshots/tiff/sources/2206.01062.tif.md +++ /dev/null @@ -1,47 +0,0 @@ -Birgit Pfitzmann BMResearch RueschllkonSwitzerland bpf@zurich.ibm.com - -AhmedS.Nassar IBMResearch Rueschlikon, Switzerland ahn@zurich.ibm.com - -## ABSTRACT - -Accurate document layout analysis is a key requirement for high- quality PDF document conversion. With the recent availability od public, large ground-truth datasets such as PubLayNet and DocBank deep-learning models have proven to be very effective at layouf detection and segmentation. While these datasets are of adequate size to train such models, they severely lack in layout variability since they are sourced from scientific article repositories such as PubMed and arXiv only. Consequently, the accuracy of the layout segmentation drops significantly when these models are applied on more challenging and diverse layouts. In this paper, we present DocLayNet, a new, publicly available, document-layout annotation dataset in COco format. It contains Soss3 manually annotated pages from diverse data sources to represent a wide variability in layouts. For each PDF page, the layout annotations provide labelled bounding-boxes with a choice of 11 distinct classes. DocLayNef also provides a subset of double- and triple-annotated pages to determine the inter-annotator agreement. In multiple experiments, we provide baseline accuracy scores (in mAP) for a set of popular object detection models. We also demonstrate that these models fall approximately 10% behind the inter-annotator agreement. Fur- thermore, we provide evidence that DocLayNet is of sufficient size Lastly, we compare models trained on PubLayNet, DocBank and DocLayNet, showing that layout predictions of the DocLayNet- trained models are more robust and thus the preferred choice for general-purpose document-layout analysis - -## CCS CONCEPTS - --Informationsystems→Documentstructure;Appliedcom- puting → Document analysis, - Computing methodologies → Machine learning Computer vision; Object detection - -Peemissiom to make digital or hard copies of part er all of this woek foe personal or classuoom use Is granted without fee prowided that copies are not made or distrnutee tor protit oe commercial advantage and that oopies bear this notice and the tull citation on the tirst page. Copyrights foe thind-party oemponents of this work mist be honored Foraocherusescomtacttheowre/authors - -KDD 22 Aueaat 24, 2022, Washimgton, DC USA - -2122 Copyrirht held by the auner/autheefs) - -7@01.8r/10.1145/35346783539043 - -# DocLayNet:ALarge Human-Annotated Datasetfor Document-LayoutAnalysis - -Michele Dolfi IBMResearch Rueschlikon, Switzerland dol@zurich.ibm.com - -Christoph Auer BMResearch Rueschlikon, Switzerland cau@zurich.ibmcom - -PeterStaar IBMResearch Rueschlikon,Switzerland taa@zurich.ibm.com - - - - - - - - - - - -Figure 1: Four examples of complex page layouts across dif ferent document categories - -## KEYWORDS - -PDF document conversion, layout segmentation, object-detection, data set, Machine Learning - -## ACMRefereneeFormat: - -Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar. 2022. DocLayNet: A Large Human-Annotated Dataset for Documen Layout Analysis. In Proceedings of the 28th ACAd SIGKDD Conference on Ksowledge Discovery &td Date Adining (KDD 'z2), Augast J41&, 2022, wasi ingtow, DC, U/SA. ACM, New York, NY, USA, 9 pages. https://doi.org/10.1145/ 353467.3539043 diff --git a/tests/snapshots/html/sources/example_image_01.png.md b/tests/snapshots/html/sources/example_image_01.png.md new file mode 100644 index 00000000..6d585350 --- /dev/null +++ b/tests/snapshots/html/sources/example_image_01.png.md @@ -0,0 +1,15 @@ + + + + + + + + +docling + + + +Dog + +Your GenAl App diff --git a/tests/pdf_snapshots/latex/sources/1706.03762/vis/anaphora_resolution2_new.pdf.md b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-19.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/1706.03762/vis/anaphora_resolution2_new.pdf.md rename to tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-19.png.md diff --git a/tests/pdf_snapshots/latex/sources/2305.03393/figs/HTMLvOTSLv7.pdf.md b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-20.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2305.03393/figs/HTMLvOTSLv7.pdf.md rename to tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-20.png.md diff --git a/tests/pdf_snapshots/latex/sources/2305.03393/figs/html_v_otsl_intro_v2.pdf.md b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-21.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2305.03393/figs/html_v_otsl_intro_v2.pdf.md rename to tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-21.png.md diff --git a/tests/pdf_snapshots/latex/sources/2305.03393/figs/otsl_proof_v3.pdf.md b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-22.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2305.03393/figs/otsl_proof_v3.pdf.md rename to tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-22.png.md diff --git a/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-23.png.md b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-23.png.md new file mode 100644 index 00000000..a5c46048 --- /dev/null +++ b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-23.png.md @@ -0,0 +1,11 @@ + + +## Linear + +ReLU + +不 + +Linear + + diff --git a/tests/pdf_snapshots/latex/sources/2305.03393/figs/otsl_vs_html_ex3_v2.pdf.md b/tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-32.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2305.03393/figs/otsl_vs_html_ex3_v2.pdf.md rename to tests/snapshots/latex/sources/1706.03762/Figures/ModalNet-32.png.md diff --git a/tests/pdf_snapshots/latex/sources/2305.03393/figs/tablemodel_overview_otsl.pdf.md b/tests/snapshots/latex/sources/1706.03762/vis/anaphora_resolution2_new.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2305.03393/figs/tablemodel_overview_otsl.pdf.md rename to tests/snapshots/latex/sources/1706.03762/vis/anaphora_resolution2_new.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/1706.03762/vis/anaphora_resolution_new.pdf.md b/tests/snapshots/latex/sources/1706.03762/vis/anaphora_resolution_new.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/1706.03762/vis/anaphora_resolution_new.pdf.md rename to tests/snapshots/latex/sources/1706.03762/vis/anaphora_resolution_new.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/1706.03762/vis/attending_to_head2_new.pdf.md b/tests/snapshots/latex/sources/1706.03762/vis/attending_to_head2_new.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/1706.03762/vis/attending_to_head2_new.pdf.md rename to tests/snapshots/latex/sources/1706.03762/vis/attending_to_head2_new.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/1706.03762/vis/attending_to_head_new.pdf.md b/tests/snapshots/latex/sources/1706.03762/vis/attending_to_head_new.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/1706.03762/vis/attending_to_head_new.pdf.md rename to tests/snapshots/latex/sources/1706.03762/vis/attending_to_head_new.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/1706.03762/vis/making_more_difficult5_new.pdf.md b/tests/snapshots/latex/sources/1706.03762/vis/making_more_difficult5_new.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/1706.03762/vis/making_more_difficult5_new.pdf.md rename to tests/snapshots/latex/sources/1706.03762/vis/making_more_difficult5_new.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/1706.03762/vis/making_more_difficult_new.pdf.md b/tests/snapshots/latex/sources/1706.03762/vis/making_more_difficult_new.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/1706.03762/vis/making_more_difficult_new.pdf.md rename to tests/snapshots/latex/sources/1706.03762/vis/making_more_difficult_new.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2310.06825/images/rolling_buffer.pdf.md b/tests/snapshots/latex/sources/2305.03393/figs/HTMLvOTSLv7.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2310.06825/images/rolling_buffer.pdf.md rename to tests/snapshots/latex/sources/2305.03393/figs/HTMLvOTSLv7.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/basic_arch.pdf.md b/tests/snapshots/latex/sources/2305.03393/figs/html_freq_v4.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/basic_arch.pdf.md rename to tests/snapshots/latex/sources/2305.03393/figs/html_freq_v4.png.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/dsv3_performance.pdf.md b/tests/snapshots/latex/sources/2305.03393/figs/html_v_otsl_intro_v2.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/dsv3_performance.pdf.md rename to tests/snapshots/latex/sources/2305.03393/figs/html_v_otsl_intro_v2.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/dualpipe.pdf.md b/tests/snapshots/latex/sources/2305.03393/figs/otsl_proof_v3.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/dualpipe.pdf.md rename to tests/snapshots/latex/sources/2305.03393/figs/otsl_proof_v3.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/fp8-128accumulatorv4.pdf.md b/tests/snapshots/latex/sources/2305.03393/figs/otsl_vs_html_ex3_v2.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/fp8-128accumulatorv4.pdf.md rename to tests/snapshots/latex/sources/2305.03393/figs/otsl_vs_html_ex3_v2.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/fp8-frameworkv3.pdf.md b/tests/snapshots/latex/sources/2305.03393/figs/tablemodel_overview_otsl.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/fp8-frameworkv3.pdf.md rename to tests/snapshots/latex/sources/2305.03393/figs/tablemodel_overview_otsl.pdf.md diff --git a/tests/snapshots/latex/sources/2305.03393/llncsdoc.pdf.md b/tests/snapshots/latex/sources/2305.03393/llncsdoc.pdf.md new file mode 100644 index 00000000..2aadf328 --- /dev/null +++ b/tests/snapshots/latex/sources/2305.03393/llncsdoc.pdf.md @@ -0,0 +1,295 @@ +## Instructions for Using Springer's llncs Class for Computer Science Proceedings Papers + +llncs , Version 2.22, Sep 05, 2022 + +## 1 Installation + +Copy llncs.cls to a directory that is searched by L A TEX, e.g. either your texmf tree or the local work directory with your main L A TEX file. + +## 2 Working with the llncs Document Class + +## 2.1 General Information + +The llncs class is an extension of the standard L A TEX article class. Therefore you may use all article commands in your manuscript. + +If you are already familiar with L A TEX, the class should not give you llncs any major difficulties. It basically adjusts the layout to the required standard, defining styles and spacing of headings and captions and setting the printing area to 122mm horizontally by 193 mm vertically. To keep the layout consistent, we kindly ask you to refrain from using any L A TEX or TEX command that modifies these settings (i.e. \textheight , \vspace , baselinestretch , etc.). Such manual layout adjustments should be limited to very exceptional cases. + +In addition to defining the general layout, the llncs document class provides some special commands for typesetting the contribution header, i.e. title, authors, affiliations, abstract, and additional metadata. These special commands are described in Sect. 3. + +For a more detailed description of how to prepare your text, illustrations, and references, see the Springer Guidelines for Authors of Proceedings . + +## 2.2 How to Use the llncs Document Class + +The llncs class is invoked by replacing article by llncs in the first line of your L A TEX document: + +\documentclass{llncs} + +``` +\begin{document} \end{document} If your file is already coded with LATEX, you can easily adapt it to the llncs document class by replacing \documentclass{article} with \documentclass{llncs} +``` + +``` +\begin{document} \end{document} +``` + +If your file is already coded with L A TEX, you can easily adapt it to the llncs document class by replacing + +\documentclass{article} + +with + +\documentclass{llncs} + +## 3 How to Code the Header of Your Paper + +## 3.1 Title + +\title Please code the title of your contribution as follows: + +\title{<Your contribution title>} + +All words in titles should be capitalized except for conjunctions, prepositions (e.g. on, of, by, and, or, but, from, with, without, under), and definite/indefinite articles (the, a, an), unless they appear at the beginning. Formula letters are typeset as in the text. Long titles that run over multiple lines can be wrapped explicitly with \\ . Titles have no end punctuation. + +Acknowledgements should generally be placed in an unnumbered subsection at the end of the paper. If you still need to refer to a support or funding program \thanks in a note to the title, you can use the \thanks macro inside the title: + +\title{<Your contribution title>\thanks{<granted by x>}} + +Please do not use \thanks inside \author or \institute as footnotes for these elements are not supported in the online version and will therefore be dropped. + +If you need two or more footnotes please separate them with \fnmsep (i.e. f oot n ote m ark sep arator). + +\fnmsep + +If a long title does not fit in the single line of the running head, a warning is generated. You can specify an abbreviated title for the running head with the command + +\titlerunning + +\titlerunning{<Your abbreviated contribution title>} + +\subtitle An optional subtitle may also be added: + +\subtitle{<subtitle of your contribution>} + +## 3.2 Author(s) + +\author The name(s) of the author(s) are specified by: + +\author{<author(s) name(s)>} + +\and If there is more than one author, please separate them by \and . This makes sure that correct punctuation is inserted according to the number of authors. + +\inst Numbers referring to different addresses or affiliations should be attached to each author with the \inst{<number>} command. If an author is affiliated with multiple institutions the numbers should be separated by a comma, for example \inst{2,3} . + +\orcidID ORCID identifiers can be included with + +\orcidID{<ORCID identifier>} + +The ORCID (Open Researcher and Contributor ID) registry provides authors with unique digital identifiers that distinguish them from other researchers and help them link their research activities to these identifiers. Authors who are not yet registered with ORCID are encouraged to apply for an individual ORCID id at https://www.orcid.org and to include it in their papers. In the final publication, the ORCID id will be replaced by an ORCID icon, which will link from the eBook to the actual ID in the ORCID database. The ORCID icon will also replace the number in the printed book. + +If you have done this correctly, the author line now reads, for example: + +``` +\author{First Author\inst{1}\orcidID{0000-1111-2222-3333} \and Second Author\inst{2,3}\orcidID{1111-2222-3333-4444}} +``` + +The given name(s) should always be followed by the family name(s). Authors who have more than one family name should indicate which part of their name represents the family name(s), for example by non-breaking spaces Jos\'{e} Martinez~Perez or curly braces Jos\'{e} {Martinez Perez} . + +As given name(s) are to be shortened to initials in the running heads, specifying an abbreviated author list with the optional command: + +\authorrunning + +``` +\authorrunning{} +``` + +might add some clarity about the correct representation of author names, in the running-heads as well as in the author index. + +## 3.3 Affiliations + +\institute Addresses of institutes, companies, etc. should be given in \institute . + +Multiple affiliations are separated by \and , which automatically assures correct numbering: + +``` +\institute{ \and \and } \email Inside \institute you can use \email{} \url and \url{} +``` + +``` +\institute{ \and \and } +``` + +\email Inside \institute you can use + +\email{<email address>} + +\url and + +``` +\url{} +``` + +to provide author email addresses and Web pages. If you need to typeset the tilde character - e.g. for your Web page in your unix system's home directory - the \homedir command will do this. If multiple authors have the same affiliation, please check that the order of email addresses matches the sequence of (affiliated) author names. + +Please note that, if email addresses are given in your paper, they will also be included in the metadata of the online version. + +## 3.4 Format the Header + +\maketitle The command \maketitle formats the header of your paper. If you leave it out the work done so far will produce no text. + +## 3.5 Abstract and Keywords + +abstract ( env. ) The abstract is coded as follows: + +``` +abstract(env.) The abstract is coded as follows: \begin{abstract} \end{abstract} +``` + +``` +\begin{abstract} \end{abstract} +``` + +\keywords Keywords should be specified inside the abstract environment. Please capitalize \and the first letter of each keyword and again separate them with \and : + +\keywords{First keyword \and Second keyword \and Third keyword} + +The keyword separator will then be properly rendered as a middle dot. + +## 4 How to Code the Body of Your Paper + +## 4.1 General Rules + +From a technical point of view, the llncs document class does not require any specific L A TEX coding in the body of your paper. You can simply use the commands provided by the 'article' document class. For more information about what will be done with your manuscript before publication, please refer to the Springer Guidelines for Authors of Proceedings . + +## 4.2 Special Math Characters + +The llncs document class supports some additional special characters: + +``` +\grole yields > < \getsto yields ← → \lid yields < = \gid yields > = +``` + +If you need blackboard bold characters, i.e. for sets of numbers, please load the related AMS -TEXfonts. If for some reason this is not possible you can also use the following commands from the llncs class: + +| \bbbc | yields | C | \bbbf | yields | IF | +|---------|----------|-----|---------|----------|------| +| \bbbh | yields | IH | \bbbk | yields | IK | +| \bbbm | yields | IM | \bbbn | yields | IN | +| \bbbp | yields | IP | \bbbq | yields | Q | +| \bbbr | yields | IR | \bbbs | yields | S | +| \bbbt | yields | T | \bbbz | yields | ZZ | +| \bbbone | yields | 1l | | | | + +Please note that all these characters are only available in math mode. + +## 5 Theorems, Definitions, and Proofs + +## 5.1 Predefined Theorem-Like Environments + +corollary ( env. ) Several theorem-like environments are predefined in the llncs document class. ( ) The following environments have a bold run-in heading, while the following text definition env. lemma ( env. ) is in italics: + +( env. ) proposition + +``` +\begin{corollary} \end{corollary} \begin{definition} \end{definition} \begin{lemma} \end{lemma} \begin{proposition} \end{proposition} \begin{theorem} \end{theorem} +``` + +case ( env. ) Other theorem-like environments render the text in roman, while the run-in conjecture ( env. ) heading is bold as well: + +example ( env. ) + +``` +property(env.) question(env.) exercise(env.) solution(env.)heading is bold as well: problem(env.) note(env.) \begin{case} \end{case} \begin{conjecture} \end{conjecture} \begin{example} \end{example} \begin{exercise} \end{exercise} \begin{note} \end{note} \begin{problem} \end{problem} remark(env.) \begin{property} \end{property} \begin{question} \end{question} \begin{remark} \end{remark} \begin{solution} \end{solution} +``` + +claim ( env. ) Finally, there are also two unnumbered environments that have the run-in headproof ( env. ) ing in italics and the text in upright roman. + +``` +\begin{claim} \end{claim} \begin{proof} \end{proof} +``` + +\qed Proofs may contain an eye catching square, which can be inserted with \qed ) before the environment ends. + +## 5.2 User-Defined Theorem-Like Environments + +\spnewtheorem We have enhanced the standard \newtheorem command and slightly changed its syntax to get two new commands \spnewtheorem and \spnewtheorem* that now can be used to define additional environments. They require two additional arguments, namely the font style of the label and the font style of the text of the new environment: + +\spnewtheorem{<env\_nam>}[<num\_like>]{<caption>}{<cap\_font>}{<body\_font>} + +``` +\spnewtheorem{}[]{}{}{} For example, \spnewtheorem{maintheorem}[theorem]{Main Theorem}{\bfseries}{\itshape} +``` + +For example, + +\spnewtheorem{maintheorem}[theorem]{Main Theorem}{\bfseries}{\itshape} + +will create a main theorem environment that is numbered together with the predefined theorem . The sharing of the default counter ( [theorem] ) is desired. If you omit the optional second argument of \spnewtheorem , a separate counter for your new environment is used throughout your document. + +In combination with the (obsolete) class option envcountsect (see. Sect. 7), the \spnewtheorem command also supports the syntax: + +\spnewtheorem{<env\_nam>}{<caption>}[<within>]{<cap\_font>}{<body\_font>} + +With the parameter <within> , you can control the sectioning element that resets the theorem counters. If you specify, for example, subsection , the newly defined environment is numbered subsectionwise. + +If you wish to add an unnumbered environment, please use the syntax + +\spnewtheorem* + +\spnewtheorem*{<env\_nam>}{<caption>}{<cap\_font>}{<body\_font>} + +## 6 References + +There are three options for citing references: + +``` +- arabic numbers, i.e. [1], [3-5], [4-6,9], - labels, i.e. [CE1], [AB1,XY2], - author/year system,(Smith et al. 2000),(Miller 1999a, 12; Brown 2018). +``` + +- arabic numbers, i.e. [1], [3-5], [4-6,9], +- labels, i.e. [CE1], [AB1,XY2], +- author/year system, (Smith et al. 2000), (Miller 1999a, 12; Brown 2018). + +We prefer citations with arabic numbers, i.e. the usage of \bibitem without an optional parameter. If you want to use the author/year system, you can use the class option citeauthoryear , i.e. + +citeauthoryear + +\documentclass[citeauthoryear]{llncs} + +Please note that this option does not automatically change your citations to the author/year style. It basically redefines the \bibitem command to take the publication year as an optional parameter that is displayed instead of an arabic number. Author name(s) and, if necessary, parentheses are to be typed manually. If your reference reads + +``` +\bibitem[2016]{vdaalst:2016} van der Aalst, W.: Process Mining, 2nd ed. Springer, Heidelberg(2016) and is cited as follows:... is shown by van der Aalst(\cite{vdaalst:2016}) the resulting text will be: "... is shown by van der Aalst(2016)." +``` + +We encourage you to use Bib TEX for typesetting your references. For formatting the bibliography according to Springer's standard (for mathematics, physical sciences, and computer science), please use the bibliography style file splncs04.bst that comes with the llncs document class. You simply need to add \bibliographystyle{splncs04} to your document. DOIs should be provided in the doi field of your .bib database. Bib TEX will then automatically add them to your references. Please note that we do not provide an option to implement splncs04.bst + +\doi If you do not use Bib TEX, you can include a DOI with the \doi command: + +- \doi If you do not use Bib TEX, you can include a DOI with the \doi command: \doi{<DOI>} + +\doi{<DOI>} + +The DOI will be expanded to the URL https://doi.org/<DOI> in accordance with the CrossRef guidelines. + +## 7 Obsolete Class Options + +The llncs document class contains several class options that have become obsolete over the years. We only mention them for completeness: + +- The document class changes the formatting of vectors coded with orivec llncs \vec to boldface italics. If you absolutely need the original L A TEX design for vectors, i.e. an arrow above the related variable, you can restore it with the orivec option. +- All theorem-like environments share one counter, i.e. Theorem 1, Lemma 2, Corollary 3, etc. + +envcountsame + +- All theorem-like environments are numbered per section, i.e. the related counters are reset to 1 in every section. + +envcountreset + +- All theorem-like environments are numbered per section, and the section number added to the individual counter, i.e. Theorem 1.2, Lemma 2.2, etc. + +envcountsect + +- This option produces the "open" bibliography style, in which each block starts on a new line, and succeeding lines in a block are indented by \bibindent . + +openbib + +- This option restores the original L A TEX definitions for the bibliography and oribibl the \cite mechanism that some Bib TEX applications rely on. diff --git a/tests/snapshots/latex/sources/2310.06825/images/230927_bars.png.md b/tests/snapshots/latex/sources/2310.06825/images/230927_bars.png.md new file mode 100644 index 00000000..d01027fa --- /dev/null +++ b/tests/snapshots/latex/sources/2310.06825/images/230927_bars.png.md @@ -0,0 +1,5 @@ + + + + + diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/fp8-v.s.-bf16.pdf.md b/tests/snapshots/latex/sources/2310.06825/images/230927_effective_sizes.png.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/fp8-v.s.-bf16.pdf.md rename to tests/snapshots/latex/sources/2310.06825/images/230927_effective_sizes.png.md diff --git a/tests/pdf_snapshots/latex/sources/2310.06825/images/chunking.pdf.md b/tests/snapshots/latex/sources/2310.06825/images/chunking.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2310.06825/images/chunking.pdf.md rename to tests/snapshots/latex/sources/2310.06825/images/chunking.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/nextn.pdf.md b/tests/snapshots/latex/sources/2310.06825/images/header.jpeg.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/nextn.pdf.md rename to tests/snapshots/latex/sources/2310.06825/images/header.jpeg.md diff --git a/tests/snapshots/latex/sources/2310.06825/images/llama_vs_mistral_example.png.md b/tests/snapshots/latex/sources/2310.06825/images/llama_vs_mistral_example.png.md new file mode 100644 index 00000000..6dbc5160 --- /dev/null +++ b/tests/snapshots/latex/sources/2310.06825/images/llama_vs_mistral_example.png.md @@ -0,0 +1,17 @@ +## Can you recommend a foundational and accessible book about quantum physics? + + + +Copy Linkto Question + +## Round wWinner: mistral-7b-instruct-vo.1 + + + +## mistral-7b-instruct-v0.1 Round Winner + +## llama-2-13b-chat + +Certainly! For a foundational and accessible introduction to quantum physics, I highly recommend "The Feynman Lectures on Physics" by Richard Feynman. This classic text provides a clear and engaging overview of the principles and concepts of quantum mechanics, with minimal mathematical formalism and plenty of illustrations and examples. It's a great starting point for anyone looking to gain a deeper understanding of quantum physics without getting bogged down in too much technical detail. + +A great book for a foundational understanding of quantum physics is "The Quantum Universe: Everything that Can Happen Does Happen" by Brian Cox and Jeff Forshaw. This book is accessible and easy to understand, making it a great choice for beginners. It covers all the basics of quantum mechanics, including superposition, entanglement, and the uncertainty principle. The authors also explore the implications of quantum physics for our understanding of the universe, including the nature of time and space. Overall, "The Quantum Universe" is an excellent choice for anyone looking to gain a foundational understanding of this fascinating field diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_13-18.pdf.md b/tests/snapshots/latex/sources/2310.06825/images/rolling_buffer.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_13-18.pdf.md rename to tests/snapshots/latex/sources/2310.06825/images/rolling_buffer.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2310.06825/images/swa.pdf.md b/tests/snapshots/latex/sources/2310.06825/images/swa.pdf.md similarity index 88% rename from tests/pdf_snapshots/latex/sources/2310.06825/images/swa.pdf.md rename to tests/snapshots/latex/sources/2310.06825/images/swa.pdf.md index 826cc7bf..0847b137 100644 --- a/tests/pdf_snapshots/latex/sources/2310.06825/images/swa.pdf.md +++ b/tests/snapshots/latex/sources/2310.06825/images/swa.pdf.md @@ -1,13 +1,11 @@ - +Effective Context Length - +Sliding Window Attention -Effective Context Length - -Sliding Window Attention - Vanilla Attention + + diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_19-24.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/basic_arch.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_19-24.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/basic_arch.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/logo/DeepSeek.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/dsv3_performance.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/logo/DeepSeek.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/dsv3_performance.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/17-bpt_scatter_examples_3x3.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/dualpipe.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/17-bpt_scatter_examples_3x3.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/dualpipe.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/322-bpt_scatter_examples_3x3.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/fp8-128accumulatorv4.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/322-bpt_scatter_examples_3x3.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/fp8-128accumulatorv4.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/SFNet_ResNet18-TopK.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/fp8-frameworkv3.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/SFNet_ResNet18-TopK.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/fp8-frameworkv3.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/equations.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/fp8-v.s.-bf16.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/equations.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/fp8-v.s.-bf16.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/needle_in_a_haystack.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/needle_in_a_haystack.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/needle_in_a_haystack.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/needle_in_a_haystack.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/pca-comparison.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/nextn.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/pca-comparison.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/nextn.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/overlap.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/overlap.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/overlap.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/overlap.pdf.md diff --git a/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi.pdf.md new file mode 100644 index 00000000..bd168040 --- /dev/null +++ b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi.pdf.md @@ -0,0 +1,16 @@ +## Aux-Loss-Based Layer 9 + + + +- Wikipedia (en) +- DM Mathematics + + + +- Wikipedia (en) +- DM Mathematics +- Wikipedia (en) + + + +- DM Mathematics diff --git a/tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/BQSC-1003.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_1-6.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/BQSC-1003.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_1-6.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/D-BQSC-0004-1003.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_13-18.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/D-BQSC-0004-1003.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_13-18.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/P_B.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_19-24.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/P_B.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_19-24.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_25-26.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_25-26.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_25-26.pdf.md rename to tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_25-26.pdf.md diff --git a/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_7-12.pdf.md b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_7-12.pdf.md new file mode 100644 index 00000000..9e663685 --- /dev/null +++ b/tests/snapshots/latex/sources/2412.19437/figures/relative_expert_load_multi_7-12.pdf.md @@ -0,0 +1,5 @@ +## Aux-Loss-Based Layer 7 + + + +Wikipedia (en) Github DM Mathematics 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 diff --git a/tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/P_M.pdf.md b/tests/snapshots/latex/sources/2412.19437/logo/DeepSeek.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/P_M.pdf.md rename to tests/snapshots/latex/sources/2412.19437/logo/DeepSeek.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/138-bpt_scatter_examples_3x3.pdf.md b/tests/snapshots/latex/sources/2501.00089/138-bpt_scatter_examples_3x3.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/138-bpt_scatter_examples_3x3.pdf.md rename to tests/snapshots/latex/sources/2501.00089/138-bpt_scatter_examples_3x3.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/2501.00089/157-bpt_scatter_examples_3x3.pdf.md b/tests/snapshots/latex/sources/2501.00089/157-bpt_scatter_examples_3x3.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/2501.00089/157-bpt_scatter_examples_3x3.pdf.md rename to tests/snapshots/latex/sources/2501.00089/157-bpt_scatter_examples_3x3.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/P_q.pdf.md b/tests/snapshots/latex/sources/2501.00089/17-bpt_scatter_examples_3x3.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/P_q.pdf.md rename to tests/snapshots/latex/sources/2501.00089/17-bpt_scatter_examples_3x3.pdf.md diff --git a/tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/m_q.pdf.md b/tests/snapshots/latex/sources/2501.00089/322-bpt_scatter_examples_3x3.pdf.md similarity index 100% rename from tests/pdf_snapshots/latex/sources/arXiv-2501.01300v2/m_q.pdf.md rename to tests/snapshots/latex/sources/2501.00089/322-bpt_scatter_examples_3x3.pdf.md diff --git a/tests/snapshots/latex/sources/2501.00089/SFNet_ResNet18-TopK.pdf.md b/tests/snapshots/latex/sources/2501.00089/SFNet_ResNet18-TopK.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/2501.00089/SFNet_ResNet18-TopK.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/2501.00089/equations.pdf.md b/tests/snapshots/latex/sources/2501.00089/equations.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/2501.00089/equations.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/2501.00089/pca-comparison.pdf.md b/tests/snapshots/latex/sources/2501.00089/pca-comparison.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/2501.00089/pca-comparison.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/BQSC-1003.pdf.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/BQSC-1003.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/BQSC-1003.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/D-BQSC-0004-1003.pdf.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/D-BQSC-0004-1003.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/D-BQSC-0004-1003.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_B.pdf.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_B.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_B.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_M.pdf.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_M.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_M.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_q.pdf.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_q.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/P_q.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/cas-email.jpeg.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/cas-email.jpeg.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/cas-email.jpeg.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/latex/sources/arXiv-2501.01300v2/m_q.pdf.md b/tests/snapshots/latex/sources/arXiv-2501.01300v2/m_q.pdf.md new file mode 100644 index 00000000..60c69367 --- /dev/null +++ b/tests/snapshots/latex/sources/arXiv-2501.01300v2/m_q.pdf.md @@ -0,0 +1 @@ + diff --git a/tests/snapshots/mets_gbs/sources/32044009881525_select.tar.gz.md b/tests/snapshots/mets_gbs/sources/32044009881525_select.tar.gz.md new file mode 100644 index 00000000..87e2c775 --- /dev/null +++ b/tests/snapshots/mets_gbs/sources/32044009881525_select.tar.gz.md @@ -0,0 +1,73 @@ +recently become prevalent that he who speaks of military power is a " militarist . " This , howreverse assertion ever , is as great a fallacy as the that he who talks of nothing but peace is a 66 pacifist . " + +Truth , even bitter truth , is better than the most high - minded fallacy . + +The author has visited Japan , Siberia , China , the Philippines , the Malay States , and Hawaii in 1919 and 1920 , and his personal impressions and investigations form the basis of the present book . The list of works which he has perused in the course of his investigation of the problem of the Pacific is hereto appended . + +The author wishes to acknowledge his debt to Admiral A. D. Bubnov , who has contributed Chapters VII - X . Admiral Bubnov took part in the Russo - Japanese War , was Professor of the Naval Staff College at Petrograd , and Chief of the Naval Section of the Staff of the Supreme Commander - in - Chief in the Great War . The Admiral is an authoritative student of the questions of naval strategy discussed in the chapters that belong to his pen . + +The author also has to thank Mr. C. Nabokoff , the late Russian Chargé d'Affaires in London , book . for undertaking the translation of his + +## 62 THE PROBLEM OF THE PACIFIC + +copper mines with up - to - date technical equipment in various provinces of Central China ¹ : - + +| | | | | +|----|----|----|----| +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | + +It has been mentioned in one of the preceding chapters that Japanese industries needed iron . The desire to obtain the necessary supplies of iron is thus perfectly legitimate . Japan's endeavour to acquire concessions for the production of iron and coal is not , therefore , a proof of the Imperialism of her policy . But , as the French saying goes , Le ton fait la chanson . Japan is trying to get hold of the entire iron industry of China . She is doing so by the veiled seizure of political and administrative control of the respective provinces of China . To Europe and America this is presented under the guise of the nebulous formula of 66 special interests in the regions of China adjacent to Japan . " Manchuria and Shantung are first in that list . When Japan succeeds , she will have deprived China + +1 These data relate to 1915 . + +## 252 THE PROBLEM OF THE PACIFIC + +France may lay down new tonnage in the years 1927 , 1929 , and 1931 , as provided in Part 3 , Section II . + +Ships which may be retained by Italy . + +| | | | | +|----|----|----|----| +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | +| | | | | + +Italy may lay down new tonnage in the years 1927 , 1929 and 1931 , as provided in Part 3 , Section II . + +| | | | | | | | +|----|----|----|----|----|----|----| +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | +| | | | | | | | + +- Part 2. - RULES FOR SCRAPPING VESSELs of War . The following rules shall be observed for the scrapping of vessels of war which are to be disposed of in accordance with Articles II and III . +- I. A vessel to be scrapped must be placed in such condition that it cannot be put to combative use . +- II . This result must be finally effected in any one of the following ways : +- ( a ) Permanent sinking of the vessel ; +- ( b ) Breaking the vessel up . This shall always involve the destruction or removal of all machinery , boilers and armour , and all deck , side and bottom plating ; diff --git a/tests/snapshots/odf/sources/odf_presentation_01.odp.pdf.md b/tests/snapshots/odf/sources/odf_presentation_01.odp.pdf.md new file mode 100644 index 00000000..3db344da --- /dev/null +++ b/tests/snapshots/odf/sources/odf_presentation_01.odp.pdf.md @@ -0,0 +1,13 @@ +## ● + +``` +eW e● a s e F l ● e T e● ● u e T r F e● ● ● s e F C● ● t C A 2● ● ● C ● a b e T l a s F l ● u r a s F l ● a s l a s e u e l T r ● ● B ● ● a s s l S d l i +``` + + + +- • Some info: + +• • Some info: Item B Item A + +- Item B Item A diff --git a/tests/pdf_snapshots/odf/sources/odf_presentation_02.odp.pdf.md b/tests/snapshots/odf/sources/odf_presentation_02.odp.pdf.md similarity index 80% rename from tests/pdf_snapshots/odf/sources/odf_presentation_02.odp.pdf.md rename to tests/snapshots/odf/sources/odf_presentation_02.odp.pdf.md index eb0f3f89..1163b433 100644 --- a/tests/pdf_snapshots/odf/sources/odf_presentation_02.odp.pdf.md +++ b/tests/snapshots/odf/sources/odf_presentation_02.odp.pdf.md @@ -6,9 +6,6 @@ -| Column 4 | -|------------| - diff --git a/tests/pdf_snapshots/odf/sources/odf_table_with_title_01.ods.pdf.md b/tests/snapshots/odf/sources/odf_table_with_title_01.ods.pdf.md similarity index 100% rename from tests/pdf_snapshots/odf/sources/odf_table_with_title_01.ods.pdf.md rename to tests/snapshots/odf/sources/odf_table_with_title_01.ods.pdf.md diff --git a/tests/pdf_snapshots/odf/sources/text_document_01.odt.pdf.md b/tests/snapshots/odf/sources/text_document_01.odt.pdf.md similarity index 77% rename from tests/pdf_snapshots/odf/sources/text_document_01.odt.pdf.md rename to tests/snapshots/odf/sources/text_document_01.odt.pdf.md index 19c8e55c..5a42db36 100644 --- a/tests/pdf_snapshots/odf/sources/text_document_01.odt.pdf.md +++ b/tests/snapshots/odf/sources/text_document_01.odt.pdf.md @@ -10,15 +10,16 @@ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. -- 1. numbered list 1 -- 2. numbered list 2 -- ◦ bullet list 2.1 -- ◦ bullet list 2.2 -- ▪ bullet list 2.2.1 -- ◦ bullet list 2.3 -- • numbered list 3 -- ▪ bullet list 3.0.1 +1. numbered list 1 +2. numbered list 2 + +- bullet list 2.1 +- bullet list 2.2 +- bullet list 2.2.1 +- bullet list 2.3 +- numbered list 3 • +- bullet list 3.0.1 ## Heading level 2: B -Contrary to popular belief, Lorem Ipsum is not simply random text . Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature , discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" ( The Extremes of Good and Evil ) by Cicero, written in 45 BC. +Contrary to popular belief, Lorem Ipsum is not simply random text . Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia , looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. diff --git a/tests/snapshots/odf/sources/text_document_02.odt.pdf.md b/tests/snapshots/odf/sources/text_document_02.odt.pdf.md new file mode 100644 index 00000000..fd992c8d --- /dev/null +++ b/tests/snapshots/odf/sources/text_document_02.odt.pdf.md @@ -0,0 +1,20 @@ +## Title + +## heading level 1.0 + +Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since 1966. + +## Heading level 2: A + +Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. + +| Merged row | Cell 1.3 | Cell 1.4 | Cell 1.5 | Cell 1.6 | Cell 1.7 | +|--------------|-----------------|-----------------|------------|---------------|------------| +| | Merged cell 2x2 | Merged cell 2x2 | | Merged column | | +| | | | | Merged column | | +| | | | | Merged column | | +| | | | | Merged column | | + + + + diff --git a/tests/snapshots/odf/sources/text_document_03.odt.pdf.md b/tests/snapshots/odf/sources/text_document_03.odt.pdf.md new file mode 100644 index 00000000..623a4572 --- /dev/null +++ b/tests/snapshots/odf/sources/text_document_03.odt.pdf.md @@ -0,0 +1,60 @@ +## Table with rich cells + +| Column A | Column B | +|---------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------| +| This is a list: • A First • A Second • A Third | This is a formatted list: • B First • B Second • B Third | +| First Paragraph Second Paragraph Third paragraph before a numbered list 1. Number one 2. Number two 3. Number three | This is simple text with bold, strikethrough and italic formatting with x2 and H2O | +| This is a paragraph This is another paragraph | | + +## Table with nested table + +Before table + +| Column A | Column A | Column A | Column B | Column B | Column B | +|------------------------|------------------------|------------------------|---------------------------------------|---------------------------------------|---------------------------------------| +| Simple cell upper left | Simple cell upper left | Simple cell upper left | Simple cell with bold and italic text | Simple cell with bold and italic text | Simple cell with bold and italic text | +| A | B | C | Rich cell | Rich cell | Rich cell | +| Cell 1 | Cell 2 | Cell 3 | A nested table | A nested table | A nested table | +| | | | | | | +| | | | A | B | C | +| | | | Cell 1 | Cell 2 | Cell 3 | + +After table with bold , underline, strikethrough, and italic formatting + +## Table with pictures + +| Column A | Column B | +|------------------|------------| +| Only text | | +| Text and picture | | + +## Lists with same numId in different cells + +| • Cell 1 item 1 | +|-------------------| +| • Cell 1 item 2 | +| • Cell 2 item 1 | +| • Cell 2 item 2 | + +## Lists with different numIds in different cells + +| • Cell 1 item 1 | +|-------------------| +| • Cell 1 item 2 | +| • Cell 2 item 1 | +| • Cell 2 item 2 | + +## Multiple columns with lists + +| • R1C1 item 1 • R1C1 item 2 | • R1C2 item 1 • R1C2 2 | +|-------------------------------|--------------------------| +| | item | +| • R2C1 item 1 | • R2C2 item 1 | +| • R2C1 item 2 | • R2C2 item 2 | + +## Mixed content - list and regular text in different cells + +| • List item | +|-----------------------------| +| • List item 2 | +| Regular text in second cell | diff --git a/tests/snapshots/pdf/sources/2203.01017v2.pdf.md b/tests/snapshots/pdf/sources/2203.01017v2.pdf.md new file mode 100644 index 00000000..0bb6f5c7 --- /dev/null +++ b/tests/snapshots/pdf/sources/2203.01017v2.pdf.md @@ -0,0 +1,429 @@ +## TableFormer: Table Structure Understanding with Transformers. + +Ahmed Nassar, Nikolaos Livathinos, Maksym Lysak, Peter Staar IBM Research + +{ ahn,nli,mly,taa } @zurich.ibm.com + +## Abstract + +Tables organize valuable content in a concise and compact representation. This content is extremely valuable for systems such as search engines, Knowledge Graph's, etc, since they enhance their predictive capabilities. Unfortunately, tables come in a large variety of shapes and sizes. Furthermore, they can have complex column/row-header configurations, multiline rows, different variety of separation lines, missing entries, etc. As such, the correct identification of the table-structure from an image is a nontrivial task. In this paper, we present a new table-structure identification model. The latter improves the latest end-toend deep learning model (i.e. encoder-dual-decoder from PubTabNet) in two significant ways. First, we introduce a new object detection decoder for table-cells. In this way, we can obtain the content of the table-cells from programmatic PDF's directly from the PDF source and avoid the training of the custom OCR decoders. This architectural change leads to more accurate table-content extraction and allows us to tackle non-english tables. Second, we replace the LSTM decoders with transformer based decoders. This upgrade improves significantly the previous state-of-the-art tree-editing-distance-score (TEDS) from 91% to 98.5% on simple tables and from 88.7% to 95% on complex tables. + +## 1. Introduction + +The occurrence of tables in documents is ubiquitous. They often summarise quantitative or factual data, which is cumbersome to describe in verbose text but nevertheless extremely valuable. Unfortunately, this compact representation is often not easy to parse by machines. There are many implicit conventions used to obtain a compact table representation. For example, tables often have complex columnand row-headers in order to reduce duplicated cell content. Lines of different shapes and sizes are leveraged to separate content or indicate a tree structure. Additionally, tables can also have empty/missing table-entries or multi-row textual table-entries. Fig. 1 shows a table which presents all these issues. + +## a. Picture of a table: + +Figure 1: Picture of a table with subtle, complex features such as (1) multi-column headers, (2) cell with multi-row text and (3) cells with no content. Image from PubTabNet evaluation set, filename: 'PMC2944238 004 02'. + + + +| issues.a. | | 13 | 201 | | +|-------------|----|------|-------|----| +| 32 | | | | | +| 32 | | | | | +| 32 | | | | | + +- b. Red-annotation of bounding boxes, Blue-predictions by TableFormer + + + +- c. Structure predicted by TableFormer: + +| issues.a. 0 | 1 32 | 2 201 13 | 2 201 13 | 2 201 13 | +|---------------|--------|------------|------------|------------| +| 3 | 4 | 5 | 6 | 7 | +| 8 2 | 9 | 10 | 1 1 | 12 | +| 8 2 | 13 | 14 | 15 | 16 | +| 8 2 | 17 | 18 | 19 | | + +Recently, significant progress has been made with vision based approaches to extract tables in documents. For the sake of completeness, the issue of table extraction from documents is typically decomposed into two separate challenges, i.e. (1) finding the location of the table(s) on a document-page and (2) finding the structure of a given table in the document. + +The first problem is called table-location and has been previously addressed [30, 38, 19, 21, 23, 26, 8] with stateof-the-art object-detection networks (e.g. YOLO and later on Mask-RCNN [9]). For all practical purposes, it can be considered as a solved problem, given enough ground-truth data to train on. + +The second problem is called table-structure decomposition. The latter is a long standing problem in the community of document understanding [6, 4, 14]. Contrary to the table-location problem, there are no commonly used approaches that can easily be re-purposed to solve this problem. Lately, a set of new model-architectures has been proposed by the community to address table-structure decomposition [37, 36, 18, 20]. All these models have some weaknesses (see Sec. 2). The common denominator here is the reliance on textual features and/or the inability to provide the bounding box of each table-cell in the original image. + +In this paper, we want to address these weaknesses and present a robust table-structure decomposition algorithm. The design criteria for our model are the following. First, we want our algorithm to be language agnostic. In this way, we can obtain the structure of any table, irregardless of the language. Second, we want our algorithm to leverage as much data as possible from the original PDF document. For programmatic PDF documents, the text-cells can often be extracted much faster and with higher accuracy compared to OCR methods. Last but not least, we want to have a direct link between the table-cell and its bounding box in the image. + +To meet the design criteria listed above, we developed a new model called TableFormer and a synthetically generated table structure dataset called SynthTabNet 1 . In particular, our contributions in this work can be summarised as follows: + +- We propose TableFormer , a transformer based model that predicts tables structure and bounding boxes for the table content simultaneously in an end-to-end approach. +- Across all benchmark datasets TableFormer significantly outperforms existing state-of-the-art metrics, while being much more efficient in training and inference to existing works. +- We present SynthTabNet a synthetically generated dataset, with various appearance styles and complexity. +- An augmented dataset based on PubTabNet [37], FinTabNet [36], and TableBank [17] with generated ground-truth for reproducibility. + +The paper is structured as follows. In Sec. 2, we give a brief overview of the current state-of-the-art. In Sec. 3, we describe the datasets on which we train. In Sec. 4, we introduce the TableFormer model-architecture and describe + +1https://github.com/IBM/SynthTabNet its results & performance in Sec. 5. As a conclusion, we describe how this new model-architecture can be re-purposed for other tasks in the computer-vision community. + +## 2. Previous work and State of the Art + +Identifying the structure of a table has been an outstanding problem in the document-parsing community, that motivates many organised public challenges [6, 4, 14]. The difficulty of the problem can be attributed to a number of factors. First, there is a large variety in the shapes and sizes of tables. Such large variety requires a flexible method. This is especially true for complex column- and row headers, which can be extremely intricate and demanding. A second factor of complexity is the lack of data with regard to table-structure. Until the publication of PubTabNet [37], there were no large datasets (i.e. > 100 K tables) that provided structure information. This happens primarily due to the fact that tables are notoriously time-consuming to annotate by hand. However, this has definitely changed in recent years with the deliverance of PubTabNet [37], FinTabNet [36], TableBank [17] etc. + +Before the rising popularity of deep neural networks, the community relied heavily on heuristic and/or statistical methods to do table structure identification [3, 7, 11, 5, 13, 28]. Although such methods work well on constrained tables [12], a more data-driven approach can be applied due to the advent of convolutional neural networks (CNNs) and the availability of large datasets. To the best-of-our knowledge, there are currently two different types of network architecture that are being pursued for state-of-the-art tablestructure identification. + +Image-to-Text networks : In this type of network, one predicts a sequence of tokens starting from an encoded image. Such sequences of tokens can be HTML table tags [37, 17] or LaTeX symbols[10]. The choice of symbols is ultimately not very important, since one can be transformed into the other. There are however subtle variations in the Image-to-Text networks. The easiest network architectures are "image-encoder → text-decoder" (IETD), similar to network architectures that try to provide captions to images [32]. In these IETD networks, one expects as output the LaTeX/HTML string of the entire table, i.e. the symbols necessary for creating the table with the content of the table. Another approach is the "image-encoder → dual decoder" (IEDD) networks. In these type of networks, one has two consecutive decoders with different purposes. The first decoder is the tag-decoder , i.e. it only produces the HTML/LaTeX tags which construct an empty table. The second content-decoder uses the encoding of the image in combination with the output encoding of each cell-tag (from the tag-decoder ) to generate the textual content of each table cell. The network architecture of IEDD is certainly more elaborate, but it has the advantage that one can pre-train the tag-decoder which is constrained to the table-tags. + +In practice, both network architectures (IETD and IEDD) require an implicit, custom trained object-characterrecognition (OCR) to obtain the content of the table-cells. In the case of IETD, this OCR engine is implicit in the decoder similar to [24]. For the IEDD, the OCR is solely embedded in the content-decoder. This reliance on a custom, implicit OCR decoder is of course problematic. OCR is a well known and extremely tough problem, that often needs custom training for each individual language. However, the limited availability for non-english content in the current datasets, makes it impractical to apply the IETD and IEDD methods on tables with other languages. Additionally, OCR can be completely omitted if the tables originate from programmatic PDF documents with known positions of each cell. The latter was the inspiration for the work of this paper. + +Graph Neural networks : Graph Neural networks (GNN's) take a radically different approach to tablestructure extraction. Note that one table cell can constitute out of multiple text-cells. To obtain the table-structure, one creates an initial graph, where each of the text-cells becomes a node in the graph similar to [33, 34, 2]. Each node is then associated with en embedding vector coming from the encoded image, its coordinates and the encoded text. Furthermore, nodes that represent adjacent text-cells are linked. Graph Convolutional Networks (GCN's) based methods take the image as an input, but also the position of the text-cells and their content [18]. The purpose of a GCN is to transform the input graph into a new graph, which replaces the old links with new ones. The new links then represent the table-structure. With this approach, one can avoid the need to build custom OCR decoders. However, the quality of the reconstructed structure is not comparable to the current state-of-the-art [18]. + +Hybrid Deep Learning-Rule-Based approach : A popular current model for table-structure identification is the use of a hybrid Deep Learning-Rule-Based approach similar to [27, 29]. In this approach, one first detects the position of the table-cells with object detection (e.g. YoloVx or MaskRCNN), then classifies the table into different types (from its images) and finally uses different rule-sets to obtain its table-structure. Currently, this approach achieves stateof-the-art results, but is not an end-to-end deep-learning method. As such, new rules need to be written if different types of tables are encountered. + +## 3. Datasets + +We rely on large-scale datasets such as PubTabNet [37], FinTabNet [36], and TableBank [17] datasets to train and evaluate our models. These datasets span over various appearance styles and content. We also introduce our own synthetically generated SynthTabNet dataset to fix an im + +Figure 2: Distribution of the tables across different table dimensions in PubTabNet + FinTabNet datasets + + + +balance in the previous datasets. + +The PubTabNet dataset contains 509k tables delivered as annotated PNG images. The annotations consist of the table structure represented in HTML format, the tokenized text and its bounding boxes per table cell. Fig. 1 shows the appearance style of PubTabNet. Depending on its complexity, a table is characterized as "simple" when it does not contain row spans or column spans, otherwise it is "complex". The dataset is divided into Train and Val splits (roughly 98% and 2%). The Train split consists of 54% simple and 46% complex tables and the Val split of 51% and 49% respectively. The FinTabNet dataset contains 112k tables delivered as single-page PDF documents with mixed table structures and text content. Similarly to the PubTabNet, the annotations of FinTabNet include the table structure in HTML, the tokenized text and the bounding boxes on a table cell basis. The dataset is divided into Train, Test and Val splits (81%, 9.5%, 9.5%), and each one is almost equally divided into simple and complex tables (Train: 48% simple, 52% complex, Test: 48% simple, 52% complex, Test: 53% simple, 47% complex). Finally the TableBank dataset consists of 145k tables provided as JPEG images. The latter has annotations for the table structure, but only few with bounding boxes of the table cells. The entire dataset consists of simple tables and it is divided into 90% Train, 3% Test and 7% Val splits. + +Due to the heterogeneity across the dataset formats, it was necessary to combine all available data into one homogenized dataset before we could train our models for practical purposes. Given the size of PubTabNet, we adopted its annotation format and we extracted and converted all tables as PNG images with a resolution of 72 dpi. Additionally, we have filtered out tables with extreme sizes due to small amount of such tables, and kept only those ones ranging between 1*1 and 20*10 (rows/columns). + +The availability of the bounding boxes for all table cells is essential to train our models. In order to distinguish between empty and non-empty bounding boxes, we have introduced a binary class in the annotation. Unfortunately, the original datasets either omit the bounding boxes for whole tables (e.g. TableBank) or they narrow their scope only to non-empty cells. Therefore, it was imperative to introduce a data pre-processing procedure that generates the missing bounding boxes out of the annotation information. This procedure first parses the provided table structure and calculates the dimensions of the most fine-grained grid that covers the table structure. Notice that each table cell may occupy multiple grid squares due to row or column spans. In case of PubTabNet we had to compute missing bounding boxes for 48% of the simple and 69% of the complex tables. Regarding FinTabNet, 68% of the simple and 98% of the complex tables require the generation of bounding boxes. + +As it is illustrated in Fig. 2, the table distributions from all datasets are skewed towards simpler structures with fewer number of rows/columns. Additionally, there is very limited variance in the table styles, which in case of PubTabNet and FinTabNet means one styling format for the majority of the tables. Similar limitations appear also in the type of table content, which in some cases (e.g. FinTabNet) is restricted to a certain domain. Ultimately, the lack of diversity in the training dataset damages the ability of the models to generalize well on unseen data. + +Motivated by those observations we aimed at generating a synthetic table dataset named SynthTabNet . This approach offers control over: 1) the size of the dataset, 2) the table structure, 3) the table style and 4) the type of content. The complexity of the table structure is described by the size of the table header and the table body, as well as the percentage of the table cells covered by row spans and column spans. A set of carefully designed styling templates provides the basis to build a wide range of table appearances. Lastly, the table content is generated out of a curated collection of text corpora. By controlling the size and scope of the synthetic datasets we are able to train and evaluate our models in a variety of different conditions. For example, we can first generate a highly diverse dataset to train our models and then evaluate their performance on other synthetic datasets which are focused on a specific domain. + +In this regard, we have prepared four synthetic datasets, each one containing 150k examples. The corpora to generate the table text consists of the most frequent terms appearing in PubTabNet and FinTabNet together with randomly generated text. The first two synthetic datasets have been fine-tuned to mimic the appearance of the original datasets but encompass more complicated table structures. The third + +| | Tags | Bbox | Size | Format | +|--------------------|--------|--------|--------|----------| +| PubTabNet | ✓ | ✓ | 509k | PNG | +| FinTabNet | ✓ | ✓ | 1 12k | PDF | +| TableBank | ✓ | ✗ | 145k | JPEG | +| Combined-Tabnet(*) | ✓ | ✓ | 400k | PNG | +| Combined(**) | ✓ | ✓ | 500k | PNG | +| SynthTabNet | ✓ | ✓ | 600k | PNG | + +Table 1: Both "Combined-Tabnet" and "CombinedTabnet" are variations of the following: (*) The CombinedTabnet dataset is the processed combination of PubTabNet and Fintabnet. (**) The combined dataset is the processed combination of PubTabNet, Fintabnet and TableBank. + +one adopts a colorful appearance with high contrast and the last one contains tables with sparse content. Lastly, we have combined all synthetic datasets into one big unified synthetic dataset of 600k examples. + +Tab. 1 summarizes the various attributes of the datasets. + +## 4. The TableFormer model + +Given the image of a table, TableFormer is able to predict: 1) a sequence of tokens that represent the structure of a table, and 2) a bounding box coupled to a subset of those tokens. The conversion of an image into a sequence of tokens is a well-known task [35, 16]. While attention is often used as an implicit method to associate each token of the sequence with a position in the original image, an explicit association between the individual table-cells and the image bounding boxes is also required. + +## 4.1. Model architecture. + +We now describe in detail the proposed method, which is composed of three main components, see Fig. 4. Our CNN Backbone Network encodes the input as a feature vector of predefined length. The input feature vector of the encoded image is passed to the Structure Decoder to produce a sequence of HTML tags that represent the structure of the table. With each prediction of an HTML standard data cell (' < td > ') the hidden state of that cell is passed to the Cell BBox Decoder. As for spanning cells, such as row or column span, the tag is broken down to ' < ', 'rowspan=' or 'colspan=', with the number of spanning cells (attribute), and ' > '. The hidden state attached to ' < ' is passed to the Cell BBox Decoder. A shared feed forward network (FFN) receives the hidden states from the Structure Decoder, to provide the final detection predictions of the bounding box coordinates and their classification. + +CNN Backbone Network. A ResNet-18 CNN is the backbone that receives the table image and encodes it as a vector of predefined length. The network has been modified by removing the linear and pooling layer, as we are not per + +Figure 3: TableFormer takes in an image of the PDF and creates bounding box and HTML structure predictions that are synchronized. The bounding boxes grabs the content from the PDF and inserts it in the structure. + + + +Figure 4: Given an input image of a table, the Encoder produces fixed-length features that represent the input image. The features are then passed to both the Structure Decoder and Cell BBox Decoder . During training, the Structure Decoder receives 'tokenized tags' of the HTML code that represent the table structure. Afterwards, a transformer encoder and decoder architecture is employed to produce features that are received by a linear layer, and the Cell BBox Decoder. The linear layer is applied to the features to predict the tags. Simultaneously, the Cell BBox Decoder selects features referring to the data cells (' < td > ', ' < ') and passes them through an attention network, an MLP, and a linear layer to predict the bounding boxes. + + + +forming classification, and adding an adaptive pooling layer of size 28*28. ResNet by default downsamples the image resolution by 32 and then the encoded image is provided to both the Structure Decoder , and Cell BBox Decoder . + +Structure Decoder. The transformer architecture of this component is based on the work proposed in [31]. After extensive experimentation, the Structure Decoder is modeled as a transformer encoder with two encoder layers and a transformer decoder made from a stack of 4 decoder layers that comprise mainly of multi-head attention and feed forward layers. This configuration uses fewer layers and heads in comparison to networks applied to other problems (e.g. "Scene Understanding", "Image Captioning"), something which we relate to the simplicity of table images. + +The transformer encoder receives an encoded image from the CNN Backbone Network and refines it through a multi-head dot-product attention layer, followed by a Feed Forward Network. During training, the transformer decoder receives as input the output feature produced by the transformer encoder, and the tokenized input of the HTML ground-truth tags. Using a stack of multi-head attention layers, different aspects of the tag sequence could be inferred. This is achieved by each attention head on a layer operating in a different subspace, and then combining altogether their attention score. + +Cell BBox Decoder. Our architecture allows to simultaneously predict HTML tags and bounding boxes for each table cell without the need of a separate object detector end to end. This approach is inspired by DETR [1] which employs a Transformer Encoder, and Decoder that looks for a specific number of object queries (potential object detections). As our model utilizes a transformer architecture, the hidden state of the < td > ' and ' < ' HTML structure tags become the object query. + +The encoding generated by the CNN Backbone Network along with the features acquired for every data cell from the Transformer Decoder are then passed to the attention network. The attention network takes both inputs and learns to provide an attention weighted encoding. This weighted at tention encoding is then multiplied to the encoded image to produce a feature for each table cell. Notice that this is different than the typical object detection problem where imbalances between the number of detections and the amount of objects may exist. In our case, we know up front that the produced detections always match with the table cells in number and correspondence. + +The output features for each table cell are then fed into the feed-forward network (FFN). The FFN consists of a Multi-Layer Perceptron (3 layers with ReLU activation function) that predicts the normalized coordinates for the bounding box of each table cell. Finally, the predicted bounding boxes are classified based on whether they are empty or not using a linear layer. + +Loss Functions. We formulate a multi-task loss Eq. 2 to train our network. The Cross-Entropy loss (denoted as l s ) is used to train the Structure Decoder which predicts the structure tokens. As for the Cell BBox Decoder it is trained with a combination of losses denoted as l box . l box consists of the generally used l 1 loss for object detection and the IoU loss ( l ) to be scale invariant as explained in [25]. In iou comparison to DETR, we do not use the Hungarian algorithm [15] to match the predicted bounding boxes with the ground-truth boxes, as we have already achieved a one-toone match through two steps: 1) Our token input sequence is naturally ordered, therefore the hidden states of the table data cells are also in order when they are provided as input to the Cell BBox Decoder , and 2) Our bounding boxes generation mechanism (see Sec. 3) ensures a one-to-one mapping between the cell content and its bounding box for all post-processed datasets. + +The loss used to train the TableFormer can be defined as following: + + + +where λ ∈ [0, 1], and λ , λ ∈ R are hyper-parameters. iou l 1 + +## 5. Experimental Results + +## 5.1. Implementation Details + +TableFormer uses ResNet-18 as the CNN Backbone Network . The input images are resized to 448*448 pixels and the feature map has a dimension of 28*28. Additionally, we enforce the following input constraints: + + + +Although input constraints are used also by other methods, such as EDD, ours are less restrictive due to the improved runtime performance and lower memory footprint of TableFormer. This allows to utilize input samples with longer sequences and images with larger dimensions. + +The Transformer Encoder consists of two "Transformer Encoder Layers", with an input feature size of 512, feed forward network of 1024, and 4 attention heads. As for the Transformer Decoder it is composed of four "Transformer Decoder Layers" with similar input and output dimensions as the "Transformer Encoder Layers". Even though our model uses fewer layers and heads than the default implementation parameters, our extensive experimentation has proved this setup to be more suitable for table images. We attribute this finding to the inherent design of table images, which contain mostly lines and text, unlike the more elaborate content present in other scopes (e.g. the COCO dataset). Moreover, we have added ResNet blocks to the inputs of the Structure Decoder and Cell BBox Decoder. This prevents a decoder having a stronger influence over the learned weights which would damage the other prediction task (structure vs bounding boxes), but learn task specific weights instead. Lastly our dropout layers are set to 0.5. + +For training, TableFormer is trained with 3 Adam optimizers, each one for the CNN Backbone Network , Structure Decoder , and Cell BBox Decoder . Taking the PubTabNet as an example for our parameter set up, the initializing learning rate is 0.001 for 12 epochs with a batch size of 24, and λ set to 0.5. Afterwards, we reduce the learning rate to 0.0001, the batch size to 18 and train for 12 more epochs or convergence. + +TableFormer is implemented with PyTorch and Torchvision libraries [22]. To speed up the inference, the image undergoes a single forward pass through the CNN Backbone Network and transformer encoder. This eliminates the overhead of generating the same features for each decoding step. Similarly, we employ a 'caching' technique to preform faster autoregressive decoding. This is achieved by storing the features of decoded tokens so we can reuse them for each time step. Therefore, we only compute the attention for each new tag. + +## 5.2. Generalization + +TableFormer is evaluated on three major publicly available datasets of different nature to prove the generalization and effectiveness of our model. The datasets used for evaluation are the PubTabNet, FinTabNet and TableBank which stem from the scientific, financial and general domains respectively. + +We also share our baseline results on the challenging SynthTabNet dataset. Throughout our experiments, the same parameters stated in Sec. 5.1 are utilized. + +## 5.3. Datasets and Metrics + +The Tree-Edit-Distance-Based Similarity (TEDS) metric was introduced in [37]. It represents the prediction, and ground-truth as a tree structure of HTML tags. This similarity is calculated as: + + + +where T and T represent tables in tree structure HTML format. EditDist denotes the tree-edit distance, and a b | T | represents the number of nodes in T . + +## 5.4. Quantitative Analysis + +Structure. As shown in Tab. 2, TableFormer outperforms all SOTA methods across different datasets by a large margin for predicting the table structure from an image. All the more, our model outperforms pre-trained methods. During the evaluation we do not apply any table filtering. We also provide our baseline results on the SynthTabNet dataset. It has been observed that large tables (e.g. tables that occupy half of the page or more) yield poor predictions. We attribute this issue to the image resizing during the preprocessing step, that produces downsampled images with indistinguishable features. This problem can be addressed by treating such big tables with a separate model which accepts a large input image size. + +| Model | Dataset | Simple | TEDS Complex | All | +|-------------|-----------|----------|----------------|-------| +| EDD | PTN | 91.1 | 88.7 | 89.9 | +| GTE | PTN | - | - | 93.01 | +| TableFormer | PTN | 98.5 | 95.0 | 96.75 | +| EDD | FTN | 88.4 | 92.08 | 90.6 | +| GTE | FTN | - | - | 87.14 | +| GTE (FT) | FTN | - | - | 91.02 | +| TableFormer | FTN | 97.5 | 96.0 | 96.8 | +| EDD | TB | 86.0 | - | 86.0 | +| TableFormer | TB | 89.6 | - | 89.6 | +| TableFormer | STN | 96.9 | 95.7 | 96.7 | + +Table 2: Structure results on PubTabNet (PTN), FinTabNet (FTN), TableBank (TB) and SynthTabNet (STN). + +FT: Model was trained on PubTabNet then finetuned. + +Cell Detection. Like any object detector, our Cell BBox Detector provides bounding boxes that can be improved with post-processing during inference. We make use of the grid-like structure of tables to refine the predictions. A detailed explanation on the post-processing is available in the supplementary material. As shown in Tab. 3, we evaluate our Cell BBox Decoder accuracy for cells with a class label of 'content' only using the PASCAL VOC mAP metric for pre-processing and post-processing. Note that we do not have post-processing results for SynthTabNet as images are only provided. To compare the performance of our proposed approach, we've integrated TableFormer's Cell BBox Decoder into EDD architecture. As mentioned previously, the Structure Decoder provides the Cell BBox Decoder with the features needed to predict the bounding box predictions. Therefore, the accuracy of the Structure Decoder directly influences the accuracy of the Cell BBox Decoder . If the Structure Decoder predicts an extra column, this will result in an extra column of predicted bounding boxes. + +| Model | Dataset | mAP | mAP (PP) | +|-------------|-------------|-------|------------| +| EDD+BBox | PubTabNet | 79.2 | 82.7 | +| TableFormer | PubTabNet | 82.1 | 86.8 | +| TableFormer | SynthTabNet | 87.7 | - | + +Table 3: Cell Bounding Box detection results on PubTabNet, and FinTabNet. PP: Post-processing. + +Cell Content. In this section, we evaluate the entire pipeline of recovering a table with content. Here we put our approach to test by capitalizing on extracting content from the PDF cells rather than decoding from images. Tab. 4 shows the TEDs score of HTML code representing the structure of the table along with the content inserted in the data cell and compared with the ground-truth. Our method achieved a 5.3% increase over the state-of-the-art, and commercial solutions. We believe our scores would be higher if the HTML ground-truth matched the extracted PDF cell content. Unfortunately, there are small discrepancies such as spacings around words or special characters with various unicode representations. + +| Model | Simple | TEDS Complex | All | +|-------------|----------|----------------|-------| +| Tabula | 78.0 | 57.8 | 67.9 | +| Traprange | 60.8 | 49.9 | 55.4 | +| Camelot | 80.0 | 66.0 | 73.0 | +| Acrobat Pro | 68.9 | 61.8 | 65.3 | +| EDD | 91.2 | 85.4 | 88.3 | +| TableFormer | 95.4 | 90.1 | 93.6 | + +Table 4: Results of structure with content retrieved using cell detection on PubTabNet. In all cases the input is PDF documents with cropped tables. + +- a. Red - PDF cells, Green - predicted bounding boxes, Blue - post-processed predictions matched to PDF cells Japanese language (previously unseen by TableFormer): Example table from FinTabNet: + +Japanese language (previously unseen by TableFormer): Example table from FinTabNet: + +Figure 5: One of the benefits of TableFormer is that it is language agnostic, as an example, the left part of the illustration demonstrates TableFormer predictions on previously unseen language (Japanese). Additionally, we see that TableFormer is robust to variability in style and content, right side of the illustration shows the example of the TableFormer prediction from the FinTabNet dataset. + + + +- b. Structure predicted by TableFormer, with superimposed matched PDF cell text: + +| | RSUsShares (in millions) | RSUsShares (in millions) | viewingWeighted Average Grant Date Fair Value | viewingWeighted Average Grant Date Fair Value | +|--------------------------|----------------------------|----------------------------|-------------------------------------------------|-------------------------------------------------| +| | | PSUs | RSUs | PSUs | +| Nonvested on January 1 | 1.1 | 0.3 | 90.1 0 $ | $ 91.1 9 | +| Granted | 0.5 | 0.1 | 1 1 7.44 | 1 22.41 | +| Vested | (0.5) | (0.1) | 87.08 | 81.14 | +| Canceled or forfeited | (0.1) | — | 102.01 | 92.18 | +| Nonvested on December 31 | 1.0 | 0.3 | 1 04.85 $ | $ 1 04.51 | + +| | | 論文フ ァ イ ル | 論文フ ァ イ ル | 参考文献 | 参考文献 | +|----------------------------------------------------|----------|-------------|-------------|--------|--------| +| 出典 | フ ァ イ ル数 | 英語 | 日本語 | 英語 | 日本語 | +| Association for Computational Linguistics(ACL2003) | 65 | 65 | 0 | 150 | 0 | +| Computational Linguistics(COLING2002) | 140 | 140 | 0 | 150 | 0 | +| 電気情報通信学会2003年総合大会 | 150 | 8 | 142 | 223 | 147 | +| 情報処理学会第65回全国大会(2003) | 177 | 1 | 176 | 150 | 236 | +| 第17回人工知能学会全国大会(2003) | 208 | 5 | 203 | 152 | 244 | +| 自然言語処理研究会第146〜155回 | 98 | 2 | 96 | 150 | 232 | +| WWWから収集 した論文 | 107 | 73 | 34 | 147 | 96 | +| 計 | 945 | 294 | 651 | 1122 | 955 | + + + +Text is aligned to match original for ease of viewing + +Figure 6: An example of TableFormer predictions (bounding boxes and structure) from generated SynthTabNet table. + + + +## 6. Future Work & Conclusion + +## 5.5. Qualitative Analysis + +In this paper, we presented TableFormer an end-to-end transformer based approach to predict table structures and bounding boxes of cells from an image. This approach enables us to recreate the table structure, and extract the cell content from PDF or OCR by using bounding boxes. Additionally, it provides the versatility required in real-world scenarios when dealing with various types of PDF documents, and languages. Furthermore, our method outperforms all state-of-the-arts with a wide margin. Finally, we introduce "SynthTabNet" a challenging synthetically generated dataset that reinforces missing characteristics from other datasets. + +We showcase several visualizations for the different components of our network on various "complex" tables within datasets presented in this work in Fig. 5 and Fig. 6 As it is shown, our model is able to predict bounding boxes for all table cells, even for the empty ones. Additionally, our post-processing techniques can extract the cell content by matching the predicted bounding boxes to the PDF cells based on their overlap and spatial proximity. The left part of Fig. 5 demonstrates also the adaptability of our method to any language, as it can successfully extract Japanese text, although the training set contains only English content. We provide more visualizations including the intermediate steps in the supplementary material. Overall these illustrations justify the versatility of our method across a diverse range of table appearances and content type. + +## References + +- [1] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to + +end object detection with transformers. In Andrea Vedaldi, Horst Bischof, Thomas Brox, and Jan-Michael Frahm, editors, Computer Vision - ECCV 2020 , pages 213-229, Cham, 2020. Springer International Publishing. 5 + +- [2] Zewen Chi, Heyan Huang, Heng-Da Xu, Houjin Yu, Wanxuan Yin, and Xian-Ling Mao. Complicated table structure recognition. arXiv preprint arXiv:1908.04729 , 2019. 3 +- [3] Bertrand Couasnon and Aurelie Lemaitre. Recognition ofTables and Forms , pages 647-677. Springer London, London, 2014. 2 +- [4] Herve D ´ ejean, Jean-Luc Meunier, Liangcai Gao, Yilun ´ Huang, Yu Fang, Florian Kleber, and Eva-Maria Lang. ICDAR 2019 Competition on Table Detection and Recognition (cTDaR), Apr. 2019. http://sac.founderit.com/. 2 +- [5] Basilios Gatos, Dimitrios Danatsas, Ioannis Pratikakis, and Stavros J Perantonis. Automatic table detection in document images. In International Conference on Pattern Recognition and Image Analysis , pages 609-618. Springer, 2005. 2 +- [6] Max Gobel, Tamir Hassan, Ermelinda Oro, and Giorgio Orsi. ¨ Icdar 2013 table competition. In 2013 12th International Conference on Document Analysis and Recognition , pages 1449-1453, 2013. 2 +- [7] EA Green and M Krishnamoorthy. Recognition of tables using table grammars. procs. In Symposium on Document Analysis and Recognition (SDAIR'95) , pages 261-277. 2 +- [8] Khurram Azeem Hashmi, Alain Pagani, Marcus Liwicki, Didier Stricker, and Muhammad Zeshan Afzal. Castabdetectors: Cascade network for table detection in document images with recursive feature pyramid and switchable atrous convolution. Journal of Imaging , 7(10), 2021. 1 +- [9] Kaiming He, Georgia Gkioxari, Piotr Dollar, and Ross Girshick. Mask r-cnn. In Proceedings of the IEEE International Conference on Computer Vision (ICCV) , Oct 2017. 1 +- [10] Yelin He, X. Qi, Jiaquan Ye, Peng Gao, Yihao Chen, Bingcong Li, Xin Tang, and Rong Xiao. Pingan-vcgroup's solution for icdar 2021 competition on scientific table image recognition to latex. ArXiv , abs/2105.01846, 2021. 2 +- [11] Jianying Hu, Ramanujan S Kashi, Daniel P Lopresti, and Gordon Wilfong. Medium-independent table detection. In Document Recognition and Retrieval VII , volume 3967, pages 291-302. International Society for Optics and Photonics, 1999. 2 +- [12] Matthew Hurst. A constraint-based approach to table structure derivation. In Proceedings of the Seventh International Conference on Document Analysis and Recognition - Volume 2 , ICDAR '03, page 911, USA, 2003. IEEE Computer Society. 2 +- [13] Thotreingam Kasar, Philippine Barlas, Sebastien Adam, Clement Chatelain, and Thierry Paquet. Learning to detect ´ tables in scanned document images using line information. In 2013 12th International Conference on Document Analysis and Recognition , pages 1185-1189. IEEE, 2013. 2 +- [14] Pratik Kayal, Mrinal Anand, Harsh Desai, and Mayank Singh. Icdar 2021 competition on scientific table image recognition to latex, 2021. 2 +- [15] Harold W Kuhn. The hungarian method for the assignment problem. Naval research logistics quarterly , 2(1-2):83-97, 1955. 6 +- [16] Girish Kulkarni, Visruth Premraj, Vicente Ordonez, Sagnik Dhar, Siming Li, Yejin Choi, Alexander C. Berg, and Tamara L. Berg. Babytalk: Understanding and generating simple image descriptions. IEEE Transactions on Pattern Analysis and Machine Intelligence , 35(12):2891-2903, 2013. 4 +- [17] Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, Ming Zhou, and Zhoujun Li. Tablebank: A benchmark dataset for table detection and recognition, 2019. 2, 3 +- [18] Yiren Li, Zheng Huang, Junchi Yan, Yi Zhou, Fan Ye, and Xianhui Liu. Gfte: Graph-based financial table extraction. In Alberto Del Bimbo, Rita Cucchiara, Stan Sclaroff, Giovanni Maria Farinella, Tao Mei, Marco Bertini, Hugo Jair Escalante, and Roberto Vezzani, editors, Pattern Recognition. ICPR International Workshops and Challenges , pages 644-658, Cham, 2021. Springer International Publishing. 2, 3 +- [19] Nikolaos Livathinos, Cesar Berrospi, Maksym Lysak, Viktor Kuropiatnyk, Ahmed Nassar, Andre Carvalho, Michele Dolfi, Christoph Auer, Kasper Dinkla, and Peter Staar. Robust pdf document conversion using recurrent neural networks. Proceedings of the AAAI Conference on Artificial Intelligence , 35(17):15137-15145, May 2021. 1 +- [20] Rujiao Long, Wen Wang, Nan Xue, Feiyu Gao, Zhibo Yang, Yongpan Wang, and Gui-Song Xia. Parsing table structures in the wild. In Proceedings of the IEEE/CVF International Conference on Computer Vision , pages 944-952, 2021. 2 +- [21] Shubham Singh Paliwal, D Vishwanath, Rohit Rahul, Monika Sharma, and Lovekesh Vig. Tablenet: Deep learning model for end-to-end table detection and tabular data extraction from scanned document images. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 128-133. IEEE, 2019. 1 +- [22] Adam Paszke, Sam Gross, Francisco Massa, Adam Lerer, James Bradbury, Gregory Chanan, Trevor Killeen, Zeming Lin, Natalia Gimelshein, Luca Antiga, Alban Desmaison, Andreas Kopf, Edward Yang, Zachary DeVito, Martin Raison, Alykhan Tejani, Sasank Chilamkurthy, Benoit Steiner, Lu Fang, Junjie Bai, and Soumith Chintala. Pytorch: An imperative style, high-performance deep learning library. In H. Wallach, H. Larochelle, A. Beygelzimer, F. d'Alche-Buc, E. ´ Fox, and R. Garnett, editors, Advances in Neural Information Processing Systems 32 , pages 8024-8035. Curran Associates, Inc., 2019. 6 +- [23] Devashish Prasad, Ayan Gadpal, Kshitij Kapadni, Manish Visave, and Kavita Sultanpure. Cascadetabnet: An approach for end to end table detection and structure recognition from image-based documents. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition Workshops , pages 572-573, 2020. 1 +- [24] Shah Rukh Qasim, Hassan Mahmood, and Faisal Shafait. Rethinking table recognition using graph neural networks. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 142-147. IEEE, 2019. 3 +- [25] Hamid Rezatofighi, Nathan Tsoi, JunYoung Gwak, Amir Sadeghian, Ian Reid, and Silvio Savarese. Generalized intersection over union: A metric and a loss for bounding box regression. In Proceedings of the IEEE/CVF Conference on + +Computer Vision and Pattern Recognition , pages 658-666, 2019. 6 + +- [26] Sebastian Schreiber, Stefan Agne, Ivo Wolf, Andreas Dengel, and Sheraz Ahmed. Deepdesrt: Deep learning for detection and structure recognition of tables in document images. In 2017 14th IAPR International Conference on Document Analysis and Recognition (ICDAR) , volume 01, pages 1162- 1167, 2017. 1 +- [27] Sebastian Schreiber, Stefan Agne, Ivo Wolf, Andreas Dengel, and Sheraz Ahmed. Deepdesrt: Deep learning for detection and structure recognition of tables in document images. In 2017 14th IAPR international conference on document analysis and recognition (ICDAR) , volume 1, pages 1162-1167. IEEE, 2017. 3 +- [28] Faisal Shafait and Ray Smith. Table detection in heterogeneous documents. In Proceedings of the 9th IAPR International Workshop on Document Analysis Systems , pages 65- 72, 2010. 2 +- [29] Shoaib Ahmed Siddiqui, Imran Ali Fateh, Syed Tahseen Raza Rizvi, Andreas Dengel, and Sheraz Ahmed. Deeptabstr: Deep learning based table structure recognition. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 1403-1409. IEEE, 2019. 3 +- [30] Peter W J Staar, Michele Dolfi, Christoph Auer, and Costas Bekas. Corpus conversion service: A machine learning platform to ingest documents at scale. In Proceedings of the 24th ACM SIGKDD , KDD '18, pages 774-782, New York, NY, USA, 2018. ACM. 1 +- [31] Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Ł ukasz Kaiser, and Illia Polosukhin. Attention is all you need. In I. Guyon, U. V. Luxburg, S. Bengio, H. Wallach, R. Fergus, S. Vishwanathan, and R. Garnett, editors, Advances in Neural Information Processing Systems 30 , pages 5998-6008. Curran Associates, Inc., 2017. 5 +- [32] Oriol Vinyals, Alexander Toshev, Samy Bengio, and Dumitru Erhan. Show and tell: A neural image caption generator. In Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR) , June 2015. 2 +- [33] Wenyuan Xue, Qingyong Li, and Dacheng Tao. Res2tim: reconstruct syntactic structures from table images. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 749-755. IEEE, 2019. 3 +- [34] Wenyuan Xue, Baosheng Yu, Wen Wang, Dacheng Tao, and Qingyong Li. Tgrnet: A table graph reconstruction network for table structure recognition. arXiv preprint arXiv:2106.10598 , 2021. 3 +- [35] Quanzeng You, Hailin Jin, Zhaowen Wang, Chen Fang, and Jiebo Luo. Image captioning with semantic attention. In Proceedings of the IEEE conference on computer vision and pattern recognition , pages 4651-4659, 2016. 4 +- [36] Xinyi Zheng, Doug Burdick, Lucian Popa, Peter Zhong, and Nancy Xin Ru Wang. Global table extractor (gte): A framework for joint table identification and cell structure recognition using visual context. Winter Conferencefor Applications in Computer Vision (WACV) , 2021. 2, 3 +- [37] Xu Zhong, Elaheh ShafieiBavani, and Antonio Jimeno Yepes. Image-based table recognition: Data, model, +- and evaluation. In Andrea Vedaldi, Horst Bischof, Thomas Brox, and Jan-Michael Frahm, editors, Computer Vision - ECCV 2020 , pages 564-580, Cham, 2020. Springer International Publishing. 2, 3, 7 +- [38] Xu Zhong, Jianbin Tang, and Antonio Jimeno Yepes. Publaynet: Largest dataset ever for document layout analysis. In 2019 International Conference on Document Analysis and Recognition (ICDAR) , pages 1015-1022, 2019. 1 + +## TableFormer: Table Structure Understanding with Transformers Supplementary Material + +## TableFormer: Table Structure Understanding with Transformers + +Supplementary Material + +## 1. Details on the datasets + +## 1.1. Data preparation + +As a first step of our data preparation process, we have calculated statistics over the datasets across the following dimensions: (1) table size measured in the number of rows and columns, (2) complexity of the table, (3) strictness of the provided HTML structure and (4) completeness (i.e. no omitted bounding boxes). A table is considered to be simple if it does not contain row spans or column spans. Additionally, a table has a strict HTML structure if every row has the same number of columns after taking into account any row or column spans. Therefore a strict HTML structure looks always rectangular. However, HTML is a lenient encoding format, i.e. tables with rows of different sizes might still be regarded as correct due to implicit display rules. These implicit rules leave room for ambiguity, which we want to avoid. As such, we prefer to have "strict" tables, i.e. tables where every row has exactly the same length. + +We have developed a technique that tries to derive a missing bounding box out of its neighbors. As a first step, we use the annotation data to generate the most fine-grained grid that covers the table structure. In case of strict HTML tables, all grid squares are associated with some table cell and in the presence of table spans a cell extends across multiple grid squares. When enough bounding boxes are known for a rectangular table, it is possible to compute the geometrical border lines between the grid rows and columns. Eventually this information is used to generate the missing bounding boxes. Additionally, the existence of unused grid squares indicates that the table rows have unequal number of columns and the overall structure is non-strict. The generation of missing bounding boxes for non-strict HTML tables is ambiguous and therefore quite challenging. Thus, we have decided to simply discard those tables. In case of PubTabNet we have computed missing bounding boxes for 48% of the simple and 69% of the complex tables. Regarding FinTabNet, 68% of the simple and 98% of the complex tables require the generation of bounding boxes. + +Figure 7 illustrates the distribution of the tables across different dimensions per dataset. + +## 1.2. Synthetic datasets + +Aiming to train and evaluate our models in a broader spectrum of table data we have synthesized four types of datasets. Each one contains tables with different appear ances in regard to their size, structure, style and content. Every synthetic dataset contains 150k examples, summing up to 600k synthetic examples. All datasets are divided into Train, Test and Val splits (80%, 10%, 10%). + +The process of generating a synthetic dataset can be decomposed into the following steps: + +1. Prepare styling and content templates: The styling templates have been manually designed and organized into groups of scope specific appearances (e.g. financial data, marketing data, etc.) Additionally, we have prepared curated collections of content templates by extracting the most frequently used terms out of non-synthetic datasets (e.g. PubTabNet, FinTabNet, etc.). +2. Generate table structures: The structure of each synthetic dataset assumes a horizontal table header which potentially spans over multiple rows and a table body that may contain a combination of row spans and column spans. However, spans are not allowed to cross the header - body boundary. The table structure is described by the parameters: Total number of table rows and columns, number of header rows, type of spans (header only spans, row only spans, column only spans, both row and column spans), maximum span size and the ratio of the table area covered by spans. +3. Generate content: Based on the dataset theme , a set of suitable content templates is chosen first. Then, this content can be combined with purely random text to produce the synthetic content. +4. Apply styling templates: Depending on the domain of the synthetic dataset, a set of styling templates is first manually selected. Then, a style is randomly selected to format the appearance of the synthesized table. +5. Render the complete tables: The synthetic table is finally rendered by a web browser engine to generate the bounding boxes for each table cell. A batching technique is utilized to optimize the runtime overhead of the rendering process. + +## 2. Prediction post-processing for PDF documents + +Although TableFormer can predict the table structure and the bounding boxes for tables recognized inside PDF documents, this is not enough when a full reconstruction of the original table is required. This happens mainly due the following reasons: + +Figure 7: Distribution of the tables across different dimensions per dataset. Simple vs complex tables per dataset and split, strict vs non strict html structures per dataset and table complexity, missing bboxes per dataset and table complexity. + + + +- TableFormer output does not include the table cell content. +- There are occasional inaccuracies in the predictions of the bounding boxes. + +However, it is possible to mitigate those limitations by combining the TableFormer predictions with the information already present inside a programmatic PDF document. More specifically, PDF documents can be seen as a sequence of PDF cells where each cell is described by its content and bounding box. If we are able to associate the PDF cells with the predicted table cells, we can directly link the PDF cell content to the table cell structure and use the PDF bounding boxes to correct misalignments in the predicted table cell bounding boxes. + +Here is a step-by-step description of the prediction postprocessing: + +1. Get the minimal grid dimensions - number of rows and columns for the predicted table structure. This represents the most granular grid for the underlying table structure. +2. Generate pair-wise matches between the bounding boxes of the PDF cells and the predicted cells. The Intersection Over Union (IOU) metric is used to evaluate the quality of the matches. +3. Use a carefully selected IOU threshold to designate the matches as "good" ones and "bad" ones. + +3. a. If all IOU scores in a column are below the threshold, discard all predictions (structure and bounding boxes) for that column. +4. Find the best-fitting content alignment for the predicted cells with good IOU per each column. The alignment of the column can be identified by the following formula: + + + +where c is one of { left, centroid, right } and x c is the xcoordinate for the corresponding point. + +5. Use the alignment computed in step 4, to compute the median x -coordinate for all table columns and the me + +dian cell size for all table cells. The usage of median during the computations, helps to eliminate outliers caused by occasional column spans which are usually wider than the normal. + +6. Snap all cells with bad IOU to their corresponding median x -coordinates and cell sizes. +7. Generate a new set of pair-wise matches between the corrected bounding boxes and PDF cells. This time use a modified version of the IOU metric, where the area of the intersection between the predicted and PDF cells is divided by the PDF cell area. In case there are multiple matches for the same PDF cell, the prediction with the higher score is preferred. This covers the cases where the PDF cells are smaller than the area of predicted or corrected prediction cells. +8. In some rare occasions, we have noticed that TableFormer can confuse a single column as two. When the postprocessing steps are applied, this results with two predicted columns pointing to the same PDF column. In such case we must de-duplicate the columns according to highest total column intersection score. +9. Pick up the remaining orphan cells. There could be cases, when after applying all the previous post-processing steps, some PDF cells could still remain without any match to predicted cells. However, it is still possible to deduce the correct matching for an orphan PDF cell by mapping its bounding box on the geometry of the grid. This mapping decides if the content of the orphan cell will be appended to an already matched table cell, or a new table cell should be created to match with the orphan. + +- 9a. Compute the top and bottom boundary of the horizontal band for each grid row (min/max y coordinates per row). +- 9b. Intersect the orphan's bounding box with the row bands, and map the cell to the closest grid row. +- 9c. Compute the left and right boundary of the vertical band for each grid column (min/max x coordinates per column). +- 9d. Intersect the orphan's bounding box with the column bands, and map the cell to the closest grid column. + +9e. If the table cell under the identified row and column is not empty, extend its content with the content of the or phan cell. + +9f. Otherwise create a new structural cell and match it wit the orphan cell. + +Aditional images with examples of TableFormer predictions and post-processing can be found below. + +Figure 8: Example of a table with multi-line header. + + + +Figure 9: Example of a table with big empty distance between cells. + + + + + +Figure 10: Example of a complex table with empty cells. + +Figure 13: Table predictions example on colorful table. + + + +Figure 11: Simple table with different style and empty cells. + + + + + +Figure 14: Example with multi-line text. + + + +Figure 12: Simple table predictions and post processing. + + + +Figure 15: Example with triangular table. + + + +Figure 16: Example of how post-processing helps to restore mis-aligned bounding boxes prediction artifact. + +Figure 17: Example of long table. End-to-end example from initial PDF cells to prediction of bounding boxes, post processing and prediction of structure. + + diff --git a/tests/snapshots/pdf/sources/2206.01062.pdf.md b/tests/snapshots/pdf/sources/2206.01062.pdf.md new file mode 100644 index 00000000..dd800400 --- /dev/null +++ b/tests/snapshots/pdf/sources/2206.01062.pdf.md @@ -0,0 +1,328 @@ +## DocLayNet: A Large Human-Annotated Dataset for Document-Layout Analysis + +Birgit Pfitzmann IBM Research Rueschlikon, Switzerland bpf@zurich.ibm.com + +Ahmed S. Nassar IBM Research Rueschlikon, Switzerland ahn@zurich.ibm.com + +## ABSTRACT + +Accurate document layout analysis is a key requirement for highquality PDF document conversion. With the recent availability of public, large ground-truth datasets such as PubLayNet and DocBank, deep-learning models have proven to be very effective at layout detection and segmentation. While these datasets are of adequate size to train such models, they severely lack in layout variability since they are sourced from scientific article repositories such as PubMed and arXiv only. Consequently, the accuracy of the layout segmentation drops significantly when these models are applied on more challenging and diverse layouts. In this paper, we present DocLayNet , a new, publicly available, document-layout annotation dataset in COCO format. It contains 80863 manually annotated pages from diverse data sources to represent a wide variability in layouts. For each PDF page, the layout annotations provide labelled bounding-boxes with a choice of 11 distinct classes. DocLayNet also provides a subset of double- and triple-annotated pages to determine the inter-annotator agreement. In multiple experiments, we provide baseline accuracy scores (in mAP) for a set of popular object detection models. We also demonstrate that these models fall approximately 10% behind the inter-annotator agreement. Furthermore, we provide evidence that DocLayNet is of sufficient size. Lastly, we compare models trained on PubLayNet, DocBank and DocLayNet, showing that layout predictions of the DocLayNettrained models are more robust and thus the preferred choice for general-purpose document-layout analysis. + +## CCS CONCEPTS + +• Information systems → Document structure ; • Applied computing → Document analysis ; • Computing methodologies → Machine learning ; Computer vision ; Object detection ; + +Permission to make digital or hard copies of part or all of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. Copyrights for third-party components of this work must be honored. For all other uses, contact the owner/author(s). + +KDD '22, August 14-18, 2022, Washington, DC, USA + +© 2022 Copyright held by the owner/author(s). + +ACM ISBN 978-1-4503-9385-0/22/08. + +https://doi.org/10.1145/3534678.3539043 + +Michele Dolfi IBM Research Rueschlikon, Switzerland dol@zurich.ibm.com + +Christoph Auer IBM Research Rueschlikon, Switzerland cau@zurich.ibm.com + +Peter Staar IBM Research Rueschlikon, Switzerland taa@zurich.ibm.com + + + +Figure 1: Four examples of complex page layouts across different document categories + + + + + + + + + +## KEYWORDS + +PDF document conversion, layout segmentation, object-detection, data set, Machine Learning + +## ACM Reference Format: + +Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar. 2022. DocLayNet: A Large Human-Annotated Dataset for DocumentLayout Analysis. In Proceedings of the 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining (KDD '22), August 14-18, 2022, Washington, DC, USA. ACM, New York, NY, USA, 9 pages. https://doi.org/10.1145/ 3534678.3539043 + +KDD '22, August 14-18, 2022, Washington, DC, USA Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar + +## 1 INTRODUCTION + +Despite the substantial improvements achieved with machine-learning (ML) approaches and deep neural networks in recent years, document conversion remains a challenging problem, as demonstrated by the numerous public competitions held on this topic [1-4]. The challenge originates from the huge variability in PDF documents regarding layout, language and formats (scanned, programmatic or a combination of both). Engineering a single ML model that can be applied on all types of documents and provides high-quality layout segmentation remains to this day extremely challenging [5]. To highlight the variability in document layouts, we show a few example documents from the DocLayNet dataset in Figure 1. + +A key problem in the process of document conversion is to understand the structure of a single document page, i.e. which segments of text should be grouped together in a unit. To train models for this task, there are currently two large datasets available to the community, PubLayNet [6] and DocBank [7]. They were introduced in 2019 and 2020 respectively and significantly accelerated the implementation of layout detection and segmentation models due to their sizes of 300K and 500K ground-truth pages. These sizes were achieved by leveraging an automation approach. The benefit of automated ground-truth generation is obvious: one can generate large ground-truth datasets at virtually no cost. However, the automation introduces a constraint on the variability in the dataset, because corresponding structured source data must be available. PubLayNet and DocBank were both generated from scientific document repositories (PubMed and arXiv), which provide XML or LATEX sources. Those scientific documents present a limited variability in their layouts, because they are typeset in uniform templates provided by the publishers. Obviously, documents such as technical manuals, annual company reports, legal text, government tenders, etc. have very different and partially unique layouts. As a consequence, the layout predictions obtained from models trained on PubLayNet or DocBank is very reasonable when applied on scientific documents. However, for more artistic or free-style layouts, we see sub-par prediction quality from these models, which we demonstrate in Section 5. + +In this paper, we present the DocLayNet dataset. It provides pageby-page layout annotation ground-truth using bounding-boxes for 11 distinct class labels on 80863 unique document pages, of which a fraction carry double- or triple-annotations. DocLayNet is similar in spirit to PubLayNet and DocBank and will likewise be made available to the public 1 in order to stimulate the document-layout analysis community. It distinguishes itself in the following aspects: + +- (1) Human Annotation : In contrast to PubLayNet and DocBank, we relied on human annotation instead of automation approaches to generate the data set. +- (2) Large Layout Variability : We include diverse and complex layouts from a large variety of public sources. +- (3) Detailed Label Set : We define 11 class labels to distinguish layout features in high detail. PubLayNet provides 5 labels; DocBank provides 13, although not a superset of ours. +- (4) Redundant Annotations : A fraction of the pages in the DocLayNet data set carry more than one human annotation. + +1 https://developer.ibm.com/exchanges/data/all/doclaynet + +This enables experimentation with annotation uncertainty and quality control analysis. + +- (5) Pre-defined Train-, Test- & Validation-set : Like DocBank, we provide fixed train-, test- & validation-sets to ensure proportional representation of the class-labels. Further, we prevent leakage of unique layouts across sets, which has a large effect on model accuracy scores. + +All aspects outlined above are detailed in Section 3. In Section 4, we will elaborate on how we designed and executed this large-scale human annotation campaign. We will also share key insights and lessons learned that might prove helpful for other parties planning to set up annotation campaigns. + +In Section 5, we will present baseline accuracy numbers for a variety of object detection methods (Faster R-CNN, Mask R-CNN and YOLOv5) trained on DocLayNet. We further show how the model performance is impacted by varying the DocLayNet dataset size, reducing the label set and modifying the train/test-split. Last but not least, we compare the performance of models trained on PubLayNet, DocBank and DocLayNet and demonstrate that a model trained on DocLayNet provides overall more robust layout recovery. + +## 2 RELATED WORK + +While early approaches in document-layout analysis used rulebased algorithms and heuristics [8], the problem is lately addressed with deep learning methods. The most common approach is to leverage object detection models [9-15]. In the last decade, the accuracy and speed of these models has increased dramatically. Furthermore, most state-of-the-art object detection methods can be trained and applied with very little work, thanks to a standardisation effort of the ground-truth data format [16] and common deep-learning frameworks [17]. Reference data sets such as PubLayNet [6] and DocBank provide their data in the commonly accepted COCO format [16]. + +Lately, new types of ML models for document-layout analysis have emerged in the community [18-21]. These models do not approach the problem of layout analysis purely based on an image representation of the page, as computer vision methods do. Instead, they combine the text tokens and image representation of a page in order to obtain a segmentation. While the reported accuracies appear to be promising, a broadly accepted data format which links geometric and textual features has yet to establish. + +## 3 THE DOCLAYNET DATASET + +DocLayNet contains 80863 PDF pages. Among these, 7059 carry two instances of human annotations, and 1591 carry three. This amounts to 91104 total annotation instances. The annotations provide layout information in the shape of labeled, rectangular boundingboxes. We define 11 distinct labels for layout features, namely Caption , Footnote , Formula , List-item , Page-footer , Page-header , Picture , Section-header , Table , Text , and Title . Our reasoning for picking this particular label set is detailed in Section 4. + +In addition to open intellectual property constraints for the source documents, we required that the documents in DocLayNet adhere to a few conditions. Firstly, we kept scanned documents + +Figure 2: Distribution of DocLayNet pages across document categories. + + + +to a minimum, since they introduce difficulties in annotation (see Section 4). As a second condition, we focussed on medium to large documents ( > 10 pages) with technical content, dense in complex tables, figures, plots and captions. Such documents carry a lot of information value, but are often hard to analyse with high accuracy due to their challenging layouts. Counterexamples of documents not included in the dataset are receipts, invoices, hand-written documents or photographs showing "text in the wild". + +The pages in DocLayNet can be grouped into six distinct categories, namely Financial Reports , Manuals , Scientific Articles , Laws & Regulations , Patents and Government Tenders . Each document category was sourced from various repositories. For example, Financial format annual reports2 Reports contain both free-style which expose company-specific, artistic layouts as well as the more formal SEC filings. The two largest categories ( Financial Reports and Manuals ) contain a large amount of free-style layouts in order to obtain maximum variability. In the other four categories, we boosted the variability by mixing documents from independent providers, such as different government websites or publishers. In Figure 2, we show the document categories contained in DocLayNet with their respective sizes. + +We did not control the document selection with regard to language. The vast majority of documents contained in DocLayNet (close to 95%) are published in English language. However, DocLayNet also contains a number of documents in other languages such as German (2.5%), French (1.0%) and Japanese (1.0%). While the document language has negligible impact on the performance of computer vision methods such as object detection and segmentation models, it might prove challenging for layout analysis methods which exploit textual features. + +To ensure that future benchmarks in the document-layout analysis community can be easily compared, we have split up DocLayNet into pre-defined train-, test- and validation-sets. In this way, we can avoid spurious variations in the evaluation scores due to random splitting in train-, test- and validation-sets. We also ensured that less frequent labels are represented in train and test sets in equal proportions. + +2e.g. AAPL from https://www.annualreports.com/ + +Table 1 shows the overall frequency and distribution of the labels among the different sets. Importantly, we ensure that subsets are only split on full-document boundaries. This avoids that pages of the same document are spread over train, test and validation set, which can give an undesired evaluation advantage to models and lead to overestimation of their prediction accuracy. We will show the impact of this decision in Section 5. + +In order to accommodate the different types of models currently in use by the community, we provide DocLayNet in an augmented COCO format [16]. This entails the standard COCO ground-truth file (in JSON format) with the associated page images (in PNG format, 1025 × 1025 pixels). Furthermore, custom fields have been added to each COCO record to specify document category, original document filename and page number. In addition, we also provide the original PDF pages, as well as sidecar files containing parsed PDF text and text-cell coordinates (in JSON). All additional files are linked to the primary page images by their matching filenames. + +Despite being cost-intense and far less scalable than automation, human annotation has several benefits over automated groundtruth generation. The first and most obvious reason to leverage human annotations is the freedom to annotate any type of document without requiring a programmatic source. For most PDF documents, the original source document is not available. The latter is not a hard constraint with human annotation, but it is for automated methods. A second reason to use human annotations is that the latter usually provide a more natural interpretation of the page layout. The human-interpreted layout can significantly deviate from the programmatic layout used in typesetting. For example, "invisible" tables might be used solely for aligning text paragraphs on columns. Such typesetting tricks might be interpreted by automated methods incorrectly as an actual table, while the human annotation will interpret it correctly as Text or other styles. The same applies to multi-line text elements, when authors decided to space them as "invisible" list elements without bullet symbols. A third reason to gather ground-truth through human annotation is to estimate a "natural" upper bound on the segmentation accuracy. As we will show in Section 4, certain documents featuring complex layouts can have different but equally acceptable layout interpretations. This natural upper bound for segmentation accuracy can be found by annotating the same pages multiple times by different people and evaluating the inter-annotator agreement. Such a baseline consistency evaluation is very useful to define expectations for a good target accuracy in trained deep neural network models and avoid overfitting (see Table 1). On the flip side, achieving high annotation consistency proved to be a key challenge in human annotation, as we outline in Section 4. + +## 4 ANNOTATION CAMPAIGN + +The annotation campaign was carried out in four phases. In phase one, we identified and prepared the data sources for annotation. In phase two, we determined the class labels and how annotations should be done on the documents in order to obtain maximum consistency. The latter was guided by a detailed requirement analysis and exhaustive experiments. In phase three, we trained the annotation staff and performed exams for quality assurance. In phase four, + +Table 1: DocLayNet dataset overview. Along with the frequency of each class label, we present the relative occurrence (as % of row "Total") in the train, test and validation sets. The inter-annotator agreement is computed as the mAP@0.5-0.95 metric between pairwise annotations from the triple-annotated pages, from which we obtain accuracy ranges. + +| | | % of Total | % of Total | % of Total | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | triple inter-annotator mAP @0.5-0.95 (%) | +|----------------|---------|--------------|--------------|--------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------|--------------------------------------------| +| class label | Count | Train | Test | Val | All | Fin | Man | Sci | Law | Pat | Ten | +| Caption | 22524 | 2.04 | 1.77 | 2.32 | 84-89 | 40-61 | 86-92 | 94-99 | 95-99 | 69-78 | n/a | +| Footnote | 6318 | 0.60 | 0.31 | 0.58 | 83-91 | n/a | 100 | 62-88 | 85-94 | n/a | 82-97 | +| Formula | 25027 | 2.25 | 1.90 | 2.96 | 83-85 | n/a | n/a | 84-87 | 86-96 | n/a | n/a | +| List-item | 185660 | 17.19 | 13.34 | 15.82 | 87-88 | 74-83 | 90-92 | 97-97 | 81-85 | 75-88 | 93-95 | +| Page-footer | 70878 | 6.51 | 5.58 | 6.00 | 93-94 | 88-90 | 95-96 | 100 | 92-97 | 100 | 96-98 | +| Page-header | 58022 | 5.10 | 6.70 | 5.06 | 85-89 | 66-76 | 90-94 | 98-100 | 91-92 | 97-99 | 81-86 | +| Picture | 45976 | 4.21 | 2.78 | 5.31 | 69-71 | 56-59 | 82-86 | 69-82 | 80-95 | 66-71 | 59-76 | +| Section-header | 142884 | 12.60 | 15.77 | 12.85 | 83-84 | 76-81 | 90-92 | 94-95 | 87-94 | 69-73 | 78-86 | +| Table | 34733 | 3.20 | 2.27 | 3.60 | 77-81 | 75-80 | 83-86 | 98-99 | 58-80 | 79-84 | 70-85 | +| Text | 510377 | 45.82 | 49.28 | 45.00 | 84-86 | 81-86 | 88-93 | 89-93 | 87-92 | 71-79 | 87-95 | +| Title | 5071 | 0.47 | 0.30 | 0.50 | 60-72 | 24-63 | 50-63 | 94-100 | 82-96 | 68-79 | 24-56 | +| Total | 1107470 | 941123 | 99816 | 66531 | 82-83 | 71-74 | 79-81 | 89-94 | 86-91 | 71-76 | 68-85 | + +Figure 3: Corpus Conversion Service annotation user interface. The PDF page is shown in the background, with overlaid text-cells (in darker shades). The annotation boxes can be drawn by dragging a rectangle over each segment with the respective label from the palette on the right. + + + +include publication repositories such as arXiv 3 , government offices, company websites as well as data directory services for financial reports and patents. Scanned documents were excluded wherever possible because they can be rotated or skewed. This would not allow us to perform annotation with rectangular bounding-boxes and therefore complicate the annotation process. + +Preparation work included uploading and parsing the sourced PDF documents in the Corpus Conversion Service (CCS) [22], a cloud-native platform which provides a visual annotation interface and allows for dataset inspection and analysis. The annotation interface of CCS is shown in Figure 3. The desired balance of pages between the different document categories was achieved by selective subsampling of pages with certain desired properties. For example, we made sure to include the title page of each document and bias the remaining page selection to those with figures or tables. The latter was achieved by leveraging pre-trained object detection models from PubLayNet, which helped us estimate how many figures and tables a given page contains. + +Phase 2: Label selection and guideline. We reviewed the collected documents and identified the most common structural features they exhibit. This was achieved by identifying recurrent layout elements and lead us to the definition of 11 distinct class labels. These 11 class labels are Caption , Footnote , Formula , List-item , Pagefooter , Page-header , Picture , Section-header , Table , Text , and Title . Critical factors that were considered for the choice of these class labels were (1) the overall occurrence of the label, (2) the specificity of the label, (3) recognisability on a single page (i.e. no need for context from previous or next page) and (4) overall coverage of the page. Specificity ensures that the choice of label is not ambiguous, while coverage ensures that all meaningful items on a page can be annotated. We refrained from class labels that are very specific to a document category, such as Abstract in the Scientific Articles category. We also avoided class labels that are tightly linked to the semantics of the text. Labels such as Author and Affiliation , as seen in DocBank, are often only distinguishable by discriminating on we distributed the annotation workload and performed continuous quality controls. Phase one and two required a small team of experts only. For phases three and four, a group of 40 dedicated annotators were assembled and supervised. + +Phase 1: Data selection and preparation. Our inclusion criteria for documents were described in Section 3. A large effort went into ensuring that all documents are free to use. The data sources + +3 https://arxiv.org/ + +the textual content of an element, which goes beyond visual layout recognition, in particular outside the Scientific Articles category. + +At first sight, the task of visual document-layout interpretation appears intuitive enough to obtain plausible annotations in most cases. However, during early trial-runs in the core team, we observed many cases in which annotators use different annotation styles, especially for documents with challenging layouts. For example, if a figure is presented with subfigures, one annotator might draw a single figure bounding-box, while another might annotate each subfigure separately. The same applies for lists, where one might annotate all list items in one block or each list item separately. In essence, we observed that challenging layouts would be annotated in different but plausible ways. To illustrate this, we show in Figure 4 multiple examples of plausible but inconsistent annotations on the same pages. + +Obviously, this inconsistency in annotations is not desirable for datasets which are intended to be used for model training. To minimise these inconsistencies, we created a detailed annotation guideline. While perfect consistency across 40 annotation staff members is clearly not possible to achieve, we saw a huge improvement in annotation consistency after the introduction of our annotation guideline. A few selected, non-trivial highlights of the guideline are:( + +- 1) Every list-item is an individual object instance with class label List-item . This definition is different from PubLayNet and DocBank, where all list-items are grouped together into one List object. +- (2) A List-item is a paragraph with hanging indentation. Singleline elements can qualify as List-item if the neighbour elements expose hanging indentation. Bullet or enumeration symbols are not a requirement. +- (3) For every Caption , there must be exactly one corresponding Picture or Table . +- (4) Connected sub-pictures are grouped together in one Picture object. +- (5) Formula numbers are included in a Formula object. +- (6) Emphasised text (e.g. in italic or bold) at the beginning of a paragraph is not considered a Section-header , unless it appears exclusively on its own line. + +The complete annotation guideline is over 100 pages long and a detailed description is obviously out of scope for this paper. Nevertheless, it will be made publicly available alongside with DocLayNet for future reference. + +Phase 3: Training. After a first trial with a small group of people, we realised that providing the annotation guideline and a set of random practice pages did not yield the desired quality level for layout annotation. Therefore we prepared a subset of pages with two different complexity levels, each with a practice and an exam part. 974 pages were reference-annotated by one proficient core team member. Annotation staff were then given the task to annotate the same subsets (blinded from the reference). By comparing the annotations of each staff member with the reference annotations, we could quantify how closely their annotations matched the reference. Only after passing two exam levels with high annotation quality, staff were admitted into the production phase. Practice iterations + +Figure 4: Examples of plausible annotation alternatives for the same page. Criteria in our annotation guideline can resolve cases A to C, while the case D remains ambiguous. + + + +were carried out over a timeframe of 12 weeks, after which 8 of the 40 initially allocated annotators did not pass the bar. + +Phase 4: Production annotation. The previously selected 80K pages were annotated with the defined 11 class labels by 32 annotators. This production phase took around three months to complete. All annotations were created online through CCS, which visualises the programmatic PDF text-cells as an overlay on the page. The page annotation are obtained by drawing rectangular bounding-boxes, as shown in Figure 3. With regard to the annotation practices, we implemented a few constraints and capabilities on the tooling level. First, we only allow non-overlapping, vertically oriented, rectangular boxes. For the large majority of documents, this constraint was sufficient and it speeds up the annotation considerably in comparison with arbitrary segmentation shapes. Second, annotator staff were not able to see each other's annotations. This was enforced by design to avoid any bias in the annotation, which could skew the numbers of the inter-annotator agreement (see Table 1). We wanted + +Table 2: Prediction performance (mAP@0.5-0.95) of object detection networks on DocLayNet test set. The MRCNN (Mask R-CNN) and FRCNN (Faster R-CNN) models with ResNet-50 or ResNet-101 backbone were trained based on the network architectures from the detectron2 model zoo (Mask R-CNN R50, R101-FPN 3x, Faster R-CNN R101-FPN 3x), with default configurations. The YOLO implementation utilized was YOLOv5x6 [13]. All models were initialised using pre-trained weights from the COCO 2017 dataset. + +| | human | MRCNN | MRCNN | FRCNN | YOLO v5x6 | +|----------------|---------|---------|---------|---------|-------------| +| | | R50 | R101 | R101 | | +| Caption | 84-89 | 68.4 | 71.5 | 70.1 | 77.7 | +| Footnote | 83-91 | 70.9 | 71.8 | 73.7 | 77.2 | +| Formula | 83-85 | 60.1 | 63.4 | 63.5 | 66.2 | +| List-item | 87-88 | 81.2 | 80.8 | 81.0 | 86.2 | +| Page-footer | 93-94 | 61.6 | 59.3 | 58.9 | 61.1 | +| Page-header | 85-89 | 71.9 | 70.0 | 72.0 | 67.9 | +| Picture | 69-71 | 71.7 | 72.7 | 72.0 | 77.1 | +| Section-header | 83-84 | 67.6 | 69.3 | 68.4 | 74.6 | +| Table | 77-81 | 82.2 | 82.9 | 82.2 | 86.3 | +| Text | 84-86 | 84.6 | 85.8 | 85.4 | 88.1 | +| Title | 60-72 | 76.7 | 80.4 | 79.9 | 82.7 | +| All | 82-83 | 72.4 | 73.5 | 73.4 | 76.8 | + +to avoid this at any cost in order to have clear, unbiased baseline numbers for human document-layout annotation. Third, we introduced the feature of snapping boxes around text segments to obtain a pixel-accurate annotation and again reduce time and effort. The CCS annotation tool automatically shrinks every user-drawn box to the minimum bounding-box around the enclosed text-cells for all purely text-based segments, which excludes only Table and Picture . For the latter, we instructed annotation staff to minimise inclusion of surrounding whitespace while including all graphical lines. A downside of snapping boxes to enclosed text cells is that some wrongly parsed PDF pages cannot be annotated correctly and need to be skipped. Fourth, we established a way to flag pages as rejected for cases where no valid annotation according to the label guidelines could be achieved. Example cases for this would be PDF pages that render incorrectly or contain layouts that are impossible to capture with non-overlapping rectangles. Such rejected pages are not contained in the final dataset. With all these measures in place, experienced annotation staff managed to annotate a single page in a typical timeframe of 20s to 60s, depending on its complexity. + +## 5 EXPERIMENTS + +The primary goal of DocLayNet is to obtain high-quality ML models capable of accurate document-layout analysis on a wide variety of challenging layouts. As discussed in Section 2, object detection models are currently the easiest to use, due to the standardisation of ground-truth data in COCO format [16] and the availability of general frameworks such as detectron2 [17]. Furthermore, baseline numbers in PubLayNet and DocBank were obtained using standard object detection models such as Mask R-CNN and Faster R-CNN. As such, we will relate to these object detection methods in this + +Figure 5: Prediction performance (mAP@0.5-0.95) of a Mask R-CNN network with ResNet50 backbone trained on increasing fractions of the DocLayNet dataset. The learning curve flattens around the 80% mark, indicating that increasing the size of the DocLayNet dataset with similar data will not yield significantly better predictions. + + + +paper and leave the detailed evaluation of more recent methods mentioned in Section 2 for future work. + +In this section, we will present several aspects related to the performance of object detection models on DocLayNet. Similarly as in PubLayNet, we will evaluate the quality of their predictions using mean average precision (mAP) with 10 overlaps that range from 0.5 to 0.95 in steps of 0.05 (mAP@0.5-0.95). These scores are computed by leveraging the evaluation code provided by the COCO API [16]. + +## Baselines for Object Detection + +In Table 2, we present baseline experiments (given in mAP) on Mask R-CNN [12], Faster R-CNN [11], and YOLOv5 [13]. Both training and evaluation were performed on RGB images with dimensions of 1025 × 1025 pixels. For training, we only used one annotation in case of redundantly annotated pages. As one can observe, the variation in mAP between the models is rather low, but overall between 6 and 10% lower than the mAP computed from the pairwise human annotations on triple-annotated pages. This gives a good indication that the DocLayNet dataset poses a worthwhile challenge for the research community to close the gap between human recognition and ML approaches. It is interesting to see that Mask R-CNN and Faster R-CNN produce very comparable mAP scores, indicating that pixel-based image segmentation derived from bounding-boxes does not help to obtain better predictions. On the other hand, the more recent Yolov5x model does very well and even out-performs humans on selected labels such as Text , Table and Picture . This is not entirely surprising, as Text , Table and Picture are abundant and the most visually distinctive in a document. + +Table 3: Performance of a Mask R-CNN R50 network in mAP@0.5-0.95 scores trained on DocLayNet with different class label sets. The reduced label sets were obtained by either down-mapping or dropping labels. + +| Class-count | 11 | 6 | 5 | 4 | +|----------------|------|---------|---------|---------| +| Caption | 68 | Text | Text | Text | +| Footnote | 71 | Text | Text | Text | +| Formula | 60 | Text | Text | Text | +| List-item | 81 | Text | 82 | Text | +| Page-footer | 62 | 62 | - | - | +| Page-header | 72 | 68 | - | - | +| Picture | 72 | 72 | 72 | 72 | +| Section-header | 68 | 67 | 69 | 68 | +| Table | 82 | 83 | 82 | 82 | +| Text | 85 | 84 | 84 | 84 | +| Title | 77 | Sec.-h. | Sec.-h. | Sec.-h. | +| Overall | 72 | 73 | 78 | 77 | + +## Learning Curve + +One of the fundamental questions related to any dataset is if it is "large enough". To answer this question for DocLayNet, we performed a data ablation study in which we evaluated a Mask R-CNN model trained on increasing fractions of the DocLayNet dataset. As can be seen in Figure 5, the mAP score rises sharply in the beginning and eventually levels out. To estimate the error-bar on the metrics, we ran the training five times on the entire data-set. This resulted in a 1% error-bar, depicted by the shaded area in Figure 5. In the inset of Figure 5, we show the exact same data-points, but with a logarithmic scale on the x-axis. As is expected, the mAP score increases linearly as a function of the data-size in the inset. The curve ultimately flattens out between the 80% and 100% mark, with the 80% mark falling within the error-bars of the 100% mark. This provides a good indication that the model would not improve significantly by yet increasing the data size. Rather, it would probably benefit more from improved data consistency (as discussed in Section 3), data augmentation methods [23], or the addition of more document categories and styles. + +## Impact of Class Labels + +The choice and number of labels can have a significant effect on the overall model performance. Since PubLayNet, DocBank and DocLayNet all have different label sets, it is of particular interest to understand and quantify this influence of the label set on the model performance. We investigate this by either down-mapping labels into more common ones (e.g. Caption → Text ) or excluding them from the annotations entirely. Furthermore, it must be stressed that all mappings and exclusions were performed on the data before model training. In Table 3, we present the mAP scores for a Mask R-CNN R50 network on different label sets. Where a label is down-mapped, we show its corresponding label, otherwise it was excluded. We present three different label sets, with 6, 5 and 4 different labels respectively. The set of 5 labels contains the same labels as PubLayNet. However, due to the different definition of + +Table 4: Performance of a Mask R-CNN R50 network with document-wise and page-wise split for different label sets. ~ Naive page-wise split will result in 10% point improvement. + +| Class-count | 11 | 11 | 5 | 5 | +|----------------|------|------|-----|------| +| Split | Doc | Page | Doc | Page | +| Caption | 68 | 83 | | | +| Footnote | 71 | 84 | | | +| Formula | 60 | 66 | | | +| List-item | 81 | 88 | 82 | 88 | +| Page-footer | 62 | 89 | | | +| Page-header | 72 | 90 | | | +| Picture | 72 | 82 | 72 | 82 | +| Section-header | 68 | 83 | 69 | 83 | +| Table | 82 | 89 | 82 | 90 | +| Text | 85 | 91 | 84 | 90 | +| Title | 77 | 81 | | | +| All | 72 | 84 | 78 | 87 | + +lists in PubLayNet (grouped list-items) versus DocLayNet (separate list-items), the label set of size 4 is the closest to PubLayNet, in the assumption that the List is down-mapped to Text in PubLayNet. The results in Table 3 show that the prediction accuracy on the remaining class labels does not change significantly when other classes are merged into them. The overall macro-average improves by around 5%, in particular when Page-footer and Page-header are excluded. + +## Impact of Document Split in Train and Test Set + +Many documents in DocLayNet have a unique styling. In order to avoid overfitting on a particular style, we have split the train-, test- and validation-sets of DocLayNet on document boundaries, i.e. every document contributes pages to only one set. To the best of our knowledge, this was not considered in PubLayNet or DocBank. To quantify how this affects model performance, we trained and evaluated a Mask R-CNN R50 model on a modified dataset version. Here, the train-, test- and validation-sets were obtained by a randomised draw over the individual pages. As can be seen in Table 4, the difference in model performance is surprisingly large: pagewise splitting gains 10% in mAP over the document-wise splitting. ˜ Thus, random page-wise splitting of DocLayNet can easily lead to accidental overestimation of model performance and should be avoided. + +## Dataset Comparison + +Throughout this paper, we claim that DocLayNet's wider variety of document layouts leads to more robust layout detection models. In Table 5, we provide evidence for that. We trained models on each of the available datasets (PubLayNet, DocBank and DocLayNet) and evaluated them on the test sets of the other datasets. Due to the different label sets and annotation styles, a direct comparison is not possible. Hence, we focussed on the common labels among the datasets. Between PubLayNet and DocLayNet, these are Picture , + +KDD '22, August 14-18, 2022, Washington, DC, USA Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar + +Table 5: Prediction Performance (mAP@0.5-0.95) of a Mask R-CNN R50 network across the PubLayNet, DocBank & DocLayNet data-sets. By evaluating on common label classes of each dataset, we observe that the DocLayNet-trained model has much less pronounced variations in performance across all datasets. + +| | | Testing on | Testing on | Testing on | +|------------------------------|------------|--------------|--------------|--------------| +| Training on | labels | PLN | DB | DLN | +| PubLayNet (PLN) confidence.6 | Figure | 96 | 43 | 23 | +| PubLayNet (PLN) confidence.6 | Sec-header | 87 | - | 32 | +| | Table | 95 | 24 | 49 | +| | Text | 96 | - | 42 | +| | total | 93 | 34 | 30 | +| DocBank (DB) | Figure | 77 | 71 | 31 | +| DocBank (DB) | Table | 19 | 65 | 22 | +| DocBank (DB) | total | 48 | 68 | 27 | +| DocLayNet (DLN) | Figure | 67 | 51 | 72 | +| DocLayNet (DLN) | Sec-header | 53 | - | 68 | +| | Table | 87 | 43 | 82 | +| | Text | 77 | - | 84 | +| | total | 59 | 47 | 78 | + +Section-header , Table and Text . Before training, we either mapped or excluded DocLayNet's other labels as specified in table 3, and also PubLayNet's List to Text . Note that the different clustering of lists (by list-element vs. whole list objects) naturally decreases the mAP score for Text . + +For comparison of DocBank with DocLayNet, we trained only on Picture and Table clusters of each dataset. We had to exclude Text because successive paragraphs are often grouped together into a single object in DocBank. This paragraph grouping is incompatible with the individual paragraphs of DocLayNet. As can be seen in Table 5, DocLayNet trained models yield better performance compared to the previous datasets. It is noteworthy that the models trained on PubLayNet and DocBank perform very well on their own test set, but have a much lower performance on the foreign datasets. While this also applies to DocLayNet, the difference is far less pronounced. Thus we conclude that DocLayNet trained models are overall more robust and will produce better results for challenging, unseen layouts. + +## Example Predictions + +To conclude this section, we illustrate the quality of layout predictions one can expect from DocLayNet-trained models by providing a selection of examples without any further post-processing applied. Figure 6 shows selected layout predictions on pages from the test-set of DocLayNet. Results look decent in general across document categories, however one can also observe mistakes such as overlapping clusters of different classes, or entirely missing boxes due to low confidence. + +## 6 CONCLUSION + +In this paper, we presented the DocLayNet dataset. It provides the document conversion and layout analysis research community a new and challenging dataset to improve and fine-tune novel ML methods on. In contrast to many other datasets, DocLayNet was created by human annotation in order to obtain reliable layout ground-truth on a wide variety of publication- and typesettingstyles. Including a large proportion of documents outside the scientific publishing domain adds significant value in this respect. + +From the dataset, we have derived on the one hand reference metrics for human performance on document-layout annotation (through double and triple annotations) and on the other hand evaluated the baseline performance of commonly used object detection methods. We also illustrated the impact of various dataset-related aspects on model performance through data-ablation experiments, both from a size and class-label perspective. Last but not least, we compared the accuracy of models trained on other public datasets and showed that DocLayNet trained models are more robust. + +To date, there is still a significant gap between human and ML accuracy on the layout interpretation task, and we hope that this work will inspire the research community to close that gap. + +## REFERENCES + +- [1] Max Göbel, Tamir Hassan, Ermelinda Oro, and Giorgio Orsi. Icdar 2013 table competition. In 2013 12th International Conference on Document Analysis and Recognition , pages 1449-1453, 2013. +- [2] Christian Clausner, Apostolos Antonacopoulos, and Stefan Pletschacher. Icdar2017 competition on recognition of documents with complex layouts - rdcl2017. In 2017 14th IAPR International Conference on Document Analysis and Recognition (ICDAR) , volume 01, pages 1404-1410, 2017. +- [3] Hervé Déjean, Jean-Luc Meunier, Liangcai Gao, Yilun Huang, Yu Fang, Florian Kleber, and Eva-Maria Lang. ICDAR 2019 Competition on Table Detection and Recognition (cTDaR), April 2019. http://sac.founderit.com/. +- [4] Antonio Jimeno Yepes, Peter Zhong, and Douglas Burdick. Competition on scientific literature parsing. In Proceedings of the International Conference on Document Analysis and Recognition , ICDAR, pages 605-617. LNCS 12824, SpringerVerlag, sep 2021. +- [5] Logan Markewich, Hao Zhang, Yubin Xing, Navid Lambert-Shirzad, Jiang Zhexin, Roy Lee, Zhi Li, and Seok-Bum Ko. Segmentation for document layout analysis: not dead yet. International Journal on Document Analysis and Recognition (IJDAR) , pages 1-11, 01 2022. +- [6] Xu Zhong, Jianbin Tang, and Antonio Jimeno-Yepes. Publaynet: Largest dataset ever for document layout analysis. In Proceedings ofthe International Conference on Document Analysis and Recognition , ICDAR, pages 1015-1022, sep 2019. +- [7] Minghao Li, Yiheng Xu, Lei Cui, Shaohan Huang, Furu Wei, Zhoujun Li, and Ming Zhou. Docbank: A benchmark dataset for document layout analysis. In Proceedings of the 28th International Conference on Computational Linguistics , COLING, pages 949-960. International Committee on Computational Linguistics, dec 2020. +- [8] Riaz Ahmad, Muhammad Tanvir Afzal, and M. Qadir. Information extraction from pdf sources based on rule-based system using integrated formats. In SemWebEval@ESWC , 2016. +- [9] Ross B. Girshick, Jeff Donahue, Trevor Darrell, and Jitendra Malik. Rich feature hierarchies for accurate object detection and semantic segmentation. In IEEE Conference on Computer Vision and Pattern Recognition , CVPR, pages 580-587. IEEE Computer Society, jun 2014. +- [10] Ross B. Girshick. Fast R-CNN. In 2015 IEEE International Conference on Computer Vision , ICCV, pages 1440-1448. IEEE Computer Society, dec 2015. +- [11] Shaoqing Ren, Kaiming He, Ross Girshick, and Jian Sun. Faster r-cnn: Towards real-time object detection with region proposal networks. IEEE Transactions on Pattern Analysis and Machine Intelligence , 39(6):1137-1149, 2017. +- [12] Kaiming He, Georgia Gkioxari, Piotr Dollár, and Ross B. Girshick. Mask R-CNN. In IEEE International Conference on Computer Vision , ICCV, pages 2980-2988. IEEE Computer Society, Oct 2017. +- [13] Glenn Jocher, Alex Stoken, Ayush Chaurasia, Jirka Borovec, NanoCode012, TaoXie, Yonghye Kwon, Kalen Michael, Liu Changyu, Jiacong Fang, Abhiram V, Laughing, tkianai, yxNONG, Piotr Skalski, Adam Hogan, Jebastin Nadar, imyhxy, Lorenzo Mammana, Alex Wang, Cristi Fati, Diego Montes, Jan Hajek, Laurentiu + +Figure 6: Example layout predictions on selected pages from the DocLayNet test-set. (A, D) exhibit favourable results on coloured backgrounds. (B, C) show accurate list-item and paragraph differentiation despite densely-spaced lines. (E) demonstrates good table and figure distinction. (F) shows predictions on a Chinese patent with multiple overlaps, label confusion and missing boxes. + + + +Text Caption List-Item Formula Table Picture Section-Header Page-Header Page-Footer Title + +Diaconu, Mai Thanh Minh, Marc, albinxavi, fatih, oleg, and wanghao yang. ultralytics/yolov5: v6.0 - yolov5n nano models, roboflow integration, tensorflow export, opencv dnn support, October 2021. + +- [14] Nicolas Carion, Francisco Massa, Gabriel Synnaeve, Nicolas Usunier, Alexander Kirillov, and Sergey Zagoruyko. End-to-end object detection with transformers. CoRR , abs/2005.12872, 2020. +- [15] Mingxing Tan, Ruoming Pang, and Quoc V. Le. Efficientdet: Scalable and efficient object detection. CoRR , abs/1911.09070, 2019. +- [16] Tsung-Yi Lin, Michael Maire, Serge J. Belongie, Lubomir D. Bourdev, Ross B. Girshick, James Hays, Pietro Perona, Deva Ramanan, Piotr Dollár, and C. Lawrence Zitnick. Microsoft COCO: common objects in context, 2014. +- [17] Yuxin Wu, Alexander Kirillov, Francisco Massa, Wan-Yen Lo, and Ross Girshick. Detectron2, 2019. +- [18] Nikolaos Livathinos, Cesar Berrospi, Maksym Lysak, Viktor Kuropiatnyk, Ahmed Nassar, Andre Carvalho, Michele Dolfi, Christoph Auer, Kasper Dinkla, and Peter W. J. Staar. Robust pdf document conversion using recurrent neural networks. In Proceedings ofthe 35th Conference on Artificial Intelligence , AAAI, pages 15137- 15145, feb 2021. +- [19] Yiheng Xu, Minghao Li, Lei Cui, Shaohan Huang, Furu Wei, and Ming Zhou. Layoutlm: Pre-training of text and layout for document image understanding. In Proceedings ofthe 26th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining , KDD, pages 1192-1200, New York, USA, 2020. Association for Computing Machinery. +- [20] Shoubin Li, Xuyan Ma, Shuaiqun Pan, Jun Hu, Lin Shi, and Qing Wang. Vtlayout: Fusion of visual and text features for document layout analysis, 2021. +- [21] Peng Zhang, Can Li, Liang Qiao, Zhanzhan Cheng, Shiliang Pu, Yi Niu, and Fei Wu. Vsr: A unified framework for document layout analysis combining vision, semantics and relations, 2021. +- [22] Peter W J Staar, Michele Dolfi, Christoph Auer, and Costas Bekas. Corpus conversion service: A machine learning platform to ingest documents at scale. In Proceedings ofthe 24th ACM SIGKDD International Conference on Knowledge Discovery and Data Mining , KDD, pages 774-782. ACM, 2018. +- [23] Connor Shorten and Taghi M. Khoshgoftaar. A survey on image data augmentation for deep learning. Journal ofBig Data , 6(1):60, 2019. diff --git a/tests/snapshots/pdf/sources/2305.03393v1-pg9.pdf.md b/tests/snapshots/pdf/sources/2305.03393v1-pg9.pdf.md new file mode 100644 index 00000000..55ca4de2 --- /dev/null +++ b/tests/snapshots/pdf/sources/2305.03393v1-pg9.pdf.md @@ -0,0 +1,21 @@ +order to compute the TED score. Inference timing results for all experiments were obtained from the same machine on a single core with AMD EPYC 7763 CPU @2.45 GHz. + +## 5.1 Hyper Parameter Optimization + +We have chosen the PubTabNet data set to perform HPO, since it includes a highly diverse set of tables. Also we report TED scores separately for simple and complex tables (tables with cell spans). Results are presented in Table. 1. It is evident that with OTSL, our model achieves the same TED score and slightly better mAP scores in comparison to HTML. However OTSL yields a 2x speed up in the inference runtime over HTML. + +Table 1. HPO performed in OTSL and HTML representation on the same transformer-based TableFormer [9] architecture, trained only on PubTabNet [22]. Effects of reducing the # of layers in encoder and decoder stages of the model show that smaller models trained on OTSL perform better, especially in recognizing complex table structures, and maintain a much higher mAP score than the HTML counterpart. + +| # enc-layers | # dec-layers | Language | TEDs | TEDs | TEDs | mAP (0.75) | Inference time (secs) | +|----------------|----------------|------------|-------------|-------------|-------------|--------------|-------------------------| +| # enc-layers | # dec-layers | Language | simple | complex | all | mAP (0.75) | Inference time (secs) | +| 6 | 6 | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | +| 4 | 4 | OTSL HTML | 0.938 0.952 | 0.904 0.909 | 0.927 0.938 | 0.853 0.843 | 1.97 3.77 | +| 2 | 4 | OTSL HTML | 0.923 0.945 | 0.897 0.901 | 0.915 0.931 | 0.859 0.834 | 1.91 3.81 | +| 4 | 2 | OTSL HTML | 0.952 0.944 | 0.92 0.903 | 0.942 0.931 | 0.857 0.824 | 1.22 2 | + +## 5.2 Quantitative Results + +We picked the model parameter configuration that produced the best prediction quality (enc=6, dec=6, heads=8) with PubTabNet alone, then independently trained and evaluated it on three publicly available data sets: PubTabNet (395k samples), FinTabNet (113k samples) and PubTables-1M (about 1M samples). Performance results are presented in Table. 2. It is clearly evident that the model trained on OTSL outperforms HTML across the board, keeping high TEDs and mAP scores even on difficult financial tables (FinTabNet) that contain sparse and large tables. + +Additionally, the results show that OTSL has an advantage over HTML when applied on a bigger data set like PubTables-1M and achieves significantly improved scores. Finally, OTSL achieves faster inference due to fewer decoding steps which is a result of the reduced sequence representation. diff --git a/tests/snapshots/pdf/sources/2305.03393v1.pdf.md b/tests/snapshots/pdf/sources/2305.03393v1.pdf.md new file mode 100644 index 00000000..f23a5b9e --- /dev/null +++ b/tests/snapshots/pdf/sources/2305.03393v1.pdf.md @@ -0,0 +1,184 @@ +## Optimized Table Tokenization for Table Structure Recognition + +Maksym Lysak [0000 - 0002 - 3723 - 6960] , Ahmed Nassar [0000 - 0002 - 9468 - 0822] , Nikolaos Livathinos [0000 - 0001 - 8513 - 3491] , Christoph Auer [0000 - 0001 - 5761 - 0422] , and Peter Staar [0000 - 0002 - 8088 - 0823] + +IBM Research {mly,ahn,nli,cau,taa}@zurich.ibm.com + +Abstract. Extracting tables from documents is a crucial task in any document conversion pipeline. Recently, transformer-based models have demonstrated that table-structure can be recognized with impressive accuracy using Image-to-Markup-Sequence (Im2Seq) approaches. Taking only the image of a table, such models predict a sequence of tokens (e.g. in HTML, LaTeX) which represent the structure of the table. Since the token representation of the table structure has a significant impact on the accuracy and run-time performance of any Im2Seq model, we investigate in this paper how table-structure representation can be optimised. We propose a new, optimised table-structure language (OTSL) with a minimized vocabulary and specific rules. The benefits of OTSL are that it reduces the number of tokens to 5 (HTML needs 28+) and shortens the sequence length to half of HTML on average. Consequently, model accuracy improves significantly, inference time is halved compared to HTML-based models, and the predicted table structures are always syntactically correct. This in turn eliminates most post-processing needs. Popular table structure data-sets will be published in OTSL format to the community. + +Keywords: Table Structure Recognition · Data Representation · Transformers · Optimization. + +## 1 Introduction + +Tables are ubiquitous in documents such as scientific papers, patents, reports, manuals, specification sheets or marketing material. They often encode highly valuable information and therefore need to be extracted with high accuracy. Unfortunately, tables appear in documents in various sizes, styling and structure, making it difficult to recover their correct structure with simple analytical methods. Therefore, accurate table extraction is achieved these days with machine-learning based methods. + +In modern document understanding systems [1,15], table extraction is typically a two-step process. Firstly, every table on a page is located with a bounding box, and secondly, their logical row and column structure is recognized. As of + +Fig. 1. Comparison between HTML and OTSL table structure representation: (A) table-example with complex row and column headers, including a 2D empty span, (B) minimal graphical representation of table structure using rectangular layout, (C) HTML representation, (D) OTSL representation. This example demonstrates many of the key-features of OTSL, namely its reduced vocabulary size (12 versus 5 in this case), its reduced sequence length (55 versus 30) and a enhanced internal structure (variable token sequence length per row in HTML versus a fixed length of rows in OTSL). + + + +today, table detection in documents is a well understood problem, and the latest state-of-the-art (SOTA) object detection methods provide an accuracy comparable to human observers [7,8,10,14,23]. On the other hand, the problem of table structure recognition (TSR) is a lot more challenging and remains a very active area of research, in which many novel machine learning algorithms are being explored [3,4,5,9,11,12,13,14,17,18,21,22]. + +Recently emerging SOTA methods for table structure recognition employ transformer-based models, in which an image of the table is provided to the network in order to predict the structure of the table as a sequence of tokens. These image-to-sequence (Im2Seq) models are extremely powerful, since they allow for a purely data-driven solution. The tokens of the sequence typically belong to a markup language such as HTML, Latex or Markdown, which allow to describe table structure as rows, columns and spanning cells in various configurations. In Figure 1, we illustrate how HTML is used to represent the table-structure of a particular example table. Public table-structure data sets such as PubTabNet [22], and FinTabNet [21], which were created in a semi-automated way from paired PDF and HTML sources (e.g. PubMed Central), popularized primarily the use of HTML as ground-truth representation format for TSR. + +While the majority of research in TSR is currently focused on the development and application of novel neural model architectures, the table structure representation language (e.g. HTML in PubTabNet and FinTabNet) is usually adopted as is for the sequence tokenization in Im2Seq models. In this paper, we aim for the opposite and investigate the impact of the table structure representation language with an otherwise unmodified Im2Seq transformer-based architecture. Since the current state-of-the-art Im2Seq model is TableFormer [9], we select this model to perform our experiments. + +The main contribution of this paper is the introduction of a new optimised table structure language (OTSL), specifically designed to describe table-structure in an compact and structured way for Im2Seq models. OTSL has a number of key features, which make it very attractive to use in Im2Seq models. Specifically, compared to other languages such as HTML, OTSL has a minimized vocabulary which yields short sequence length, strong inherent structure (e.g. strict rectangular layout) and a strict syntax with rules that only look backwards. The latter allows for syntax validation during inference and ensures a syntactically correct table-structure. These OTSL features are illustrated in Figure 1, in comparison to HTML. + +The paper is structured as follows. In section 2, we give an overview of the latest developments in table-structure reconstruction. In section 3 we review the current HTML table encoding (popularised by PubTabNet and FinTabNet) and discuss its flaws. Subsequently, we introduce OTSL in section 4, which includes the language definition, syntax rules and error-correction procedures. In section 5, we apply OTSL on the TableFormer architecture, compare it to TableFormer models trained on HTML and ultimately demonstrate the advantages of using OTSL. Finally, in section 6 we conclude our work and outline next potential steps. + +## 2 Related Work + +Approaches to formalize the logical structure and layout of tables in electronic documents date back more than two decades [16]. In the recent past, a wide variety of computer vision methods have been explored to tackle the problem of table structure recognition, i.e. the correct identification of columns, rows and spanning cells in a given table. Broadly speaking, the current deeplearning based approaches fall into three categories: object detection (OD) methods, Graph-Neural-Network (GNN) methods and Image-to-Markup-Sequence (Im2Seq) methods. Object-detection based methods [11,12,13,14,21] rely on tablestructure annotation using (overlapping) bounding boxes for training, and produce bounding-box predictions to define table cells, rows, and columns on a table image. Graph Neural Network (GNN) based methods [3,6,17,18], as the name suggests, represent tables as graph structures. The graph nodes represent the content of each table cell, an embedding vector from the table image, or geometric coordinates of the table cell. The edges of the graph define the relationship between the nodes, e.g. if they belong to the same column, row, or table cell. + +Other work [20] aims at predicting a grid for each table and deciding which cells must be merged using an attention network. Im2Seq methods cast the problem as a sequence generation task [4,5,9,22], and therefore need an internal tablestructure representation language, which is often implemented with standard markup languages (e.g. HTML, LaTeX, Markdown). In theory, Im2Seq methods have a natural advantage over the OD and GNN methods by virtue of directly predicting the table-structure. As such, no post-processing or rules are needed in order to obtain the table-structure, which is necessary with OD and GNN approaches. In practice, this is not entirely true, because a predicted sequence of table-structure markup does not necessarily have to be syntactically correct. Hence, depending on the quality of the predicted sequence, some post-processing needs to be performed to ensure a syntactically valid (let alone correct) sequence. + +Within the Im2Seq method, we find several popular models, namely the encoder-dual-decoder model (EDD) [22], TableFormer [9], Tabsplitter[2] and Ye et. al. [19]. EDD uses two consecutive long short-term memory (LSTM) decoders to predict a table in HTML representation. The tag decoder predicts a sequence of HTML tags. For each decoded table cell ( <td> ), the attention is passed to the cell decoder to predict the content with an embedded OCR approach. The latter makes it susceptible to transcription errors in the cell content of the table. TableFormer address this reliance on OCR and uses two transformer decoders for HTML structure and cell bounding box prediction in an end-to-end architecture. The predicted cell bounding box is then used to extract text tokens from an originating (digital) PDF page, circumventing any need for OCR. TabSplitter [2] proposes a compact double-matrix representation of table rows and columns to do error detection and error correction of HTML structure sequences based on predictions from [19]. This compact double-matrix representation can not be used directly by the Img2seq model training, so the model uses HTML as an intermediate form. Chi et. al. [4] introduce a data set and a baseline method using bidirectional LSTMs to predict LaTeX code. Kayal [5] introduces Gated ResNet transformers to predict LaTeX code, and a separate OCR module to extract content. + +Im2Seq approaches have shown to be well-suited for the TSR task and allow a full end-to-end network design that can output the final table structure without pre- or post-processing logic. Furthermore, Im2Seq models have demonstrated to deliver state-of-the-art prediction accuracy [9]. This motivated the authors to investigate if the performance (both in accuracy and inference time) can be further improved by optimising the table structure representation language. We believe this is a necessary step before further improving neural network architectures for this task. + +## 3 Problem Statement + +All known Im2Seq based models for TSR fundamentally work in similar ways. Given an image of a table, the Im2Seq model predicts the structure of the table by generating a sequence of tokens. These tokens originate from a finite vocab- ulary and can be interpreted as a table structure. For example, with the HTML tokens <table> , </table> , <tr> , </tr> , <td> and </td> , one can construct simple table structures without any spanning cells. In reality though, one needs at least 28 HTML tokens to describe the most common complex tables observed in real-world documents [21,22], due to a variety of spanning cells definitions in the HTML token vocabulary. + +Fig. 2. Frequency of tokens in HTML and OTSL as they appear in PubTabNet. + + + +Obviously, HTML and other general-purpose markup languages were not designed for Im2Seq models. As such, they have some serious drawbacks. First, the token vocabulary needs to be artificially large in order to describe all plausible tabular structures. Since most Im2Seq models use an autoregressive approach, they generate the sequence token by token. Therefore, to reduce inference time, a shorter sequence length is critical. Every table-cell is represented by at least two tokens ( <td> and </td> ). Furthermore, when tokenizing the HTML structure, one needs to explicitly enumerate possible column-spans and row-spans as words. In practice, this ends up requiring 28 different HTML tokens (when including column- and row-spans up to 10 cells) just to describe every table in the PubTabNet dataset. Clearly, not every token is equally represented, as is depicted in Figure 2. This skewed distribution of tokens in combination with variable token row-length makes it challenging for models to learn the HTML structure. + +Additionally, it would be desirable if the representation would easily allow an early detection of invalid sequences on-the-go, before the prediction of the entire table structure is completed. HTML is not well-suited for this purpose as the verification of incomplete sequences is non-trivial or even impossible. + +In a valid HTML table, the token sequence must describe a 2D grid of table cells, serialised in row-major ordering, where each row and each column have the same length (while considering row- and column-spans). Furthermore, every opening tag in HTML needs to be matched by a closing tag in a correct hierarchical manner. Since the number of tokens for each table row and column can vary significantly, especially for large tables with many row- and column-spans, it is complex to verify the consistency of predicted structures during sequence generation. Implicitly, this also means that Im2Seq models need to learn these complex syntax rules, simply to deliver valid output. + +In practice, we observe two major issues with prediction quality when training Im2Seq models on HTML table structure generation from images. On the one hand, we find that on large tables, the visual attention of the model often starts to drift and is not accurately moving forward cell by cell anymore. This manifests itself in either in an increasing location drift for proposed table-cells in later rows on the same column or even complete loss of vertical alignment, as illustrated in Figure 5. Addressing this with post-processing is partially possible, but clearly undesired. On the other hand, we find many instances of predictions with structural inconsistencies or plain invalid HTML output, as shown in Figure 6, which are nearly impossible to properly correct. Both problems seriously impact the TSR model performance, since they reflect not only in the task of pure structure recognition but also in the equally crucial recognition or matching of table cell content. + +## 4 Optimised Table Structure Language + +To mitigate the issues with HTML in Im2Seq-based TSR models laid out before, we propose here our Optimised Table Structure Language (OTSL). OTSL is designed to express table structure with a minimized vocabulary and a simple set of rules, which are both significantly reduced compared to HTML. At the same time, OTSL enables easy error detection and correction during sequence generation. We further demonstrate how the compact structure representation and minimized sequence length improves prediction accuracy and inference time in the TableFormer architecture. + +## 4.1 Language Definition + +In Figure 3, we illustrate how the OTSL is defined. In essence, the OTSL defines only 5 tokens that directly describe a tabular structure based on an atomic 2D grid. + +The OTSL vocabulary is comprised of the following tokens: + +- "C" cell - a new table cell that either has or does not have cell content +- "L" cell - left-looking cell , merging with the left neighbor cell to create a span +- "U" cell - up-looking cell , merging with the upper neighbor cell to create a span +- "X" cell - cross cell , to merge with both left and upper neighbor cells +- "NL" - new-line , switch to the next row. + +A notable attribute of OTSL is that it has the capability of achieving lossless conversion to HTML. + +Fig. 3. OTSL description of table structure: A - table example; B - graphical representation of table structure; C - mapping structure on a grid; D - OTSL structure encoding; E - explanation on cell encoding + + + +## 4.2 Language Syntax + +The OTSL representation follows these syntax rules: + +1. Left-looking cell rule : The left neighbour of an "L" cell must be either another "L" cell or a "C" cell. +2. Up-looking cell rule : The upper neighbour of a "U" cell must be either another "U" cell or a "C" cell. +3. Cross cell rule : + +The left neighbour of an "X" cell must be either another "X" cell or a "U" cell, and the upper neighbour of an "X" cell must be either another "X" cell or an "L" cell. + +4. First row rule : Only "L" cells and "C" cells are allowed in the first row. +5. First column rule : Only "U" cells and "C" cells are allowed in the first column. +6. Rectangular rule : The table representation is always rectangular - all rows must have an equal number of tokens, terminated with "NL" token. + +The application of these rules gives OTSL a set of unique properties. First of all, the OTSL enforces a strictly rectangular structure representation, where every new-line token starts a new row. As a consequence, all rows and all columns have exactly the same number of tokens, irrespective of cell spans. Secondly, the OTSL representation is unambiguous: Every table structure is represented in one way. In this representation every table cell corresponds to a "C"-cell token, which in case of spans is always located in the top-left corner of the table cell definition. Third, OTSL syntax rules are only backward-looking. As a consequence, every predicted token can be validated straight during sequence generation by looking at the previously predicted sequence. As such, OTSL can guarantee that every predicted sequence is syntactically valid. + +These characteristics can be easily learned by sequence generator networks, as we demonstrate further below. We find strong indications that this pattern reduces significantly the column drift seen in the HTML based models (see Figure 5). + +## 4.3 Error-detection and -mitigation + +The design of OTSL allows to validate a table structure easily on an unfinished sequence. The detection of an invalid sequence token is a clear indication of a prediction mistake, however a valid sequence by itself does not guarantee prediction correctness. Different heuristics can be used to correct token errors in an invalid sequence and thus increase the chances for accurate predictions. Such heuristics can be applied either after the prediction of each token, or at the end on the entire predicted sequence. For example a simple heuristic which can correct the predicted OTSL sequence on-the-fly is to verify if the token with the highest prediction confidence invalidates the predicted sequence, and replace it by the token with the next highest confidence until OTSL rules are satisfied. + +## 5 Experiments + +To evaluate the impact of OTSL on prediction accuracy and inference times, we conducted a series of experiments based on the TableFormer model (Figure 4) with two objectives: Firstly we evaluate the prediction quality and performance of OTSL vs. HTML after performing Hyper Parameter Optimization (HPO) on the canonical PubTabNet data set. Secondly we pick the best hyper-parameters found in the first step and evaluate how OTSL impacts the performance of TableFormer after training on other publicly available data sets (FinTabNet, PubTables-1M [14]). The ground truth (GT) from all data sets has been converted into OTSL format for this purpose, and will be made publicly available. + +Fig. 4. Architecture sketch of the TableFormer model, which is a representative for the Im2Seq approach. + + + +We rely on standard metrics such as Tree Edit Distance score (TEDs) for table structure prediction, and Mean Average Precision (mAP) with 0.75 Intersection Over Union (IOU) threshold for the bounding-box predictions of table cells. The predicted OTSL structures were converted back to HTML format in order to compute the TED score. Inference timing results for all experiments were obtained from the same machine on a single core with AMD EPYC 7763 CPU @2.45 GHz. + +## 5.1 Hyper Parameter Optimization + +We have chosen the PubTabNet data set to perform HPO, since it includes a highly diverse set of tables. Also we report TED scores separately for simple and complex tables (tables with cell spans). Results are presented in Table. 1. It is evident that with OTSL, our model achieves the same TED score and slightly better mAP scores in comparison to HTML. However OTSL yields a 2x speed up in the inference runtime over HTML. + +Table 1. HPO performed in OTSL and HTML representation on the same transformer-based TableFormer [9] architecture, trained only on PubTabNet [22]. Effects of reducing the # of layers in encoder and decoder stages of the model show that smaller models trained on OTSL perform better, especially in recognizing complex table structures, and maintain a much higher mAP score than the HTML counterpart. + +| # enc-layers | # dec-layers | Language | TEDs | TEDs | TEDs | mAP (0.75) | Inference time (secs) | +|----------------|----------------|------------|-------------|-------------|-------------|--------------|-------------------------| +| # enc-layers | # dec-layers | Language | simple | complex | all | mAP (0.75) | Inference time (secs) | +| 6 | 6 | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | +| 4 | 4 | OTSL HTML | 0.938 0.952 | 0.904 0.909 | 0.927 0.938 | 0.853 0.843 | 1.97 3.77 | +| 2 | 4 | OTSL HTML | 0.923 0.945 | 0.897 0.901 | 0.915 0.931 | 0.859 0.834 | 1.91 3.81 | +| 4 | 2 | OTSL HTML | 0.952 0.944 | 0.92 0.903 | 0.942 0.931 | 0.857 0.824 | 1.22 2 | + +## 5.2 Quantitative Results + +We picked the model parameter configuration that produced the best prediction quality (enc=6, dec=6, heads=8) with PubTabNet alone, then independently trained and evaluated it on three publicly available data sets: PubTabNet (395k samples), FinTabNet (113k samples) and PubTables-1M (about 1M samples). Performance results are presented in Table. 2. It is clearly evident that the model trained on OTSL outperforms HTML across the board, keeping high TEDs and mAP scores even on difficult financial tables (FinTabNet) that contain sparse and large tables. + +Additionally, the results show that OTSL has an advantage over HTML when applied on a bigger data set like PubTables-1M and achieves significantly improved scores. Finally, OTSL achieves faster inference due to fewer decoding steps which is a result of the reduced sequence representation. + +Table 2. TSR and cell detection results compared between OTSL and HTML on the PubTabNet [22], FinTabNet [21] and PubTables-1M [14] data sets using TableFormer [9] (with enc=6, dec=6, heads=8). + +| Data set | Language | TEDs | TEDs | TEDs | mAP(0.75) | Inference time (secs) | +|--------------|------------|-------------|-------------|-------------|-------------|-------------------------| +| Data set | Language | simple | complex | all | mAP(0.75) | Inference time (secs) | +| PubTabNet | OTSL HTML | 0.965 0.969 | 0.934 0.927 | 0.955 0.955 | 0.88 0.857 | 2.73 5.39 | +| FinTabNet | OTSL HTML | 0.955 0.917 | 0.961 0.922 | 0.959 0.92 | 0.862 0.722 | 1.85 3.26 | +| PubTables-1M | OTSL HTML | 0.987 0.983 | 0.964 0.944 | 0.977 0.966 | 0.896 0.889 | 1.79 3.26 | + +## 5.3 Qualitative Results + +To illustrate the qualitative differences between OTSL and HTML, Figure 5 demonstrates less overlap and more accurate bounding boxes with OTSL. In Figure 6, OTSL proves to be more effective in handling tables with longer token sequences, resulting in even more precise structure prediction and bounding boxes. + +Fig. 5. The OTSL model produces more accurate bounding boxes with less overlap (E) than the HTML model (D), when predicting the structure of a sparse table (A), at twice the inference speed because of shorter sequence length (B),(C). "PMC2807444\_006\_00.png" PubTabNet. μ + + + +Fig. 6. Visualization of predicted structure and detected bounding boxes on a complex table with many rows. The OTSL model (B) captured repeating pattern of horizontally merged cells from the GT (A), unlike the HTML model (C). The HTML model also didn't complete the HTML sequence correctly and displayed a lot more of drift and overlap of bounding boxes. "PMC5406406\_003\_01.png" PubTabNet. + + + +## 6 Conclusion + +We demonstrated that representing tables in HTML for the task of table structure recognition with Im2Seq models is ill-suited and has serious limitations. Furthermore, we presented in this paper an Optimized Table Structure Language (OTSL) which, when compared to commonly used general purpose languages, has several key benefits. + +First and foremost, given the same network configuration, inference time for a table-structure prediction is about 2 times faster compared to the conventional HTML approach. This is primarily owed to the shorter sequence length of the OTSL representation. Additional performance benefits can be obtained with HPO (hyper parameter optimization). As we demonstrate in our experiments, models trained on OTSL can be significantly smaller, e.g. by reducing the number of encoder and decoder layers, while preserving comparatively good prediction quality. This can further improve inference performance, yielding 5-6 times faster inference speed in OTSL with prediction quality comparable to models trained on HTML (see Table 1). + +Secondly, OTSL has more inherent structure and a significantly restricted vocabulary size. This allows autoregressive models to perform better in the TED metric, but especially with regards to prediction accuracy of the table-cell bounding boxes (see Table 2). As shown in Figure 5, we observe that the OTSL drastically reduces the drift for table cell bounding boxes at high row count and in sparse tables. This leads to more accurate predictions and a significant reduction in post-processing complexity, which is an undesired necessity in HTML-based Im2Seq models. Significant novelty lies in OTSL syntactical rules, which are few, simple and always backwards looking. Each new token can be validated only by analyzing the sequence of previous tokens, without requiring the entire sequence to detect mistakes. This in return allows to perform structural error detection and correction on-the-fly during sequence generation. + +## References + +1. Auer, C., Dolfi, M., Carvalho, A., Ramis, C.B., Staar, P.W.J.: Delivering document conversion as a cloud service with high throughput and responsiveness. CoRR abs/2206.00785 (2022). https://doi.org/10.48550/arXiv.2206.00785 , https://doi.org/10.48550/arXiv.2206.00785 +2. Chen, B., Peng, D., Zhang, J., Ren, Y., Jin, L.: Complex table structure recognition in the wild using transformer and identity matrix-based augmentation. In: Porwal, U., Fornés, A., Shafait, F. (eds.) Frontiers in Handwriting Recognition. pp. 545- 561. Springer International Publishing, Cham (2022) +3. Chi, Z., Huang, H., Xu, H.D., Yu, H., Yin, W., Mao, X.L.: Complicated table structure recognition. arXiv preprint arXiv:1908.04729 (2019) +4. Deng, Y., Rosenberg, D., Mann, G.: Challenges in end-to-end neural scientific table recognition. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 894-901. IEEE (2019) +5. Kayal, P., Anand, M., Desai, H., Singh, M.: Tables to latex: structure and content extraction from scientific tables. International Journal on Document Analysis and Recognition (IJDAR) pp. 1-10 (2022) +6. Lee, E., Kwon, J., Yang, H., Park, J., Lee, S., Koo, H.I., Cho, N.I.: Table structure recognition based on grid shape graph. In: 2022 Asia-Pacific Signal and Information Processing Association Annual Summit and Conference (APSIPA ASC). pp. 1868- 1873. IEEE (2022) +7. Li, M., Cui, L., Huang, S., Wei, F., Zhou, M., Li, Z.: Tablebank: A benchmark dataset for table detection and recognition (2019) +8. Livathinos, N., Berrospi, C., Lysak, M., Kuropiatnyk, V., Nassar, A., Carvalho, A., Dolfi, M., Auer, C., Dinkla, K., Staar, P.: Robust pdf document conversion using recurrent neural networks. Proceedings of the AAAI Conference on Artificial Intelligence 35 (17), 15137-15145 (May 2021), https://ojs.aaai.org/index.php/ AAAI/article/view/17777 +9. Nassar, A., Livathinos, N., Lysak, M., Staar, P.: Tableformer: Table structure understanding with transformers. In: Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). pp. 4614-4623 (June 2022) +10. Pfitzmann, B., Auer, C., Dolfi, M., Nassar, A.S., Staar, P.W.J.: Doclaynet: A large human-annotated dataset for document-layout segmentation. In: Zhang, A., Rangwala, H. (eds.) KDD '22: The 28th ACM SIGKDD Conference on Knowledge Discovery and Data Mining, Washington, DC, USA, August 14 - 18, 2022. pp. 3743-3751. ACM (2022). https://doi.org/10.1145/3534678.3539043 , https:// doi.org/10.1145/3534678.3539043 +11. Prasad, D., Gadpal, A., Kapadni, K., Visave, M., Sultanpure, K.: Cascadetabnet: An approach for end to end table detection and structure recognition from imagebased documents. In: Proceedings of the IEEE/CVF conference on computer vision and pattern recognition workshops. pp. 572-573 (2020) +12. Schreiber, S., Agne, S., Wolf, I., Dengel, A., Ahmed, S.: Deepdesrt: Deep learning for detection and structure recognition of tables in document images. In: 2017 14th IAPR international conference on document analysis and recognition (ICDAR). vol. 1, pp. 1162-1167. IEEE (2017) +13. Siddiqui, S.A., Fateh, I.A., Rizvi, S.T.R., Dengel, A., Ahmed, S.: Deeptabstr: Deep learning based table structure recognition. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 1403-1409 (2019). https:// doi.org/10.1109/ICDAR.2019.00226 +14. Smock, B., Pesala, R., Abraham, R.: PubTables-1M: Towards comprehensive table extraction from unstructured documents. In: Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). pp. 4634-4642 (June 2022) +15. Staar, P.W.J., Dolfi, M., Auer, C., Bekas, C.: Corpus conversion service: A machine learning platform to ingest documents at scale. In: Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining. pp. 774-782. KDD '18, Association for Computing Machinery, New York, NY, USA (2018). https://doi.org/10.1145/3219819.3219834 , https://doi.org/10. 1145/3219819.3219834 +16. Wang, X.: Tabular Abstraction, Editing, and Formatting. Ph.D. thesis, CAN (1996), aAINN09397 +17. Xue, W., Li, Q., Tao, D.: Res2tim: Reconstruct syntactic structures from table images. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 749-755. IEEE (2019) +18. Xue, W., Yu, B., Wang, W., Tao, D., Li, Q.: Tgrnet: A table graph reconstruction network for table structure recognition. In: Proceedings of the IEEE/CVF International Conference on Computer Vision. pp. 1295-1304 (2021) +19. Ye, J., Qi, X., He, Y., Chen, Y., Gu, D., Gao, P., Xiao, R.: Pingan-vcgroup's solution for icdar 2021 competition on scientific literature parsing task b: Table recognition to html (2021). https://doi.org/10.48550/ARXIV.2105.01848 , https://arxiv.org/abs/2105.01848 +20. Zhang, Z., Zhang, J., Du, J., Wang, F.: Split, embed and merge: An accurate table structure recognizer. Pattern Recognition 126 , 108565 (2022) +21. Zheng, X., Burdick, D., Popa, L., Zhong, X., Wang, N.X.R.: Global table extractor (gte): A framework for joint table identification and cell structure recognition using visual context. In: 2021 IEEE Winter Conference on Applications of Computer Vision (WACV). pp. 697-706 (2021). https://doi.org/10.1109/WACV48630.2021. 00074 +22. Zhong, X., ShafieiBavani, E., Jimeno Yepes, A.: Image-based table recognition: Data, model, and evaluation. In: Vedaldi, A., Bischof, H., Brox, T., Frahm, J.M. (eds.) Computer Vision - ECCV 2020. pp. 564-580. Springer International Publishing, Cham (2020) +23. Zhong, X., Tang, J., Yepes, A.J.: Publaynet: largest dataset ever for document layout analysis. In: 2019 International Conference on Document Analysis and Recognition (ICDAR). pp. 1015-1022. IEEE (2019) diff --git a/tests/pdf_snapshots/pdf/sources/amt_handbook_sample.pdf.md b/tests/snapshots/pdf/sources/amt_handbook_sample.pdf.md similarity index 53% rename from tests/pdf_snapshots/pdf/sources/amt_handbook_sample.pdf.md rename to tests/snapshots/pdf/sources/amt_handbook_sample.pdf.md index 33ecc611..35caca77 100644 --- a/tests/pdf_snapshots/pdf/sources/amt_handbook_sample.pdf.md +++ b/tests/snapshots/pdf/sources/amt_handbook_sample.pdf.md @@ -1,10 +1,10 @@ pulleys, provided the inner race of the bearing is clamped to the supporting structure by the nut and bolt. Plates must be attached to the structure in a positive manner to eliminate rotation or misalignment when tightening the bolts or screws. -The two general types of self-locking nuts currently in use are the all-metal type and the fiber lock type. For the sake of simplicity, only three typical kinds of self-locking nuts are considered in this handbook: the Boots self-locking and the stainless steel self-locking nuts, representing the all-metal types; and the elastic stop nut, representing t the fiber insert type. +The two general types of self-locking nuts currently in use are the all-metal type and the fiber lock type. For the sake of simplicity, only three typical kinds of self-locking nuts are considered in this handbook: the Boots self-locking and the stainless steel self-locking nuts, representing the all-metal types; and the elastic stop nut, representing the fiber insert type. ## Boots Self-Locking Nut -T he Boots self-locking nut is of one piece, all-metal construction designed to hold tight despite severe vibration. Note in F Figure 7-26 6 that it has two sections and is essentially two nuts in one: a locking nut and a load-carrying nut. The two sections are connected with a spring, which is an integral part of the nut. +The Boots self-locking nut is of one piece, all-metal construction designed to hold tight despite severe vibration. Note in Figure 7-26 that it has two sections and is essentially two nuts in one: a locking nut and a load-carrying nut. The two sections are connected with a spring, which is an integral part of the nut. The spring keeps the locking and load-carrying sections such a distance apart that the two sets of threads are out of phase or spaced so that a bolt, which has been screwed through the load-carrying section, must push the locking section outward against the force of the spring to engage the threads of the locking section properly. @@ -12,20 +12,20 @@ The spring, through the medium of the locking section, exerts a constant locking Boots self-locking nuts are made with three different spring styles and in various shapes and sizes. The wing type that is - - Figure 7-26. Self-locking nuts. -the most common ranges in size for No. 6 up to 1 ⁄ 1 ⁄4 ⁄4 inch, the Rol-top ranges from 1 ⁄ 1 ⁄4 inch to 1 ⁄ 1 ⁄6 inch, and the bellows type ⁄4 ⁄6 ranges in size from No. 8 up to 3 ⁄ 3 ⁄8 ⁄8 inch. Wing-type nuts are made of anodized aluminum alloy, cadmium-plated carbon steel, or stainless steel. The Rol-top nut is cadmium-plated steel, and the bellows type is made of aluminum alloy only. + + +the most common ranges in size for No. 6 up to 1 / 4 inch, the Rol-top ranges from 1 / 4 inch to 1 / 6 inch, and the bellows type ranges in size from No. 8 up to 3 / 8 inch. Wing-type nuts are made of anodized aluminum alloy, cadmium-plated carbon steel, or stainless steel. The Rol-top nut is cadmium-plated steel, and the bellows type is made of aluminum alloy only. ## Stainless Steel Self-Locking Nut -The stainless steel self-locking nut may be spun on and off by hand as its locking action takes places only when the nut is seated against a solid surface and tightened. The nut consists of two parts: a case with a beveled locking shoulder and key and a thread insert with a locking shoulder and slotted keyway. Until the nut is tightened, it spins on the bolt easily, because the threaded insert is the proper size for the bolt. However, when the nut is seated against a solid surface and tightened, the locking shoulder of the insert is pulled downward and wedged against the locking shoulder of the case. This action compresses the threaded insert and causes it to clench the bolt tightly. The cross-sectional view in Figure 7-27 7 shows how the key of the case fits into the slotted keyway of the insert so that when the case is turned, the threaded insert is turned with it. Note that the slot is wider than the key. This permits the slot to be narrowed and the insert to be compressed when the nut is tightened. +The stainless steel self-locking nut may be spun on and off by hand as its locking action takes places only when the nut is seated against a solid surface and tightened. The nut consists of two parts: a case with a beveled locking shoulder and key and a thread insert with a locking shoulder and slotted keyway. Until the nut is tightened, it spins on the bolt easily, because the threaded insert is the proper size for the bolt. However, when the nut is seated against a solid surface and tightened, the locking shoulder of the insert is pulled downward and wedged against the locking shoulder of the case. This action compresses the threaded insert and causes it to clench the bolt tightly. The cross-sectional view in Figure 7-27 shows how the key of the case fits into the slotted keyway of the insert so that when the case is turned, the threaded insert is turned with it. Note that the slot is wider than the key. This permits the slot to be narrowed and the insert to be compressed when the nut is tightened. ## Elastic Stop Nut -The elastic stop nut is a standard nut with the height increased to accommodate a fiber locking collar. This - - +The elastic stop nut is a standard nut with the height increased to accommodate a fiber locking collar. This Figure 7-27. Stainless steel self-locking nut. + + diff --git a/tests/pdf_snapshots/pdf/sources/code_and_formula.pdf.md b/tests/snapshots/pdf/sources/code_and_formula.pdf.md similarity index 68% rename from tests/pdf_snapshots/pdf/sources/code_and_formula.pdf.md rename to tests/snapshots/pdf/sources/code_and_formula.pdf.md index 9fcafb6d..ebb09fab 100644 --- a/tests/pdf_snapshots/pdf/sources/code_and_formula.pdf.md +++ b/tests/snapshots/pdf/sources/code_and_formula.pdf.md @@ -1,12 +1,14 @@ ## JavaScript Code Example -Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eir mod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam volup tua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ip sum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. +Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, -Listing 1: Simple JavaScript Program +``` +function add(a, b) { return a + b; } console.log(add(3, 5)); +``` -function add ( a , b ) { return a + b ; } console log ( add (3 , 5) ) ; . +Listing 1: Simple JavaScript Program Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. @@ -14,11 +16,11 @@ Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie co ## Formula -Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eir mod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam volup tua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ip sum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. +Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt. -a 2 + 8 = 12 + Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. diff --git a/tests/snapshots/pdf/sources/multi_page.pdf.md b/tests/snapshots/pdf/sources/multi_page.pdf.md new file mode 100644 index 00000000..308d5d47 --- /dev/null +++ b/tests/snapshots/pdf/sources/multi_page.pdf.md @@ -0,0 +1,87 @@ +## The Evolution of the Word Processor + +The concept of the word processor predates modern computers and has evolved through several technological milestones. + +## Pre-Digital Era (19th - Early 20th Century) + +The origins of word processing can be traced back to the invention of the typewriter in the mid-19th century. Patented in 1868 by Christopher Latham Sholes, the typewriter revolutionized written communication by enabling people to produce legible, professional documents more efficiently than handwriting. + +During this period, the term "word processing" didn't exist, but the typewriter laid the groundwork for future developments. Over time, advancements such as carbon paper (for copies) and the electric typewriter (introduced by IBM in 1935) improved the speed and convenience of document creation. + +## The Birth of Word Processing (1960s - 1970s) + +The term "word processor" first emerged in the 1960s and referred to any system designed to streamline written communication and document production. Early word processors were not software programs but rather standalone machines. + +- IBM MT/ST (Magnetic Tape/Selectric Typewriter) : Introduced in 1964, this machine combined IBM's Selectric typewriter with magnetic tape storage. It allowed users to record, edit, and replay typed content-an early example of digital text storage. +- Wang Laboratories : In the 1970s, Wang introduced dedicated word processing machines. These devices, like the Wang 1200, featured small screens and floppy disks, making them revolutionary for their time. + +These machines were primarily used in offices, where secretarial pools benefited from their ability to make revisions without retyping entire documents. + +## The Rise of Personal Computers (1980s) + +The advent of personal computers in the late 1970s and early 1980s transformed word processing from a niche tool to an essential technology for businesses and individuals alike. + +- WordStar (1978) : Developed for the CP/M operating system, WordStar was one of the first widely used word processing programs. It featured early examples of modern features like cut, copy, and paste. +- Microsoft Word (1983) : Microsoft launched Word for MS-DOS in 1983, introducing a graphical user interface (GUI) and mouse support. Over the years, Microsoft Word became the industry standard for word processing. + +Other notable software from this era included WordPerfect, which was popular among legal professionals, and Apple's MacWrite, which leveraged the Macintosh's graphical capabilities. + +## The Modern Era (1990s - Present) + +By the 1990s, word processing software had become more sophisticated, with features like spell check, grammar check, templates, and collaborative tools. + +- Microsoft Office Suite : Microsoft continued to dominate with its Office Suite, integrating Word with other productivity tools like Excel and PowerPoint. +- OpenOffice and LibreOffice : Open-source alternatives emerged in the early 2000s, offering free and flexible word processing options. +- Google Docs (2006) : The introduction of cloud-based word processing revolutionized collaboration. Google Docs enabled real-time editing and sharing, making it a staple for teams and remote work. + +## Future of Word Processing + +Today, word processors are more than just tools for typing. They integrate artificial intelligence for grammar and style suggestions (e.g., Grammarly), voice-to-text features, and advanced layout options. As AI continues to advance, word processors may evolve into even more intuitive tools that predict user needs, automate repetitive tasks, and support richer multimedia integration. + +From the clunky typewriters of the 19th century to the AI-powered cloud tools of today, the word processor has come a long way. It remains an essential tool for communication and creativity, shaping how we write and share ideas. + +## Specialized Word Processing Tools + +In addition to general-purpose word processors, specialized tools have emerged to cater to specific industries and needs. These tools incorporate unique features tailored to their users' workflows: + +- Academic and Technical Writing : Tools like LaTeX gained popularity among academics, scientists, and engineers. Unlike traditional word processors, LaTeX focuses on precise formatting, particularly for complex mathematical equations, scientific papers, and technical documents. It relies on a markup language to produce polished documents suitable for publishing. +- Screenwriting Software : For screenwriters, tools like Final Draft and Celtx are specialized to handle scripts for film and television. These programs automate the formatting of dialogue, scene descriptions, and other elements unique to screenwriting. +- Legal Document Processors : Word processors tailored for legal professionals, like WordPerfect, offered features such as redlining (early version tracking) and document comparison. Even today, many law firms rely on these tools due to their robust formatting options for contracts and legal briefs. + +## Key Features That Changed Word Processing + +The evolution of word processors wasn't just about hardware or software improvements-it was about the features that revolutionized how people wrote and edited. Some of these transformative features include: + +1. Undo/Redo : Introduced in the 1980s, the ability to undo mistakes and redo actions made experimentation and error correction much easier. +2. Spell Check and Grammar Check : By the 1990s, these became standard, allowing users to spot errors automatically. +3. Templates : Pre-designed formats for documents, such as resumes, letters, and invoices, helped users save time. +4. Track Changes : A game-changer for collaboration, this feature allowed multiple users to suggest edits while maintaining the original text. +5. Real-Time Collaboration : Tools like Google Docs and Microsoft 365 enabled multiple users to edit the same document simultaneously, forever changing teamwork dynamics. + +## The Cultural Impact of Word Processors + +The word processor didn't just change workplaces-it changed culture. It democratized writing, enabling anyone with access to a computer to produce professional-quality documents. This shift had profound implications for education, business, and creative fields: + +- Accessibility : Writers no longer needed expensive publishing equipment or training in typesetting to create polished work. This accessibility paved the way for selfpublishing, blogging, and even fan fiction communities. +- Education : Word processors became a cornerstone of education, teaching students not only how to write essays but also how to use technology effectively. Features like bibliography generators and integrated research tools enhanced learning. +- Creative Writing : Writers gained powerful tools to organize their ideas. Programs like Scrivener allowed authors to manage large projects, from novels to screenplays, with features like chapter outlines and character notes. + +## Word Processors in a Post-Digital Era + +As we move further into the 21st century, the role of the word processor continues to evolve: + +1. Artificial Intelligence : Modern word processors are leveraging AI to suggest content improvements. Tools like Grammarly, ProWritingAid, and even native features in Word now analyze tone, conciseness, and clarity. Some AI systems can even generate entire paragraphs or rewrite sentences. +2. Integration with Other Tools : Word processors are no longer standalone. They integrate with task managers, cloud storage, and project management platforms. For instance, Google Docs syncs with Google Drive, while Microsoft Word integrates seamlessly with OneDrive and Teams. +3. Voice Typing : Speech-to-text capabilities have made word processing more accessible, particularly for those with disabilities. Tools like Dragon NaturallySpeaking and built-in options in Google Docs and Microsoft Word have made dictation mainstream. +4. Multimedia Documents : Word processing has expanded beyond text. Modern tools allow users to embed images, videos, charts, and interactive elements, transforming simple documents into rich multimedia experiences. +5. Cross-Platform Accessibility : Thanks to cloud computing, documents can now be accessed and edited across devices. Whether you're on a desktop, tablet, or smartphone, you can continue working seamlessly. + +## A Glimpse Into the Future + +The word processor's future lies in adaptability and intelligence. Some exciting possibilities include: + +- Fully AI-Assisted Writing : Imagine a word processor that understands your writing style, drafts emails, or creates entire essays based on minimal input. +- Immersive Interfaces : As augmented reality (AR) and virtual reality (VR) technology advance, users may be able to write and edit in 3D spaces, collaborating in virtual environments. +- Hyper-Personalization : Word processors could offer dynamic suggestions based on industry-specific needs, user habits, or even regional language variations. + +The journey of the word processor-from clunky typewriters to AI-powered platformsreflects humanity's broader technological progress. What began as a tool to simply replace handwriting has transformed into a powerful ally for creativity, communication, and collaboration. As technology continues to advance, the word processor will undoubtedly remain at the heart of how we express ideas and connect with one another. diff --git a/tests/pdf_snapshots/pdf/sources/normal_4pages.pdf.md b/tests/snapshots/pdf/sources/normal_4pages.pdf.md similarity index 58% rename from tests/pdf_snapshots/pdf/sources/normal_4pages.pdf.md rename to tests/snapshots/pdf/sources/normal_4pages.pdf.md index c5c18380..074f6236 100644 --- a/tests/pdf_snapshots/pdf/sources/normal_4pages.pdf.md +++ b/tests/snapshots/pdf/sources/normal_4pages.pdf.md @@ -4,43 +4,39 @@ 발행일 2020년 4월 2일 -2020년 4월 2일 발행일 발행처 국회입법조사처 발행인 김하중 국회입법조사처장 www.nars.go.kr +발행일 2020년 4월 2일 발행처 국회입법조사처 발행인 김하중 국회입법조사처장 www.nars.go.kr 발행처 국회입법조사처 -발행인 김하중 국회입법조사처장 +발행인 김하중 국회입법조사처장 www.nars.go.kr -www.nars.go.kr + + +제1695호 + +## 이슈와 논점 ## 코로나-19 관련 보험약관상 재해보험금 지급문제 및 개선과제 -2020.1.1. 「감염병예방법」 관련 규정이 변경되어 적용됨에 따라, 세계적 유행(Pandemic) 단계에 돌 입하였다고 세계보건기구(WHO)가 인정한 코로나-1 9와 관련하여, 보험회사에서 그동안 판매했거나 향후 판매하게 될 보험상품의 입원 및 사망의 재해 인정 여부에 대하여 보험실무상 혼선이 초래되어 이 에 대하여 보험약관의 현황 및 문제점을 살 펴보고 그에 따른 개선방안을 제시하고자 하였다. +김 창 호* -## 들어가며 +2020.1.1. 「감염병예방법」 관련 규정이 변경되어 적용됨에 따라, 세계적 유행(Pandemic) 단계에 돌 입하였다고 세계보건기구(WHO)가 인정한 코로나-19와 관련하여, 보험회사에서 그동안 판매했거나 향후 판매하게 될 보험상품의 입원 및 사망의 재해 인정 여부에 대하여 보험실무상 혼선이 초래되어 이 에 대하여 보험약관의 현황 및 문제점을 살펴보고 그에 따른 개선방안을 제시하고자 하였다. -1 +## 1 들어가며 -2020.3.30. 0시 기준 현재 “코로나바이러스감염 증-19(COVID-19, 이하 “코로나-19”)”의 국내 확 진자는 9,661명, 사망자는 158명으로 나타났다. +2020.3.30. 0시 기준 현재 "코로나바이러스감염 증-19(COVID-19, 이하 "코로나-19")"의 국내 확 진자는 9,661명, 사망자는 158명으로 나타났다. 이와 관련하여 세계보건기구(WHO)는 지난 2020. 3.11. 코로나-19가 세계적 유행(Pandemic) 단계 에 돌입하였음을 선언하였다. 한편 코로나-19가 전 세계적 유행단계에 돌입한 와중에 국내 보험업계에서는 코로나-19를 과연 질 병으로 보아야 할지, 상해 1) 나 재해 2) 로 보아야 할지 -1) 손해보험의 표준약관 규정에 따르면, 보험기간 중에 발생한 급격하고도 우연한 외래의 사고로 신체에 입은 상해라고 규정하고 있는데, 즉, “급 격성, 우연성, 외래성”을 충족하는 사고를 상해로 정의함 - -2) 생명보험은 표준약관 “재해분류표”에서 “우발적인 외래의 사고”를 재 해라고 정의하며 보장대상이 되는 재해는 다음 중 어느 하나에 해당하 는 것을 말함 +1) 손해보험의 표준약관 규정에 따르면, 보험기간 중에 발생한 급격하고도 우연한 외래의 사고로 신체에 입은 상해라고 규정하고 있는데, 즉, "급 격성, 우연성, 외래성"을 충족하는 사고를 상해로 정의함 -1) 한국표준질병·사인분류상의 ‘S80~Y84'에 해당하는 우발적인 외래의 사고 +2) 생명보험은 표준약관 "재해분류표"에서 "우발적인 외래의 사고"를 재 해라고 정의하며 보장대상이 되는 재해는 다음 중 어느 하나에 해당하 는 것을 말함 -2) 감염병의 예방 및 관리에 관한 법률 제2조 제2호에서 규정한 감염병 그러나, 약관상 한국표준질병·사인분류상의 U00~U99에 해당하는 +1) 한국표준질병·사인분류상의 'S80~Y84'에 해당하는 우발적인 외래의 사고 - - -제1695호 - -## 이슈 와 와 논점 - -김 창 호* +1) 한국표준질병·사인분류상의 'S80~Y84'에 해당하는 우발적인 외래의 사고 2) 감염병의 예방 및 관리에 관한 법률 제2조 제2호에서 규정한 감염병 그러나, 약관상 한국표준질병·사인분류상의 U00~U99에 해당하는 이슈가 될 것으로 판단된다. @@ -58,62 +54,50 @@ www.nars.go.kr ## (1) 「감염병의 예방 및 관리에 관한 법률」 개정 -2020.1.1. 시행된 3) 「감염병의 예방 및 관리에 관 한 법률」(이하 ‘감염병예방법’) 제2조 제2호에 의하 면 제1급감염병이란 생물테러감염병 또는 치명률 이 높거나 집단 발생의 우려가 커서 발생 또는 유행 즉시 신고하여야 하고, 음압격리와 같은 높은 수준 의 격리가 필요한 감염병으로서 제2호 각 목4 목4) 에 규 정된 감염병을 말한다. +3) 「감염병의 예방 및 관리에 관 2020.1.1. 시행된 한 법률」(이하 '감염병예방법') 제2조 제2호에 의하 면 제1급감염병이란 생물테러감염병 또는 치명률 이 높거나 집단 발생의 우려가 커서 발생 또는 유행 즉시 신고하여야 하고, 음압격리와 같은 높은 수준 의 격리가 필요한 감염병으로서 제2호 각 목 4) 에 규 정된 감염병을 말한다. 다만, 갑작스러운 국내 유입 또는 유행이 예견되 어 긴급한 예방ㆍ관리가 필요하여 보건복지부장관 이 지정하는 감염병을 포함한다고 설명하고 있다. [표 1] 감염병예방법 제2조제2호 개정전·후 비교 -| 구분 | | 개정전 | | 개정후 | -|------|----------------------|-------|------------------------|-------| -| 분류 | 1군 감염병 1급 감염병 | | | | -| | ◦ 마시는 물 또는 식품을 매개로 | | ◦ 생물테러감염병 또는 치명률이 | | -| 분류 | | | | | -| | 발생하고 집단 발생의 우려가 | | 높거나 집단 발생의 우려가 커 높 | | -| 기준 | | | | | -| | 큰 감염병 | | 은 수준의 격리가 필요한 감염병 | | -| | ◦ (6종) 콜레라, 장티푸스, 파라 | | ◦ (17종) 에볼라, 페스트 등 | | -| 대상 | | | * 좌측 6종(2급 감염병 분류)은 | | -| | 티푸스, 세균성이질, 장출혈 | | | | -| 질병 | | | | | -| | 성대장균감염증, A형간염 | | 미포함 | | -| | | | ◦ 대상질병에 U코드 일부(3종) | | -| | | | 포함 | | -| U코드 | ◦ 대상질병에 U코드 없음 | | ① 신종감염병증후군 → 코로나19(U) | | -| | | | ② 중증급성호흡기증후군(SARS) (U) | | -| | | | ③ 중동호흡기증후군(MERS)(U) | | +| 구분 | 개정전 | 개정후 | +|-------|----------------------------------------------------|----------------------------------------------------------------------------------------| +| 분류 | 1군 감염병 | 1급 감염병 | +| 분류 기준 | ◦ 마시는 물 또는 식품을 매개로 발생하고 집단 발생의 우려가 큰 감염병 | ◦ 생물테러감염병 또는 치명률이 높거나 집단 발생의 우려가 커 높 은 수준의 격리가 필요한 감염병 | +| 대상 질병 | ◦ (6종) 콜레라, 장티푸스, 파라 티푸스, 세균성이질, 장출혈 성대장균감염증, A형간염 | ◦ (17종) 에볼라, 페스트 등 * 좌측 6종(2급 감염병 분류)은 미포함 | +| U코드 | ◦ 대상질병에 U코드 없음 | ◦ 대상질병에 U코드 일부(3종) 포함 ① 신종감염병증후군 → 코로나19(U) ② 중증급성호흡기증후군(SARS) (U) ③ 중동호흡기증후군(MERS)(U) | ※ 주: 2020.1.1. 기준 -※ 자료: 생명보험협회, ‘20.3.11. +※ 자료: 생명보험협회, '20.3.11. -기존 생명보험에서 재해로 보장하는 법정1군 전염 병은 “콜레라, 장티푸스, 파라티푸스, 세균성이질, 장 출혈성대장균감염증, A형간염”이었으나 이번에 개 +기존 생명보험에서 재해로 보장하는 법정1군 전염 병은 "콜레라, 장티푸스, 파라티푸스, 세균성이질, 장 출혈성대장균감염증, A형간염"이었으나 이번에 개 -3) 개정 이유는 질환의 특성별 ‘군(群)’별로 구분되어 있는 현행 감염병 분 류체계를 감염병의 심각도ㆍ전파력ㆍ격리수준ㆍ신고시기 등을 중심으 로 한 ‘급(級)’별 분류체계로 개편하고, 감염병 위기상황 발생 시 컨트롤 타워 역할을 수행할 수 있는 긴급상황실의 설치ㆍ운영과 감염병환자와 접촉한 자를 격리할 수 있는 접촉자격리시설의 지정을 위한 법적 근거 를 신설하며, 감염병관리위원회 위원장을 보건복지부차관에서 질병관 리본부장으로 변경하는 등 감염병 발생 시 보다 효율적인 대처가 이루 어질 수 있도록 현행 감염병 관리체계를 개선ㆍ보완하려는 것임. +3) 개정 이유는 질환의 특성별 '군(群)'별로 구분되어 있는 현행 감염병 분 류체계를 감염병의 심각도ㆍ전파력ㆍ격리수준ㆍ신고시기 등을 중심으 로 한 '급(級)'별 분류체계로 개편하고, 감염병 위기상황 발생 시 컨트롤 타워 역할을 수행할 수 있는 긴급상황실의 설치ㆍ운영과 감염병환자와 접촉한 자를 격리할 수 있는 접촉자격리시설의 지정을 위한 법적 근거 를 신설하며, 감염병관리위원회 위원장을 보건복지부차관에서 질병관 리본부장으로 변경하는 등 감염병 발생 시 보다 효율적인 대처가 이루 어질 수 있도록 현행 감염병 관리체계를 개선ㆍ보완하려는 것임. -4) 2. 가. ~ 더.; 에볼라바이러스병, 마버그열, 라싸열, 크리미안콩고출혈 열, 남아메리카출혈열, 리프트밸리열, 두창, 페스트, 탄저, 보툴리눔독 신종감염병증후군, 중증급성호흡기증후군(SARS), 중동 소증, 야토병, 호흡기증후군(MERS), 동물인플루엔자 인체감염증, 신종인플루엔자, 디프테리아 등 17종 +4) 2. 가. ~ 더.; 에볼라바이러스병, 마버그열, 라싸열, 크리미안콩고출혈 열, 남아메리카출혈열, 리프트밸리열, 두창, 페스트, 탄저, 보툴리눔독 소증, 야토병, 신종감염병증후군, 중증급성호흡기증후군(SARS), 중동 호흡기증후군(MERS), 동물인플루엔자 인체감염증, 신종인플루엔자, 디프테리아 등 17종 -정된 법에서 이들은 제2급감염병으로 변경되었다. 대신에 「감염병예방법」 제1급감염병으로 “에볼 라바이러스병, ~ 신종감염증후군, SARS, MERS, ~ 디프테리아”등 17종이 새롭게 포함되었다. +정된 법에서 이들은 제2급감염병으로 변경되었다. 대신에 「감염병예방법」 제1급감염병으로 "에볼 라바이러스병, ~ 신종감염증후군, SARS, MERS, ~ 디프테리아"등 17종이 새롭게 포함되었다. ## (2) 생명보험 표준약관 재해분류표 -현행 생명보험 표준약관상 재해분류표5 표5) 는 위 「감염병예방법」 제2조 제2호의 제1급 감염병들을 질병임에도 불구하고 보장대상이 되는 ‘재해’로 규 정하고 있다. +현행 생명보험 표준약관상 재해분류표 5) 는 위 「감염병예방법」 제2조 제2호의 제1급 감염병들을 질병임에도 불구하고 보장대상이 되는 '재해'로 규 정하고 있다. -그러나 제1급 감염병에 포함되는 질병임에도 불 구하고, 생명보험 표준약관 재해분류표의 한국표 준질병·사인분류6 류6) (이하 ‘KCD’라 함)상 U코드 (U00~U99)에 해당하는 질병들(SARS-U04.9, MERS-U19.9 등)은 보장제외 대상으로 분류되어 보험금을 지급하지 않는 재해로 규정되어 있다. +그러나 제1급 감염병에 포함되는 질병임에도 불 구하고, 생명보험 표준약관 재해분류표의 한국표 준질병·사인분류 6) (이하 'KCD'라 함)상 U코드 (U00~U99)에 해당하는 질병들(SARS-U04.9, MERS-U19.9 등)은 보장제외 대상으로 분류되어 보험금을 지급하지 않는 재해로 규정되어 있다. -코로나-19 역시 KCD 수록 정식 명칭은 “코로나 바이러스 질환 2019”로 질병분류기호는 “U07.1” 로 표시하고 있어서 보험금이 지급되지 않는 재해 로 분류되어 재해보험금 지급대상에 포함되지 않는 다고 해석될 수 있다. +코로나-19 역시 KCD 수록 정식 명칭은 "코로나 바이러스 질환 2019"로 질병분류기호는 "U07.1" 로 표시하고 있어서 보험금이 지급되지 않는 재해 로 분류되어 재해보험금 지급대상에 포함되지 않는 다고 해석될 수 있다. -한편, 현재 생명보험 표준약관은 2020.1.1.부터 신규 판매되고 있는 보험상품의 약관이며 해당 약 관에는 아직 상기 법 개정사항이 반영되지 않은 상 황이지만, 재해분류표를 보면 별도의 각주를 통해 “감염병에 관한 법률이 제·개정될 경우, 보험사고 발생 당시 제·개정된 법률을 적용합니다.”라고 명 시되어 코로나-19를 재해보험금 지급대상에 포함 되는 것으로도 해석할 수 있다. +한편, 현재 생명보험 표준약관은 2020.1.1.부터 신규 판매되고 있는 보험상품의 약관이며 해당 약 관에는 아직 상기 법 개정사항이 반영되지 않은 상 황이지만, 재해분류표를 보면 별도의 각주를 통해 "감염병에 관한 법률이 제·개정될 경우, 보험사고 발생 당시 제·개정된 법률을 적용합니다."라고 명 시되어 코로나-19를 재해보험금 지급대상에 포함 되는 것으로도 해석할 수 있다. - (3) 「약관의 규제에 관한 법률」상 약관해석의 원칙 현재 「약관의 규제에 관한 법률」 7) 을 보면 약관은 5) 「생명보험 표준약관 부표4」 -6) 한국표준질병사인분류(Korean Standard Cl assification of Diseases, “KCD”)는 대한민국에서 의무기록자료 및 사망원인통계조사 등 질병이 환 및 사망자료를 그 성질의 유사성에 따라 체계적으로 유형화한 것으로, 모든 형태의 보건 및 인구동태 기록에 기재되어 있는 질병 및 기타 보건 문제를 분류하는데 이용하기 위하여 설정한 으로 통계청에서 작성함 +6) 한국표준질병사인분류(Korean Standard Classification of Diseases, "KCD")는 대한민국에서 의무기록자료 및 사망원인통계조사 등 질병이 환 및 사망자료를 그 성질의 유사성에 따라 체계적으로 유형화한 것으로, 모든 형태의 보건 및 인구동태 기록에 기재되어 있는 질병 및 기타 보건 문제를 분류하는데 이용하기 위하여 설정한 으로 통계청에서 작성함 7) 제5조(약관의 해석) ① 약관은 신의성실의 원칙에 따라 공정하게 해석 되어야 하며 고객에 따라 다르게 해석되어서는 아니 된다. ② 약관의 뜻이 명백하지 아니한 경우에는 고객에게 유리하게 해석되어 야 한다. -작성자인 사업자에 의하여 일방적으로 유리하게 작 성되고 고객에게는 그 약관내용에 관한 교섭이나 검토의 기회가 제대로 주어지지 않는 것이 일반적 이므로 이러한 형성과정에 비추어 고객보호의 측면 에서 약관내용이 명백하지 못하거나 의심스러운 때 에는 고객에게 유리하게 해석되어야 한다는 ‘작성 자 불이익의 해석원칙’이 있다. +작성자인 사업자에 의하여 일방적으로 유리하게 작 성되고 고객에게는 그 약관내용에 관한 교섭이나 검토의 기회가 제대로 주어지지 않는 것이 일반적 이므로 이러한 형성과정에 비추어 고객보호의 측면 에서 약관내용이 명백하지 못하거나 의심스러운 때 에는 고객에게 유리하게 해석되어야 한다는 '작성 자 불이익의 해석원칙'이 있다. ## (4) 생보업계의 재해보험금 지급에 대한 의견 @@ -123,9 +107,9 @@ www.nars.go.kr ## (1) 상위법에 반하는 보험약관의 해석 -최근 코로나-19는 개정 법령에서 정한 법정감염 병 1급에 해당하는 17종 중 “신종감염병증후군”으 로 분류할 수 있다고 볼 수 있어 재해보상 대상이라 는 주장과 보장제외 대상인 U코드에 해당하여 재해 보장대상에서 제외해야 한다는 일부 생명보험사의 주장 등 의견이 상반된다. +최근 코로나-19는 개정 법령에서 정한 법정감염 병 1급에 해당하는 17종 중 "신종감염병증후군"으 로 분류할 수 있다고 볼 수 있어 재해보상 대상이라 는 주장과 보장제외 대상인 U코드에 해당하여 재해 보장대상에서 제외해야 한다는 일부 생명보험사의 주장 등 의견이 상반된다. -따라서 법정1급 감염병에 포함된 17종의 질환이 보험약관 재해분류표 상 재해에 해당되지만 기존의 “SARS(U04.9)”, “MERS(U19.9)”를 포함하여 “코로 나-19(U07.1)”는 재해분류표 상 면책사유(U00~09) 에 포함된다고 생명보험사가 주장할 경우 보험약관 이 상위법인 「감염병예방법」 개정취지에 반하는 결 과를 가져오게 되는 상황이 발생한다. +따라서 법정1급 감염병에 포함된 17종의 질환이 보험약관 재해분류표 상 재해에 해당되지만 기존의 "SARS(U04.9)", "MERS(U19.9)"를 포함하여 "코로 나-19(U07.1)"는 재해분류표 상 면책사유(U00~09) 에 포함된다고 생명보험사가 주장할 경우 보험약관 이 상위법인 「감염병예방법」 개정취지에 반하는 결 과를 가져오게 되는 상황이 발생한다. ## (2) 감독당국의 표준약관 개정작업 소홀 @@ -137,7 +121,7 @@ www.nars.go.kr ## (3) 보험사의 보험금 지급실무상 혼선 초래 -보험업계는 보험은 사고 위험의 예측가능성과, 8) 보험의 기본원리인 대수의 법칙 이나 수지상등의 원칙 9) 에 부합하고, 최대 손실을 보험회사가 감당할 수 있어야 한다고 주장한다. +보험업계는 보험은 사고 위험의 예측가능성과, 보험의 기본원리인 대수의 법칙 8) 이나 수지상등의 9) 원칙 에 부합하고, 최대 손실을 보험회사가 감당할 수 있어야 한다고 주장한다. 특히, 신종감염병증후군과 신종인플루엔자는 특 정 질병이 아닌 앞으로 새롭게 발생할 모든 신종감 염병을 포괄하는 개념으로 위험률 측정이 불가능하 고, 담보 범위도 확정할 수도 없다고 주장한다. @@ -165,7 +149,7 @@ www.nars.go.kr 우선 「감염병예방법」 변경에 따른 감독당국의 조속한 표준약관 개정작업이 진행되어야 할 필요가 있다. -보험사가 생명보험에서 ‘일부 감염병’을 재해로 보장하는 이유는 ‘일부 감염병’이 우연성, 외래성, 급격성 등 재해의 특성을 지니고 있기 때문이며, 실 례로 페스트는 질병이지만 재해에 준하는 급격성도 지니고 있어, 정책적으로 재해로 취급하여 보험의 보장 범위를 확대한 바 있다. +보험사가 생명보험에서 '일부 감염병'을 재해로 보장하는 이유는 '일부 감염병'이 우연성, 외래성, 급격성 등 재해의 특성을 지니고 있기 때문이며, 실 례로 페스트는 질병이지만 재해에 준하는 급격성도 지니고 있어, 정책적으로 재해로 취급하여 보험의 보장 범위를 확대한 바 있다. 코로나-19 역시 질병이지만 세계적 유행단계에 돌입하는 등 페스트와 같은 재해에 준하는 성격을 포함하고 있어 이를 재해로 인정할 필요가 있다. @@ -175,7 +159,7 @@ www.nars.go.kr 보험사는 기후변화, 전염병 등과 같은 신종위험 으로 인한 사회적 손실이 증가하는 추세에 있는바 손실이 광범위하고 직·간접적이어서 손해 규모를 측정하기 어려운 경우를 대비한 보험상품을 개발할 필요가 있다. -따라서 감염병 보험, 파라메트릭(Parametric Insurance)보험 10) , 인덱스(Index)보험 등과 같이 실제 발생한 손실액이 아니라 특정 지표에 의해 보 험금이 지급되는 신종보험상품을 개발 보급 판매할 필요가 점진적으로 증가하고 있다. +따라서 감염병 보험, 파라메트릭(Parametric Insurance)보험 10) , 인덱스(Index)보험 등과 같이 실제 발생한 손실액이 아니라 특정 지표에 의해 보 험금이 지급되는 신종보험상품을 개발 보급 판매할 필요가 점진적으로 증가하고 있다. ## 5 맺으며 @@ -187,7 +171,7 @@ www.nars.go.kr 코로나-19로 인한 국민의 경제손실을 보충하고 보험의 기본원리에 충실한 경제제도로서의 역할을 수행하도록 금융감독당국과 보험업계의 현명하고 빠른 보험약관의 제도적 보완이 필요한 시점이다. -󰡔 이슈와 논점 󰡕 은 국회의원의 입법활동을 지원하기 위해 최신 국내외 동향 및 현안에 대해 수시로 발간하는 정보 소식지입니다. +이슈와 논점 은 국회의원의 입법활동을 지원하기 위해 최신 국내외 동향 및 현안에 대해 수시로 발간하는 정보 소식지입니다. 10) 인덱스 보험이라고도 불리며, 손실규모를 측정하기 어려운 홍수나 자 연재해 리스크를 보상하는 보험으로 실제로 발생한 손실금액을 보상 하는 실손보상의 원칙이 적용되지 않고 강수량, 풍속, 온도 등과 같은 개관적인 지표에 의해서 보상이 결정되는 보험을 말함 diff --git a/tests/pdf_snapshots/pdf/sources/picture_classification.pdf.md b/tests/snapshots/pdf/sources/picture_classification.pdf.md similarity index 76% rename from tests/pdf_snapshots/pdf/sources/picture_classification.pdf.md rename to tests/snapshots/pdf/sources/picture_classification.pdf.md index 5a14c469..b12796ac 100644 --- a/tests/pdf_snapshots/pdf/sources/picture_classification.pdf.md +++ b/tests/snapshots/pdf/sources/picture_classification.pdf.md @@ -1,17 +1,17 @@ ## Figures Example -Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eir mod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam volup tua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ip sum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. - - +Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Figure 1: This is an example image. + + Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. - - Figure 2: This is an example image. + + Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. diff --git a/tests/snapshots/pdf/sources/redp5110_sampled.pdf.md b/tests/snapshots/pdf/sources/redp5110_sampled.pdf.md new file mode 100644 index 00000000..3d344d7c --- /dev/null +++ b/tests/snapshots/pdf/sources/redp5110_sampled.pdf.md @@ -0,0 +1,358 @@ + + +## Row and Column Access Control Support in IBM DB2 for i + +Implement roles and separation of duties + + + +Leverage row permissions on the database + +Protect columns by defining column masks ibm.com /redbooks + +Jim Bainbridge Hernando Bedoya Rob Bestgen Mike Cain Dan Cruikshank Jim Denton Doug Mack Tom McKinley Kent Milligan + +Redpaper + +## Contents + + + +Solution Brief + + + +## Highlights + +-                +-                     +-       !   " #  +-  ! #      " "       + + + +Power Services + +## DB2 for i Center of Excellence + +Expert help to achieve your business requirements + +## We build confident, satisfied clients + +No one else has the vast consulting experiences, skills sharing and renown service offerings to do what we can do for you. + +Because no one else is IBM. + +With combined experiences and direct access to development groups, we're the experts in IBM DB2® for i. The DB2 for i Center of Excellence (CoE) can help you achieve-perhaps reexamine and exceed-your business requirements and gain more confidence and satisfaction in IBM product data management products and solutions. + +## Who we are, some of what we do + +Global CoE engagements cover topics including: + +- r Database performance and scalability +- r Advanced SQL knowledge and skills transfer +- r Business intelligence and analytics +- r DB2 Web Query +- r Query/400 modernization for better reporting and analysis capabilities +- r Database modernization and re-engineering +- r Data-centric architecture and design +- r Extremely large database and overcoming limits to growth +- ISV education and enablement r + +## Preface + +This IBM® Redpaper™ publication provides information about the IBM i 7.2 feature of IBM DB2® for i Row and Column Access Control (RCAC). It offers a broad description of the function and advantages of controlling access to data in a comprehensive and transparent way. This publication helps you understand the capabilities of RCAC and provides examples of defining, creating, and implementing the row permissions and column masks in a relational database environment. + +This paper is intended for database engineers, data-centric application developers, and security officers who want to design and implement RCAC as a part of their data control and governance policy. A solid background in IBM i object level security, DB2 for i relational database concepts, and SQL is assumed. + +## Authors + +This paper was produced by the IBM DB2 for i Center of Excellence team in partnership with the International Technical Support Organization (ITSO), Rochester, Minnesota US. + + + +Jim Bainbridge is a senior DB2 consultant on the DB2 for i Center of Excellence team in the IBM Lab Services and Training organization. His primary role is training and implementation services for IBM DB2 Web Query for i and business analytics. Jim began his career with IBM 30 years ago in the IBM Rochester Development Lab, where he developed cooperative processing products that paired IBM PCs with IBM S/36 and AS/.400 systems. In the years since, Jim has held numerous technical roles, including independent software vendors technical support on a broad range of IBM technologies and products, and supporting customers in the IBM Executive Briefing Center and IBM Project Office. + + + +Hernando Bedoya is a Senior IT Specialist at STG Lab Services and Training in Rochester, Minnesota. He writes extensively and teaches IBM classes worldwide in all areas of DB2 for i. Before joining STG Lab Services, he worked in the ITSO for nine years writing multiple IBM Redbooks® publications. He also worked for IBM Colombia as an IBM AS/400® IT Specialist doing presales support for the Andean countries. He has 28 years of experience in the computing field and has taught database classes in Colombian universities. He holds a Master's degree in Computer Science from EAFIT, Colombia. His areas of expertise are database technology, performance, and data warehousing. Hernando can be contacted at hbedoya@us.ibm.com . + + + +## 1 + +## Securing and protecting IBM DB2 data + +Recent news headlines are filled with reports of data breaches and cyber-attacks impacting 1 reports that almost 5000 global businesses of all sizes. The Identity Theft Resource Center data breaches have occurred since 2005, exposing over 600 million records of data. The financial cost of these data breaches is skyrocketing. Studies from the Ponemon Institute2 revealed that the average cost of a data breach increased in 2013 by 15% globally and resulted in a brand equity loss of $9.4 million per attack. The average cost that is incurred for each lost record containing sensitive information increased more than 9% to $145 per record. + +Businesses must make a serious effort to secure their data and recognize that securing information assets is a cost of doing business. In many parts of the world and in many industries, securing the data is required by law and subject to audits. Data security is no longer an option; it is a requirement. + +This chapter describes how you can secure and protect data in DB2 for i. The following topics are covered in this chapter: + +- Security fundamentals +- Current state of IBM i security +- DB2 for i security controls + +1 http://www.idtheftcenter.org + +2 http://www.ponemon.org / + +## 1.1 Security fundamentals + +Before reviewing database security techniques, there are two fundamental steps in securing information assets that must be described: + +- First, and most important, is the definition of a company's security policy . Without a security policy, there is no definition of what are acceptable practices for using, accessing, and storing information by who, what, when, where, and how. A security policy should minimally address three things: confidentiality, integrity, and availability. + +The monitoring and assessment of adherence to the security policy determines whether your security strategy is working. Often, IBM security consultants are asked to perform security assessments for companies without regard to the security policy. Although these assessments can be useful for observing how the system is defined and how data is being accessed, they cannot determine the level of security without a security policy. Without a security policy, it really is not an assessment as much as it is a baseline for monitoring the changes in the security settings that are captured. + +A security policy is what defines whether the system and its settings are secure (or not). + +- The second fundamental in securing data assets is the use of resource security . If implemented properly, resource security prevents data breaches from both internal and external intrusions. Resource security controls are closely tied to the part of the security policy that defines who should have access to what information resources. A hacker might be good enough to get through your company firewalls and sift his way through to your system, but if they do not have explicit access to your database, the hacker cannot compromise your information assets. + +With your eyes now open to the importance of securing information assets, the rest of this chapter reviews the methods that are available for securing database resources on IBM i. + +## 1.2 Current state of IBM i security + +Because of the inherently secure nature of IBM i, many clients rely on the default system settings to protect their business data that is stored in DB2 for i. In most cases, this means no data protection because the default setting for the Create default public authority (QCRTAUT) system value is *CHANGE. + +Even more disturbing is that many IBM i clients remain in this state, despite the news headlines and the significant costs that are involved with databases being compromised. This default security configuration makes it quite challenging to implement basic security policies. A tighter implementation is required if you really want to protect one of your company's most valuable assets, which is the data. + +Traditionally, IBM i applications have employed menu-based security to counteract this default configuration that gives all users access to the data. The theory is that data is protected by the menu options controlling what database operations that the user can perform. This approach is ineffective, even if the user profile is restricted from running interactive commands. The reason is that in today's connected world there are a multitude of interfaces into the system, from web browsers to PC clients, that bypass application menus. If there are no object-level controls, users of these newer interfaces have an open door to your data. + +Many businesses are trying to limit data access to a need-to-know basis. This security goal means that users should be given access only to the minimum set of data that is required to perform their job. Often, users with object-level access are given access to row and column values that are beyond what their business task requires because that object-level security provides an all-or-nothing solution. For example, object-level controls allow a manager to access data about all employees. Most security policies limit a manager to accessing data only for the employees that they manage. + +## 1.3.1 Existing row and column control + +Some IBM i clients have tried augmenting the all-or-nothing object-level security with SQL views (or logical files) and application logic, as shown in Figure 1-2. However, application-based logic is easy to bypass with all of the different data access interfaces that are provided by the IBM i operating system, such as Open Database Connectivity (ODBC) and System i Navigator. + +Using SQL views to limit access to a subset of the data in a table also has its own set of challenges. First, there is the complexity of managing all of the SQL view objects that are used for securing data access. Second, scaling a view-based security solution can be difficult as the amount of data grows and the number of users increases. + +Even if you are willing to live with these performance and management issues, a user with *ALLOBJ access still can directly access all of the data in the underlying DB2 table and easily bypass the security controls that are built into an SQL view. + +Figure 1-2 Existing row and column controls + + + +## 2.1.6 Change Function Usage CL command + +The following CL commands can be used to work with, display, or change function usage IDs: + +- Work Function Usage ( WRKFCNUSG ) +- Change Function Usage ( CHGFCNUSG ) +- Display Function Usage ( DSPFCNUSG ) + +For example, the following CHGFCNUSG command shows granting authorization to user HBEDOYA to administer and manage RCAC rules: + +CHGFCNUSG FCNID(QIBM\_DB\_SECADM) USER(HBEDOYA) USAGE(*ALLOWED) + +## 2.1.7 Verifying function usage IDs for RCAC with the FUNCTION\_USAGE view + +The FUNCTION\_USAGE view contains function usage configuration details. Table 2-1 describes the columns in the FUNCTION\_USAGE view. + +Table 2-1 FUNCTION\_USAGE view + +| name | Data type | Description | +|-------------|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------------| +| FUNCTION_ID | VARCHAR(30) | ID of the function. | +| USER_NAME | VARCHAR(10) | Name of the user profile that has a usage setting for this function. | +| USAGE | VARCHAR(7) | authority.Column Usage setting:  ALLOWED: The user profile is allowed to use the function.  DENIED: The user profile is not allowed to use the function. | +| USER_TYPE | VARCHAR(5) | i2.1.6 Type of user profile:  USER: The user profile is a user.  GROUP: The user profile is a group. | + +To discover who has authorization to define and manage RCAC, you can use the query that is shown in Example 2-1. + +Example 2-1 Query to determine who has authority to define and manage RCAC + +| SELECT | functi on_i d, u s er_n ame, u s age, er_type | +|----------|-----------------------------------------------------------------------------------| +| FROM | i2.1.6 functi on_usage functi on_i d=’QIBM_DB_SECADM’ user_name; authority.Column | +| WHERE | | + +## 2.2 Separation of duties + +Separation of duties helps businesses comply with industry regulations or organizational requirements and simplifies the management of authorities. Separation of duties is commonly used to prevent fraudulent activities or errors by a single person. It provides the ability for administrative functions to be divided across individuals without overlapping responsibilities, so that one user does not possess unlimited authority, such as with the *ALLOBJ authority. + +For example, assume that a business has assigned the duty to manage security on IBM i to Theresa. Before release IBM i 7.2, to grant privileges, Theresa had to have the same privileges Theresa was granting to others. Therefore, to grant *USE privileges to the PAYROLL table, Theresa had to have *OBJMGT and *USE authority (or a higher level of authority, such as *ALLOBJ). This requirement allowed Theresa to access the data in the PAYROLL table even though Theresa's job description was only to manage its security. + +In IBM i 7.2, the QIBM\_DB\_SECADM function usage grants authorities, revokes authorities, changes ownership, or changes the primary group without giving access to the object or, in the case of a database table, to the data that is in the table or allowing other operations on the table. + +QIBM\_DB\_SECADM function usage can be granted only by a user with *SECADM special authority and can be given to a user or a group. + +QIBM\_DB\_SECADM also is responsible for administering RCAC, which restricts which rows a user is allowed to access in a table and whether a user is allowed to see information in certain columns of a table. + +A preferred practice is that the RCAC administrator has the QIBM\_DB\_SECADM function usage ID, but absolutely no other data privileges. The result is that the RCAC administrator can deploy and maintain the RCAC constructs, but cannot grant themselves unauthorized access to data itself. + +Table 2-2 shows a comparison of the different function usage IDs and *JOBCTL authority to the different CL commands and DB2 for i tools. + +Table 2-2 Comparison of the different function usage IDs and *JOBCTL authority + +| User action | *JOBCTL | QIBM_DB_SECADM | QIBM_DB_SQLADM | QIBM_DB_SYSMON | No Authority | +|----------------------------------------------------------------------------------|-----------|------------------|------------------|------------------|----------------| +| SET CURRENT DEGREE (SQL statement) | X | | X | | | +| CHGQRYA command targeting a different user's job | X | | X | | | +| STRDBMON or ENDDBMON commands targeting a different user's job | X | | X | | | +| STRDBMON or ENDDBMON commands targeting a job that matches the current user | X | | X | X | X | +| QUSRJOBI() API format 900 or System i Navigator's SQL Details for Job | X | | X | X | | +| Visual Explain within Run SQL scripts | X | | X | X | X | +| Visual Explain outside of Run SQL scripts | X | | X | | | +| ANALYZE PLAN CACHE procedure | X | | X | | | +| DUMP PLAN CACHE procedure | X | | X | | | +| MODIFY PLAN CACHE procedure | X | | X | | | +| 1For MODIFY PLAN CACHE PROPERTIES procedure (currently does not check authority) | X | | X | | | +| CHANGE PLAN CACHE SIZE procedure (currently does not check authority) | X | | X | | | + +The SQL CREATE PERMISSION statement that is shown in Figure 3-1 is used to define and initially enable or disable the row access rules. + +Figure 3-1 CREATE PERMISSION SQL statement + + + +## Column mask + +A column mask is a database object that manifests a column value access control rule for a specific column in a specific table. It uses a CASE expression that describes what you see when you access the column. For example, a teller can see only the last four digits of a tax identification number. + +Table 3-1 summarizes these special registers and their values. + +Table 3-1 Special registers and their corresponding values + +| register | Corresponding value | +|----------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| +| USER or SESSION_USER | The effective user of the thread excluding adopted authority. | +| CURRENT_USER | 9Table logic.Special The effective user of the thread including adopted authority. When no adopted authority is present, this has the same value as USER. | +| SYSTEM_USER | The authorization ID that initiated the connection. | + +Figure 3-5 shows the difference in the special register values when an adopted authority is used: + +- A user connects to the server using the user profile ALICE. +- USER and CURRENT USER initially have the same value of ALICE. +- ALICE calls an SQL procedure that is named proc1, which is owned by user profile JOE and was created to adopt JOE's authority when it is called. +- While the procedure is running, the special register USER still contains the value of ALICE because it excludes any adopted authority. The special register CURRENT USER contains the value of JOE because it includes any adopted authority. +- When proc1 ends, the session reverts to its original state with both USER and CURRENT USER having the value of ALICE. + +Figure 3-5 Special registers and adopted authority + + + +## 3.2.2 Built-in global variables + +Built-in global variables are provided with the database manager and are used in SQL statements to retrieve scalar values that are associated with the variables. + +IBM DB2 for i supports nine different built-in global variables that are read only and maintained by the system. These global variables can be used to identify attributes of the database connection and used as part of the RCAC logic. + +Table 3-2 lists the nine built-in global variables. + +Table 3-2 Built-in global variables + +| variable | Type | Description | +|-----------------------|---------------------|-------------------------------------------------------------------------| +| CLIENT_HOST | VARCHAR(255) | Host name of the current client as returned by the system | +| CLIENT_IPADDR | VARCHAR(128) | TONY')Global IP address of the current client as returned by the system | +| CLIENT_PORT | INTEGER | Port used by the current client to communicate with the server | +| PACKAGE_NAME | VARCHAR(128) | Name of the currently running package | +| PACKAGE_SCHEMA | VARCHAR(128) | Schema name of the currently running package | +| PACKAGE_VERSION | VARCHAR(64) | Version identifier of the currently running package | +| ROUTINE_SCHEMA | VARCHAR(128) | Schema name of the currently running routine | +| ROUTINE_SPECIFIC_NAME | iTable VARCHAR(128) | Name of the currently running routine | +| ROUTINE_TYPE | CHAR(1) | Type of the currently running routine | + +## 3.3 VERIFY\_GROUP\_FOR\_USER function + +The VERIFY\_GROUP\_FOR\_USER function was added in IBM i 7.2. Although it is primarily intended for use with RCAC permissions and masks, it can be used in other SQL statements. The first parameter must be one of these three special registers: SESSION\_USER, USER, or CURRENT\_USER. The second and subsequent parameters are a list of user or group profiles. Each of these values must be 1 - 10 characters in length. These values are not validated for their existence, which means that you can specify the names of user profiles that do not exist without receiving any kind of error. + +If a special register value is in the list of user profiles or it is a member of a group profile included in the list, the function returns a long integer value of 1. Otherwise, it returns a value of 0. It never returns the null value. + +Here is an example of using the VERIFY\_GROUP\_FOR\_USER function: + +1. There are user profiles for MGR, JANE, JUDY, and TONY. +2. The user profile JANE specifies a group profile of MGR. +3. If a user is connected to the server using user profile JANE, all of the following function invocations return a value of 1: + +VERIFY\_GROUP\_FOR\_USER (CURRENT\_USER, 'MGR') VERIFY\_GROUP\_FOR\_USER (CURRENT\_USER, 'JANE', 'MGR') VERIFY\_GROUP\_FOR\_USER (CURRENT\_USER, 'JANE', 'MGR', 'STEVE') + +The following function invocation returns a value of 0: + +The following function invocation returns a value of 0: VERIFY\_GROUP\_FOR\_USER (CURRENT\_USER, 'JUDY', 'TONY') + +VERIFY\_GROUP\_FOR\_USER (CURRENT\_USER, 'JUDY', 'TONY') + +``` +CASE WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'HR', 'EMP') = 1 THEN EMPLOYEES. DATE_OF_BIRTH WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'MGR') = 1 AND SESSION_USER = EMPLOYEES. USER_ID THEN EMPLOYEES. DATE_OF_BIRTH WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'MGR') = 1 AND SESSION_USER <> EMPLOYEES. USER_ID THEN( 9999 || '-' || MONTH( EMPLOYEES. DATE_OF_BIRTH) || '-' || DAY(EMPLOYEES.DATE_OF_BIRTH)) ELSE NULL END ENABLE; +``` + +2. The other column to mask in this example is the TAX\_ID information. In this example, the rules to enforce include the following ones: + +- Human Resources can see the unmasked TAX\_ID of the employees. +- Employees can see only their own unmasked TAX\_ID. +- Managers see a masked version of TAX\_ID with the first five characters replaced with the X character (for example, XXX-XX-1234). +- Any other person sees the entire TAX\_ID as masked, for example, XXX-XX-XXXX. + +To implement this column mask, run the SQL statement that is shown in Example 3-9. + +``` +CREATE MASK HR_SCHEMA.MASK_TAX_ID_ON_EMPLOYEES ON HR_SCHEMA.EMPLOYEES AS EMPLOYEES FOR COLUMN TAX_ID RETURN CASE WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'HR') = 1 THEN EMPLOYEES. TAX_ID WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'MGR') = 1 AND SESSION_USER = EMPLOYEES. USER_ID THEN EMPLOYEES. TAX_ID WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'MGR') = 1 AND SESSION_USER <> EMPLOYEES. USER_ID THEN( 'XXX-XX-' CONCAT QSYS2. SUBSTR( EMPLOYEES. TAX_ID, 8, 4)) WHEN VERIFY_GROUP_FOR_USER( SESSION_USER, 'EMP') = 1 THEN EMPLOYEES. TAX_ID ELSE 'XXX-XX-XXXX' END ENABLE; +``` + +Example 3-9 Creating a mask on the TAX_ID column + +3. Figure 3-10 shows the masks that are created in the HR\_SCHEMA. + +Figure 3-10 Column masks shown in System i Navigator + + + +## 3.6.6 Activating RCAC + +Now that you have created the row permission and the two column masks, RCAC must be activated. The row permission and the two column masks are enabled (last clause in the scripts), but now you must activate RCAC on the table. To do so, complete the following steps: + +1. Run the SQL statements that are shown in Example 3-10. + +Example 3-10 Activating RCAC on the EMPLOYEES table + +``` +/* Active Row Access Control(permissions) */ /* Active Column Access Control(masks) */ ALTER TABLE HR_SCHEMA.EMPLOYEES ACTIVATE ROW ACCESS CONTROL ACTIVATE COLUMN ACCESS CONTROL; +``` + +2. Look at the definition of the EMPLOYEE table, as shown in Figure 3-11. To do this, from the main navigation pane of System i Navigator, click Schemas  HR\_SCHEMA  Tables , right-click the EMPLOYEES table, and click Definition . + +Figure 3-11 Selecting the EMPLOYEES table from System i Navigator + + + +2. Figure 4-68 shows the Visual Explain of the same SQL statement, but with RCAC enabled. It is clear that the implementation of the SQL statement is more complex because the row permission rule becomes part of the WHERE clause. + +Figure 4-68 Visual Explain with RCAC enabled + + + +3. Compare the advised indexes that are provided by the Optimizer without RCAC and with RCAC enabled. Figure 4-69 shows the index advice for the SQL statement without RCAC enabled. The index being advised is for the ORDER BY clause. + +Figure 4-69 Index advice with no RCAC + + + +``` +WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'TELLER') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'CUSTOMER') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'ADMIN') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'TELLER') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'CUSTOMER') = 1 124 Row and Column Access Control Support in IBM DB2 for iTHEN C. CUSTOMER_TAX_ID THEN( 'XXX-XX-' CONCAT QSYS2. SUBSTR( C. CUSTOMER_TAX_ID, 8, 4)) THEN C. CUSTOMER_TAX_ID THEN C. CUSTOMER_DRIVERS_LICENSE_NUMBER THEN C. CUSTOMER_DRIVERS_LICENSE_NUMBER THEN C. CUSTOMER_DRIVERS_LICENSE_NUMBER CREATE MASK BANK_SCHEMA.MASK_DRIVERS_LICENSE_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C CREATE MASK BANK_SCHEMA.MASK_LOGIN_ID_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C ELSE 'XXX-XX-XXXX' END ELSE '*************' END RETURN CASE RETURN CASE ENABLE; FOR COLUMN CUSTOMER_DRIVERS_LICENSE_NUMBER ENABLE; FOR COLUMN CUSTOMER_LOGIN_ID ALTER TABLE BANK_SCHEMA.CUSTOMERS WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'ADMIN') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'CUSTOMER') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'ADMIN') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'CUSTOMER') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'ADMIN') = 1 WHEN QSYS2. VERIFY_GROUP_FOR_USER( SESSION_USER, 'CUSTOMER') = 1 THEN C. CUSTOMER_LOGIN_ID THEN C. CUSTOMER_LOGIN_ID THEN C. CUSTOMER_SECURITY_QUESTION THEN C. CUSTOMER_SECURITY_QUESTION THEN C. CUSTOMER_SECURITY_QUESTION_ANSWER THEN C. CUSTOMER_SECURITY_QUESTION_ANSWER CREATE MASK BANK_SCHEMA.MASK_SECURITY_QUESTION_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C CREATE MASK BANK_SCHEMA.MASK_SECURITY_QUESTION_ANSWER_ON_CUSTOMERS ON BANK_SCHEMA.CUSTOMERS AS C ELSE '*****' END ELSE '*****' END ELSE '*****' END ACTIVATE ROW ACCESS CONTROL ACTIVATE COLUMN ACCESS CONTROL; RETURN CASE RETURN CASE ENABLE; FOR COLUMN CUSTOMER_SECURITY_QUESTION ENABLE; FOR COLUMN CUSTOMER_SECURITY_QUESTION_ANSWER ENABLE; +``` + + + +## Row and Column Access Control Support in IBM DB2 for i + +Implement roles and separation of duties + +This IBM Redpaper publication provides information about the IBM i 7.2 feature of IBM DB2 for i Row and Column Access Control (RCAC). It offers a broad description of the function and advantages of controlling access to data in a comprehensive and transparent way. This publication helps you understand the capabilities of RCAC and provides examples of defining, creating, and implementing the row permissions and column masks in a relational database environment. + +Leverage row permissions on the database + +This paper is intended for database engineers, data-centric application developers, and security officers who want to design and implement RCAC as a part of their data control and governance policy. A solid background in IBM i object level security, DB2 for i relational database concepts, and SQL is assumed. + +Protect columns by defining column masks + + + +INTERNATIONAL TECHNICAL SUPPORT ORGANIZATION + +## BUILDING TECHNICAL INFORMATION BASED ON PRACTICAL EXPERIENCE + +IBM Redbooks are developed by the IBM International Technical Support Organization. Experts from IBM, Customers and Partners from around the world create timely technical information based on realistic scenarios. Specific recommendations are provided to help you implement IT solutions more effectively in your environment. + +For more information: ibm.com /redbooks diff --git a/tests/snapshots/pdf/sources/right_to_left_01.pdf.md b/tests/snapshots/pdf/sources/right_to_left_01.pdf.md new file mode 100644 index 00000000..29aa2785 --- /dev/null +++ b/tests/snapshots/pdf/sources/right_to_left_01.pdf.md @@ -0,0 +1,3 @@ +## تحسين الإنتاجية وحل المشكلات من خلال البرمجة بلغة R و Python + +تعتبر البرمجة بلغة R و Python من الأدوات القوية التي يمكن أن تعزز الإنتاجية وتساعد في إيجاد حلول فعالة للمشكلات. يمتلك كل من R و Python ميزات فريدة تجعلها مثالية لتحليل البيانات، مما يسهل على المحللين والعلماء إجراء تحليلات معقدة بطريقة سريعة وفعالة. إذا كان لديك عقلية تحليلية، فإن استخدام هذه اللغات يمكن أن يسهم بشكل كبير في تحسين نتائج العمل. عندما يجتمع التفكير التحليلي مع مهارات البرمجة، يصبح من الممكن معالجة كميات هائلة من البيانات واستخراج الأنماط والتوجهات منها. يمكن للمبرمجين استخدام R و Python لتنفيذ عمليات تحليلية متقدمة، مثل النمذجة الإحصائية وتحليل البيانات الكبيرة. هذا ليس فقط يوفر الوقت، بل يمكن أن يؤدي أيضًا إلى اتخاذ قرارات أكثر دقة بناءً على استنتاجات قائمة على البيانات. علاوة على ذلك، توفر كل من R و Python مكتبات وأدوات غنية تدعم مجموعة واسعة من التطبيقات، من التحليل البياني إلى التعلم اللآي. يمكن للمستخدمين الاستفادة من هذه المكتبات لتطوير حلول مبتكرة للمشكلات المختلفة. على سبيل المثال، يمكن استخدام مكتبة pandas في Python لإدارة البيانات بكفاءة، بينما توفر R أدوات قوية للرسم البياني والتحليل الإحصائي، مما يجعلها مثالية للباحثين والمحللين. في النهاية، يمكن أن تؤدي البرمجة بلغة R و Python مع عقلية تحليلية إلى تحسين الإنتاجية وتوفير حلول مبتكرة للمشكلات المعقدة. إن القدرة على تحليل البيانات بشكل فعال وتطبيق الأساليب البرمجية المناسبة يمكن أن تكون لها تأثيرات إيجابية بعيدة المدى على الأداء الشخصي والمهني. diff --git a/tests/snapshots/pdf/sources/right_to_left_02.pdf.md b/tests/snapshots/pdf/sources/right_to_left_02.pdf.md new file mode 100644 index 00000000..4eb87f6b --- /dev/null +++ b/tests/snapshots/pdf/sources/right_to_left_02.pdf.md @@ -0,0 +1,9 @@ + + +وعليه، فإن الحكومة المصرية تضع صوو عييهاوخ لوال المر اوة الم باوة تكايف السيد رئيس الجماورية لاخ بخلعمل ياى تح يق يدد من الأهودا ياى رعساخ: وضع ماف بهخء الإنسخن المصري ياى رعس قخئموة الأولويوخت، لخصوة فووا مجوخحت الصووحة واللعاوويل، العمول ياووى تح يوق معوودحت نمووو قويوووة ومسووولدامة و وووخماة فوووا عذاوووف ال لخيوووخت، و ووو ا الح وووخ ياوووى محوددات الأمون ال ووما المصوري فوا ضووء اللحوديخت الإقايميوة والدوليوة، ومواصواة واوود تلووير الماوخر ة السيخسوية، واسولمرار ملخبعوة ما وخت الأمووون واحسووول رار ومكخفحوووة الإرهوووخ ، تلووووير ما وووخت ال خفوووة والوووويا الوووو،ها، والبلوووخ الوووديها المعلووودل ياوووى الهحوووو الووو ي يرسووو م وووخهيل الموا،هة والسام المجلمعا. + +ووف ً خ لمخ سبق، يسولاد برنوخما الحكوموة المصورية لوال ال لور ) - 2024 تح يق عربعة عهدا (2026 اسلراتيجية رئيسة، وها ياى الهحو الآتا: + + + +تجدر الإ خر إلى عنه قد تل تحديد مسولادفخت البرنوخما بخحسولهخد باوكل رئووويس ياوووى مسووولادفخت ر يوووة مصووور ، 2023 وتوصووويخت واسوووخت الحووووار الوو،ها، ومسولادفخت الوو ارات، والبرنوخما الوو،ها ليصوا خت الايكايوة، ومبلاف احسلراتيجيخت الو،هية. diff --git a/tests/snapshots/pdf/sources/right_to_left_03.pdf.md b/tests/snapshots/pdf/sources/right_to_left_03.pdf.md new file mode 100644 index 00000000..f05605ed --- /dev/null +++ b/tests/snapshots/pdf/sources/right_to_left_03.pdf.md @@ -0,0 +1,21 @@ +## اميدنامه پذيرش در بازار اصلی - کالای داخلی + + + + + +## شرکت بورس کالای ايران + +## 5 - -2 استاندارد کالا + +## -3 پذيرش در بورس + +| بورس1403/09/19 | تاريخ ارائه مدارک | +|--------------------------------|-------------------------------------------------------| +| 1 4 0 3/ 1 0 / 0 4 | تاريخ پذيرش | +| 436 | شماره جلسه کميته عرضه | +| 1 4 0 3/ 1 0 / 0 5 | تاريخ درج اميدنامه | +| کارگزاری آرمون بورس | مشاور پذيرش | +| اساس قيمت های جهانی | نحوة تعيين قيمت پايه پس از پذيرش کالا در بورسبر | +| از توليد ساليانه يا 47.50 0 تن | حداقل درصد عرضه از توليد/ کل فروش/ فروش داخلیحداقل%50 | +| 5% آخرين محموله قابل تحويل | خطای مجاز تحويل | diff --git a/tests/snapshots/pdf/sources/skipped_1page.pdf.md b/tests/snapshots/pdf/sources/skipped_1page.pdf.md new file mode 100644 index 00000000..dc68fbc3 --- /dev/null +++ b/tests/snapshots/pdf/sources/skipped_1page.pdf.md @@ -0,0 +1,50 @@ +- 보안분 + +## [그림 4-5] 8대 미래 유망 보안기술 도출 + + + + + + + + + +엣지컴퓨팅 (Edge Computing) + + + +차세대 AI (Next AI) + + + + + + + + + + + +차세대 AI (Next AI) + + + + + + + +데이터 + + + +웨어러블 컨트롤 인터페이스 + +(Wearable Control Interfaces) + +(Hyper-Connected Networking) + +84 ICT 기술변화에 따른 미래 보안기술 전망 보고서 + +- AI 기술을 활용해 오탐율을 줄이고, 빠른 분석 탐지를 넘어 자동적인 격리까지 제공하는 방향으로 진화 +- 각종 사이버위협에 대한 하나의 기법 또는 알고리즘이 아닌, 침해 대응의 각 요소별로 최적화된 알고리즘과 기법, 이전에 설명한 학습 방법을 지원하고 이를 통합할 수 있는 기술 필요 diff --git a/tests/snapshots/pdf/sources/skipped_2pages.pdf.md b/tests/snapshots/pdf/sources/skipped_2pages.pdf.md new file mode 100644 index 00000000..2bb335c0 --- /dev/null +++ b/tests/snapshots/pdf/sources/skipped_2pages.pdf.md @@ -0,0 +1,56 @@ +- 보안분 + + + +## [그림 4-3] 미래 보안기술 도출 과정 + + + +## [그림 4-5] 8대 미래 유망 보안기술 도출 + + + + + + + + + +엣지컴퓨팅 (Edge Computing) + + + +차세대 AI (Next AI) + + + + + + + + + + + +차세대 AI (Next AI) + + + + + + + +데이터 + + + +웨어러블 컨트롤 인터페이스 + +(Wearable Control Interfaces) + +(Hyper-Connected Networking) + +84 ICT 기술변화에 따른 미래 보안기술 전망 보고서 + +- AI 기술을 활용해 오탐율을 줄이고, 빠른 분석 탐지를 넘어 자동적인 격리까지 제공하는 방향으로 진화 +- 각종 사이버위협에 대한 하나의 기법 또는 알고리즘이 아닌, 침해 대응의 각 요소별로 최적화된 알고리즘과 기법, 이전에 설명한 학습 방법을 지원하고 이를 통합할 수 있는 기술 필요 diff --git a/tests/snapshots/pdf/sources/table_mislabeled_as_picture.pdf.md b/tests/snapshots/pdf/sources/table_mislabeled_as_picture.pdf.md new file mode 100644 index 00000000..ab83293a --- /dev/null +++ b/tests/snapshots/pdf/sources/table_mislabeled_as_picture.pdf.md @@ -0,0 +1,84 @@ +| | 209„ They work in parallel to State funded private practitioners who take assignments to represent people eligible for legal aid | +|----|------------------------------------------------------------------------------------------------------------------------------------| +| | They coordinate appointments of private practitioners (ex officio, or panel appoint ments) to legal aid cases | +| | They supervise, coach or mentor private practitioners who take legal aid cases | +| | They conduct or organize training sessions for staff lawyers/paralegals | +| | They conduct or organize training sessions for all providers of legal aid, including both staff and private lawyers/paralegals | +| | Other (Please specify) | +| | Not applicable, there is no institutional legal aid provider | + +- „ They work in parallel to State funded private practitioners who take assignments to represent people eligible for legal aid +- „ They coordinate appointments of private practitioners (ex officio, or panel appointments) to legal aid cases +- „ They supervise, coach or mentor private practitioners who take legal aid cases +- „ They conduct or organize training sessions for staff lawyers/paralegals +- „ They conduct or organize training sessions for all providers of legal aid, including both staff and private lawyers/paralegals +- „ Other (Please specify) \_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_ +- „ Not applicable, there is no institutional legal aid provider + +23. If your country has an institutional legal aid provider (e.g. public defender), what is the maximum caseload per lawyer at one time? + +| 23. | 209„ If your country has an institutional legal aid provider (e.g. public defender), what is the maximum caseload per lawyer at one time? _______ at the national (federal) level | +|-------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| + +- \_\_\_\_\_\_\_ at the national (federal) level +- \_\_\_\_\_\_\_ at the regional (district) level +- \_\_\_\_\_\_\_ at the local (municipal) level +- „ There is no such limitation + +24. If your country has an institutional legal aid provider (e.g. public defender), do the staff lawyers coordinate to uniformly challenge common violations of national and international due process rights and human rights? + +- „ Yes, at the national (federal) level +- „ Yes, at regional (district) level +- „ Yes, at the local (municipal) level +- „ No + +| 25. | 209„ If your country has an institutional legal aid provider (e.g. public defender), does it have specialized providers and/or units for representing child victims, child witness es or suspected and accused children? | +|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| | Yes, at the national (federal) level | +| „ | Yes, at regional (district) level | +| „ | Yes, at the local (municipal) level | +| „ | No | + +25. If your country has an institutional legal aid provider (e.g. public defender), does it have specialized providers and/or units for representing child victims, child witnesses or suspected and accused children? + +- „ Yes, at the national (federal) level +- Yes, at regional (district) level +- „ Yes, at the local (municipal) level + +26. If your country allows legal aid services through university-based student law clinics, are there national guidelines on how students are supervised in providing legal aid services? (Please select all that apply) + +- „ Yes, there are specific guidelines for non-lawyers providing legal aid services +- „ Yes, there are specific guidelines on faculty/student ratios +- „ No, it is up to the discretion of each university +- „ Don't know +- „ There are no university-based student law clinics + +| 27. | 209„ If your country allows legal aid services through university-based student law clinics, what type of legal aid services is a student authorized to undertake? (Please select all that apply) | +|-------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| „ | There is no limitation; they have the same authority as lawyers | +| „ | They can represent people in administrative or civil law hearings | +| „ | They can provide primary legal aid (legal advice) | +| „ | They can prepare legal documents | +| „ | They can represent people in court in civil and criminal matters | +| „ | They have the same authority as lawyers in criminal cases of low to mid gravity | +| „ | They can provide a full range of legal services in criminal cases regardless of gravity | +| „ | They can conduct mediation | +| „ | They are authorized to provide only those services that a faculty member or practic ing lawyer supervises | +| „ | Don’t know | +| „ | Other (Please specify) _____________________________________________________ | + +27. If your country allows legal aid services through university-based student law clinics, what type of legal aid services is a student authorized to undertake? (Please select all that apply) + +- specialized legal aid services 28. Are provided focusing on specific disadvantaged population groups? If yes, please indicate to whom these services are provided, and whether they are provided by State-funded legal aid, civil society organizations, or both. + +(Please select all that apply) + +| | 209„ | State funded legal aid | CSOs | +|----|------------------------------------------------|--------------------------|--------| +| y | Persons with disabilities | * | * | +| y | Children | * | * | +| y | Women | * | * | +| y | The elderly | * | * | +| y | Migrants | * | * | +| y | Refugees, asylum seekers, or stateless persons | * | * | +| y | Internally displaced persons | * | * | diff --git a/tests/pdf_snapshots/pdf_password/sources/2206.01062_pg3.pdf.md b/tests/snapshots/pdf_password/sources/2206.01062_pg3.pdf.md similarity index 100% rename from tests/pdf_snapshots/pdf_password/sources/2206.01062_pg3.pdf.md rename to tests/snapshots/pdf_password/sources/2206.01062_pg3.pdf.md diff --git a/tests/snapshots/scanned/sources/nemotron_multipage.pdf.md b/tests/snapshots/scanned/sources/nemotron_multipage.pdf.md new file mode 100644 index 00000000..4ccde8ad --- /dev/null +++ b/tests/snapshots/scanned/sources/nemotron_multipage.pdf.md @@ -0,0 +1,3 @@ +Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package aerosaeoe e o a + +H W ep 9 ps 1s e. uu P1 po te od nn na sm 88 ek da sd bd p0 M e 00 a K C a p diff --git a/tests/pdf_snapshots/scanned/sources/ocr_test.pdf.md b/tests/snapshots/scanned/sources/ocr_test.pdf.md similarity index 100% rename from tests/pdf_snapshots/scanned/sources/ocr_test.pdf.md rename to tests/snapshots/scanned/sources/ocr_test.pdf.md diff --git a/tests/snapshots/scanned/sources/ocr_test_rotated_180.pdf.md b/tests/snapshots/scanned/sources/ocr_test_rotated_180.pdf.md new file mode 100644 index 00000000..b7787b6c --- /dev/null +++ b/tests/snapshots/scanned/sources/ocr_test_rotated_180.pdf.md @@ -0,0 +1 @@ +aerosaeoe e o a diff --git a/tests/snapshots/scanned/sources/ocr_test_rotated_270.pdf.md b/tests/snapshots/scanned/sources/ocr_test_rotated_270.pdf.md new file mode 100644 index 00000000..4d299e55 --- /dev/null +++ b/tests/snapshots/scanned/sources/ocr_test_rotated_270.pdf.md @@ -0,0 +1 @@ +H W ep 9 ps 1s e. uu P1 po diff --git a/tests/snapshots/scanned/sources/ocr_test_rotated_90.pdf.md b/tests/snapshots/scanned/sources/ocr_test_rotated_90.pdf.md new file mode 100644 index 00000000..a8bf7add --- /dev/null +++ b/tests/snapshots/scanned/sources/ocr_test_rotated_90.pdf.md @@ -0,0 +1 @@ +te od nn na sm 88 ek da sd bd p0 M e 00 a K C a p diff --git a/tests/snapshots/scanned/sources/old_newspaper.png.md b/tests/snapshots/scanned/sources/old_newspaper.png.md new file mode 100644 index 00000000..bb3003db --- /dev/null +++ b/tests/snapshots/scanned/sources/old_newspaper.png.md @@ -0,0 +1,117 @@ +## French Institute Creates A French Community At OU + +ology.A demonstration class of first year students of French at the high school and junior high schoollevel is to be conducted by Pierre Simonian, the Institute's teacher in charge of demonstrationandmethodology. + +strengthen the teacher's knowledge and control of the langlage, + +AnNDEAFrench Institute opened its doors on OU's campuslastweekwith the arrival of its 48participants,eightexperienced professors of French, and four graduate assistants'and natives of France. + +Lastweek marked the beginning of an intensive program in the French language,methods of teaching the language,and the culture of France.Faculty and Institute participants meet together instudysessionsallmorning and afternoon,Classes are conducted entirely in French, with the exception of courses in language analysis and method- + +The participants eatlunchand dinner together and speak,it is expected,nothing but French. After dinner,participants share extracurricular activitiestogether--films,music,lectures.Often the arranged program of activi- + +Theparticipants in the Institute(14menand34women,10 of them nuns)are teachers of French in junior and senior high schoolsinMichiganand14other states.Director of the Institute Is Ou's assistant professor of French,Don Iodice.Also from OU's staff are Mme Genevieve Prevost, assistant director of the Institute,-and M. Charles Forton,in charge of language Improvement. Familiar to OU's campus as well are M. et Mme Francis Tafoya,who will be workingwithcontemporary French-civilization andlanguage improvementrespectively.M. Tafoya was formerly the head of OU's department of foreign languages. + + + +## MITZELFELD'S + +ROCHESTER + +The object of the Institute is twofold.The iirst objective is to bring the teachers up to date In theirsubject area,Because of rapid changes in content,approach,.and teaching techniques, trueofsuchfieldsasmathematics andscience as well asforeign languages,the National Defense EducationAct has established summer institutes all over the country to help teachers keep pace with advances within their own fields.The second goal of theFrench institute will be to + + + +## HILLS THEATRE + +Rochester + +Friday -Tuesday ONE SHOWING NIGHTLY 7:30 SUNDAY2:30&7:30 Programlnformation651-8311 + +## FIRSTTIME AT POPULARPRICES + + + + + +IR LaDY + +Daiey + +OF ROCHESTER 743N.MAIN + + + +Try our + +FIESTAS + +Winner of 8Academy Awards + +## AUDREY HEPBURN·REXHARRISONSTANLEYHOLLOWAY + +SPLITS + +Hours Hours 11A.M.to11P.M 11A.M.to11P.M + +Hours Hours + +TECHNICOLOR SUPER PANAVISION 7OFROMWARNER BRO + +11A.M.to11P.M 11A.M.to11P.M + +GETDUNLOPIMPORTQUALITY INTHEAMERICAN MADE GOLD SEAL FULL 4PLY (NOT2PLY)CONSTRUCTION NO THUMP WITHTYREX CORD NYLONALSOAVAILABLE) Certified Safe At A SUSTAINED 100 M.P.H. Wholesale Prices to O.U.Students & Faculty on Passenger Car, Sports Car, Radial Ply & Racing Tires + +BruceRobertson + +Tom Hill + +Bill Basinger + +## R.B. DUNLOP TIRE SALES + +Phone:651-3422 or 673-9227after5p.m.call 334-6452 + +## Arnold Rexall Pharmacy + +ties cohtinuesuntil sevenoreight in the evening.When they return tothe dormitory(allparticipants are housed in AnibalHousethis summer),they areencouragedto continue speaking nothingbut French.They are bound together in a linguistic and cultural island, andtheirveryisolationwithinthe French language and their tightnessasa community is meant to Increase theirfacility with the language + +Prescriptions Cosmetics SundryItems Liquor,Beer,Wine + +2026OpdykeRd. Corner of Pontiac Road 333-7033 + +## CLASSIFIED ADS + +Wanted:Man or womanfullor part time.Direct Sales Prestige Products.Call Mrs.Lodge,682- 5540or335-9937forappt + +## TUKO + +872E.Auburn,NearJohnR.Rochester UL2-5363 + + + +Treat* the* eptire family +$ to the happiest entertaipment ofall! + + + +## HAV FULL HOUSE? + +Then use our storage service for all your clothes. It includes complete protection for all your garments, including your furs. Everything is thoroughly cleaned and mothproofed before storing. + +## P.S.FREE... + + + +s the wider your choice.Bring your Springcleaning in nov + + + + + +## M.G.M. Cleaners, Inc. + +In Business for 2l Years Auburn Rd..at Adams Crooks Rd..at Auburn Mound Rd..at 23 Mile Rd. Also on Campus at Oakland Unirersity B Plants and Stores Serving Oakland and Macomb Counties + +DUNLOP + +OpenytoMMu My huSat diff --git a/tests/snapshots/scanned/sources/qr_bill_example.jpg.md b/tests/snapshots/scanned/sources/qr_bill_example.jpg.md new file mode 100644 index 00000000..9c4377b5 --- /dev/null +++ b/tests/snapshots/scanned/sources/qr_bill_example.jpg.md @@ -0,0 +1,59 @@ +## Fictitiousexampleforillustrationpurposes + +Ms PiaRutschmann Marktgasse28 9400Rorschach + +DearMs.Rutschmann, + +Wearebillingyouasfollowsforcompletionoftheassignedactivities + +## Billno.3139 + +RobertSchneiderAG RueduLac1268 2501Bie + +059/9876540 + +E-Mail robert@rschneider.ch www.rschneider.ch + +Internet: + +Date + +01.07.2020 + +| | | | | | +|----|----|----|----|----| +| | | | | | +| | | | | | +| | | | | | +| | | | | | +| | | | | | +| | | | | | +| | | | | | + +Thankyoufortheassignment.Pleasepaythebillamountwithin3Odays + +Yourssincerely + +RobertSchneider + +## Receipt + +Paymentpart + +Account/Payableto CH5800791123000889012 RobertSchneiderAG RueduLac1268 2501Bie + + + +Payableby PiaRutschmann Marktgasse28 9400Rorschach + +Amount + +3.949.75 + +Acceptancepoint + +Account/Payableto CH5800791123000889012 RobertSchneiderAG RueduLac1268 2501Bie + +Additionalinformation BillNo.3139forgardenworkanddisposalof cuttings + +Payableby PiaRutschmann Marktgasse28 9400Rorschach diff --git a/tests/snapshots/scanned/sources/sample_with_rotation_mismatch.pdf.md b/tests/snapshots/scanned/sources/sample_with_rotation_mismatch.pdf.md new file mode 100644 index 00000000..256d8c6a --- /dev/null +++ b/tests/snapshots/scanned/sources/sample_with_rotation_mismatch.pdf.md @@ -0,0 +1,33 @@ + + +## THE SLEREXE COMPANY LIMITED + +SAPORSLANE-BOOLE.DORSET-BH258ER SAPORSLANE-BOOLE.DORSET-BH258ER + +SAPORSLANE-BOOLE.DORSET-BH258ER SAPORSLANE-BOOLE.DORSET-BH258ER TELEPHONEB0OLB(94513)51617-TELEX123456 TELEPHONEB0OLE(94513)51617-TELEX123456 + +TELEPHONEB0OLB(94513)51617-TELEX123456 TELEPHONEB0OLE(94513)51617-TELEX123456 + +18th January,1972. + +OurRef.35O/PJC/EAC + + + +Dr.P.N.Cundall, Mining Surveys Ltd., Holroyd Road, Reading, Berks. + +Dear Pete, + +Permit me to introduce you to the faciiity of facsimile transmlsson. + +In facsimile aphotocell is caused toperform a raster scanover the subject copy. The variations of print density on the document cause the photocell to generate an analogous electrical video signal. This signal is used to modulate a carrier, which is transmitted to a remote destinationover aradioorcablecommunicationslink. + +At the remote terminal, demodulation reconstructsthe video signal, which is used to modulate the density of print produced by a printing device. This device is scanning in a raster scan synchronised with that at the transmitting terminal. As a result, a facsimile copy of the subject document is produced. + +Probably you have uses for this facility in your organisation. + +Yours sincerely, + +P.J.CROSS Group Leader - Facsimile Research + + diff --git a/tests/snapshots/tiff/sources/2206.01062.tif.md b/tests/snapshots/tiff/sources/2206.01062.tif.md new file mode 100644 index 00000000..5eac0bf8 --- /dev/null +++ b/tests/snapshots/tiff/sources/2206.01062.tif.md @@ -0,0 +1,47 @@ +## DocLayNet:ALarge Human-Annotated Datasetfor Document-LayoutAnalysis + +Birgit Pfitzmann BMResearch RueschllkonSwitzerland bpf@zurich.ibm.com + +AhmedS.Nassar IBMResearch Rueschlikon, Switzerland ahn@zurich.ibm.com + +## ABSTRACT + +Accurate document layout analysis is a key requirement for highquality PDF document conversion. With the recent availability od public, large ground-truth datasets such as PubLayNet and DocBank deep-learning models have proven to be very effective at layouf detection and segmentation. While these datasets are of adequate size to train such models, they severely lack in layout variability since they are sourced from scientific article repositories such as PubMed and arXiv only. Consequently, the accuracy of the layout segmentation drops significantly when these models are applied on more challenging and diverse layouts. In this paper, we present DocLayNet, a new, publicly available, document-layout annotation dataset in COco format. It contains Soss3 manually annotated pages from diverse data sources to represent a wide variability in layouts. For each PDF page, the layout annotations provide labelled bounding-boxes with a choice of 11 distinct classes. DocLayNef also provides a subset of double- and triple-annotated pages to determine the inter-annotator agreement. In multiple experiments, we provide baseline accuracy scores (in mAP) for a set of popular object detection models. We also demonstrate that these models fall approximately 10% behind the inter-annotator agreement. Furthermore, we provide evidence that DocLayNet is of sufficient size Lastly, we compare models trained on PubLayNet, DocBank and DocLayNet, showing that layout predictions of the DocLayNettrained models are more robust and thus the preferred choice for general-purpose document-layout analysis + +## CCS CONCEPTS + +-Informationsystems→Documentstructure;Appliedcomputing → Document analysis, - Computing methodologies → Machine learning Computer vision; Object detection + +Peemissiom to make digital or hard copies of part er all of this woek foe personal or classuoom use Is granted without fee prowided that copies are not made or distrnutee tor protit oe commercial advantage and that oopies bear this notice and the tull citation on the tirst page. Copyrights foe thind-party oemponents of this work mist be honored Foraocherusescomtacttheowre/authors + +KDD 22 Aueaat 24, 2022, Washimgton, DC USA + +2122 Copyrirht held by the auner/autheefs) + +7@01.8r/10.1145/35346783539043 + +Michele Dolfi IBMResearch Rueschlikon, Switzerland dol@zurich.ibm.com + +Christoph Auer BMResearch Rueschlikon, Switzerland cau@zurich.ibmcom + +PeterStaar IBMResearch Rueschlikon,Switzerland taa@zurich.ibm.com + + + +Figure 1: Four examples of complex page layouts across dif ferent document categories + + + + + + + + + +## KEYWORDS + +PDF document conversion, layout segmentation, object-detection, data set, Machine Learning + +## ACMRefereneeFormat: + +Birgit Pfitzmann, Christoph Auer, Michele Dolfi, Ahmed S. Nassar, and Peter Staar. 2022. DocLayNet: A Large Human-Annotated Dataset for Documen Layout Analysis. In Proceedings of the 28th ACAd SIGKDD Conference on Ksowledge Discovery &td Date Adining (KDD 'z2), Augast J41&, 2022, wasi ingtow, DC, U/SA. ACM, New York, NY, USA, 9 pages. https://doi.org/10.1145/ 353467.3539043 diff --git a/tests/pdf_snapshots/webp/sources/webp-test.webp.md b/tests/snapshots/webp/sources/webp-test.webp.md similarity index 100% rename from tests/pdf_snapshots/webp/sources/webp-test.webp.md rename to tests/snapshots/webp/sources/webp-test.webp.md