mirror of
https://github.com/DS4SD/docling.git
synced 2025-07-27 04:24:45 +00:00
Merge remote-tracking branch 'origin/main' into support-webp-filetype
This commit is contained in:
commit
482483e74a
49
CHANGELOG.md
49
CHANGELOG.md
@ -1,3 +1,52 @@
|
|||||||
|
## [v2.31.2](https://github.com/docling-project/docling/releases/tag/v2.31.2) - 2025-05-13
|
||||||
|
|
||||||
|
### Fix
|
||||||
|
|
||||||
|
* AsciiDoc header identification (#1562) ([#1563](https://github.com/docling-project/docling/issues/1563)) ([`4046d0b`](https://github.com/docling-project/docling/commit/4046d0b2f38254679de5fc78aaf2fe630d6bb61c))
|
||||||
|
* Restrict click version and update lock file ([#1582](https://github.com/docling-project/docling/issues/1582)) ([`8baa85a`](https://github.com/docling-project/docling/commit/8baa85a49d3a456d198c52aac8e0b4ac70c92e72))
|
||||||
|
|
||||||
|
## [v2.31.1](https://github.com/docling-project/docling/releases/tag/v2.31.1) - 2025-05-12
|
||||||
|
|
||||||
|
### Fix
|
||||||
|
|
||||||
|
* Add smoldocling in download utils ([#1577](https://github.com/docling-project/docling/issues/1577)) ([`127e386`](https://github.com/docling-project/docling/commit/127e38646fd7f23fcda0e392e756fe27f123bd78))
|
||||||
|
* **HTML:** Handle row spans in header rows ([#1536](https://github.com/docling-project/docling/issues/1536)) ([`776e7ec`](https://github.com/docling-project/docling/commit/776e7ecf9ac93d62c66b03f33e5c8560e81b6fb3))
|
||||||
|
* Mime error in document streams ([#1523](https://github.com/docling-project/docling/issues/1523)) ([`f1658ed`](https://github.com/docling-project/docling/commit/f1658edbad5c7205bb457322d2c89f7f4d8a4659))
|
||||||
|
* Usage of hashlib for FIPS ([#1512](https://github.com/docling-project/docling/issues/1512)) ([`7c70573`](https://github.com/docling-project/docling/commit/7c705739f9db1cfc6c0a502fd5ba8b2093376d7f))
|
||||||
|
* Guard against attribute errors in TesseractOcrModel __del__ ([#1494](https://github.com/docling-project/docling/issues/1494)) ([`4ab7e9d`](https://github.com/docling-project/docling/commit/4ab7e9ddfb9d8fd0abc483efb70e701447a602c5))
|
||||||
|
* Enable cuda_use_flash_attention2 for PictureDescriptionVlmModel ([#1496](https://github.com/docling-project/docling/issues/1496)) ([`cc45396`](https://github.com/docling-project/docling/commit/cc453961a9196c79f6428305b9007402e448f300))
|
||||||
|
* Updated the time-recorder label for reading order ([#1490](https://github.com/docling-project/docling/issues/1490)) ([`976e92e`](https://github.com/docling-project/docling/commit/976e92e289a414b6b70c3e3ca37a60c85fa12535))
|
||||||
|
* Incorrect scaling of TableModel bboxes when do_cell_matching is False ([#1459](https://github.com/docling-project/docling/issues/1459)) ([`94d66a0`](https://github.com/docling-project/docling/commit/94d66a076559c4e48017bd619508cfeef104079b))
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
* Update links in data_prep_kit ([#1559](https://github.com/docling-project/docling/issues/1559)) ([`844babb`](https://github.com/docling-project/docling/commit/844babb39034b39d9c4edcc3f145684991cda174))
|
||||||
|
* Add serialization docs, update chunking docs ([#1556](https://github.com/docling-project/docling/issues/1556)) ([`3220a59`](https://github.com/docling-project/docling/commit/3220a592e720174940a3b958555f90352d7320d8))
|
||||||
|
* Update supported formats guide ([#1463](https://github.com/docling-project/docling/issues/1463)) ([`3afbe6c`](https://github.com/docling-project/docling/commit/3afbe6c9695d52cf6ed8b48b2f403df7d53342e5))
|
||||||
|
|
||||||
|
## [v2.31.0](https://github.com/docling-project/docling/releases/tag/v2.31.0) - 2025-04-25
|
||||||
|
|
||||||
|
### Feature
|
||||||
|
|
||||||
|
* Add tutorial using Milvus and Docling for RAG pipeline ([#1449](https://github.com/docling-project/docling/issues/1449)) ([`a2fbbba`](https://github.com/docling-project/docling/commit/a2fbbba9f7f889a1f84f8642cf5c75feb57e8668))
|
||||||
|
|
||||||
|
### Fix
|
||||||
|
|
||||||
|
* **html:** Handle address, details, and summary tags ([#1436](https://github.com/docling-project/docling/issues/1436)) ([`ed20124`](https://github.com/docling-project/docling/commit/ed20124544a1b10f068b11bbdf12e1bfc7567195))
|
||||||
|
* Treat overflowing -v flags as DEBUG ([#1419](https://github.com/docling-project/docling/issues/1419)) ([`8012a3e`](https://github.com/docling-project/docling/commit/8012a3e4d6b9ce4cae28210d525d87175da2f5c2))
|
||||||
|
* **codecov:** Fix codecov argument and yaml file ([#1399](https://github.com/docling-project/docling/issues/1399)) ([`fa7fc9e`](https://github.com/docling-project/docling/commit/fa7fc9e63d45f44af57dd6ad7636a2a16f04b8c4))
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
* Fix wrong output format in example code ([#1427](https://github.com/docling-project/docling/issues/1427)) ([`c2470ed`](https://github.com/docling-project/docling/commit/c2470ed216eaf3aae0ad16306de19682fa55b99b))
|
||||||
|
* Add OpenSSF Best Practices badge ([#1430](https://github.com/docling-project/docling/issues/1430)) ([`64918a8`](https://github.com/docling-project/docling/commit/64918a81ac315ea0108f1411a1537dd12117e49c))
|
||||||
|
* Typo fixes in docling_document.md ([#1400](https://github.com/docling-project/docling/issues/1400)) ([`995b3b0`](https://github.com/docling-project/docling/commit/995b3b0ab1c4e566eaba2ea31af3db21eb12a7ae))
|
||||||
|
* Updated the [Usage] link in architecture.md ([#1416](https://github.com/docling-project/docling/issues/1416)) ([`88948b0`](https://github.com/docling-project/docling/commit/88948b0bbaba2ecbaa71f703d2cc94055a3e6b3e))
|
||||||
|
* **ocr:** Add docs entry for OnnxTR OCR plugin ([#1382](https://github.com/docling-project/docling/issues/1382)) ([`a7dd59c`](https://github.com/docling-project/docling/commit/a7dd59c5cb3e7f1eba76c7e2e20be79d8fa5b367))
|
||||||
|
* **security:** More statements about secure development ([#1381](https://github.com/docling-project/docling/issues/1381)) ([`293c28c`](https://github.com/docling-project/docling/commit/293c28ca7c4a44dcd56595ed2fe0372fe1b531b2))
|
||||||
|
* Add testing in the docs ([#1379](https://github.com/docling-project/docling/issues/1379)) ([`01fbfd5`](https://github.com/docling-project/docling/commit/01fbfd565204258acb2986dcaefad3a328626c66))
|
||||||
|
* Add Notes for Installing in Intel macOS ([#1377](https://github.com/docling-project/docling/issues/1377)) ([`a026b4e`](https://github.com/docling-project/docling/commit/a026b4e84bcc8e11ceaa6d9a46c7c741000aff44))
|
||||||
|
|
||||||
## [v2.30.0](https://github.com/docling-project/docling/releases/tag/v2.30.0) - 2025-04-14
|
## [v2.30.0](https://github.com/docling-project/docling/releases/tag/v2.30.0) - 2025-04-14
|
||||||
|
|
||||||
### Feature
|
### Feature
|
||||||
|
@ -22,6 +22,7 @@
|
|||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://pepy.tech/projects/docling)
|
[](https://pepy.tech/projects/docling)
|
||||||
[](https://apify.com/vancura/docling)
|
[](https://apify.com/vancura/docling)
|
||||||
|
[](https://www.bestpractices.dev/projects/10101)
|
||||||
[](https://lfaidata.foundation/projects/)
|
[](https://lfaidata.foundation/projects/)
|
||||||
|
|
||||||
Docling simplifies document processing, parsing diverse formats — including advanced PDF understanding — and providing seamless integrations with the gen AI ecosystem.
|
Docling simplifies document processing, parsing diverse formats — including advanced PDF understanding — and providing seamless integrations with the gen AI ecosystem.
|
||||||
|
@ -287,7 +287,7 @@ class AsciiDocBackend(DeclarativeDocumentBackend):
|
|||||||
|
|
||||||
# ========= Section headers
|
# ========= Section headers
|
||||||
def _is_section_header(self, line):
|
def _is_section_header(self, line):
|
||||||
return re.match(r"^==+", line)
|
return re.match(r"^==+\s+", line)
|
||||||
|
|
||||||
def _parse_section_header(self, line):
|
def _parse_section_header(self, line):
|
||||||
match = re.match(r"^(=+)\s+(.*)", line)
|
match = re.match(r"^(=+)\s+(.*)", line)
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
import logging
|
import logging
|
||||||
|
import traceback
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Final, Optional, Union, cast
|
from typing import Final, Optional, Union, cast
|
||||||
@ -26,6 +27,8 @@ _log = logging.getLogger(__name__)
|
|||||||
|
|
||||||
# tags that generate NodeItem elements
|
# tags that generate NodeItem elements
|
||||||
TAGS_FOR_NODE_ITEMS: Final = [
|
TAGS_FOR_NODE_ITEMS: Final = [
|
||||||
|
"address",
|
||||||
|
"details",
|
||||||
"h1",
|
"h1",
|
||||||
"h2",
|
"h2",
|
||||||
"h3",
|
"h3",
|
||||||
@ -38,6 +41,7 @@ TAGS_FOR_NODE_ITEMS: Final = [
|
|||||||
"ul",
|
"ul",
|
||||||
"ol",
|
"ol",
|
||||||
"li",
|
"li",
|
||||||
|
"summary",
|
||||||
"table",
|
"table",
|
||||||
"figure",
|
"figure",
|
||||||
"img",
|
"img",
|
||||||
@ -134,7 +138,7 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
self.analyze_tag(cast(Tag, element), doc)
|
self.analyze_tag(cast(Tag, element), doc)
|
||||||
except Exception as exc_child:
|
except Exception as exc_child:
|
||||||
_log.error(
|
_log.error(
|
||||||
f"Error processing child from tag {tag.name}: {exc_child!r}"
|
f"Error processing child from tag {tag.name}:\n{traceback.format_exc()}"
|
||||||
)
|
)
|
||||||
raise exc_child
|
raise exc_child
|
||||||
elif isinstance(element, NavigableString) and not isinstance(
|
elif isinstance(element, NavigableString) and not isinstance(
|
||||||
@ -163,7 +167,7 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
def analyze_tag(self, tag: Tag, doc: DoclingDocument) -> None:
|
def analyze_tag(self, tag: Tag, doc: DoclingDocument) -> None:
|
||||||
if tag.name in ["h1", "h2", "h3", "h4", "h5", "h6"]:
|
if tag.name in ["h1", "h2", "h3", "h4", "h5", "h6"]:
|
||||||
self.handle_header(tag, doc)
|
self.handle_header(tag, doc)
|
||||||
elif tag.name in ["p"]:
|
elif tag.name in ["p", "address", "summary"]:
|
||||||
self.handle_paragraph(tag, doc)
|
self.handle_paragraph(tag, doc)
|
||||||
elif tag.name in ["pre", "code"]:
|
elif tag.name in ["pre", "code"]:
|
||||||
self.handle_code(tag, doc)
|
self.handle_code(tag, doc)
|
||||||
@ -177,6 +181,8 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
self.handle_figure(tag, doc)
|
self.handle_figure(tag, doc)
|
||||||
elif tag.name == "img":
|
elif tag.name == "img":
|
||||||
self.handle_image(tag, doc)
|
self.handle_image(tag, doc)
|
||||||
|
elif tag.name == "details":
|
||||||
|
self.handle_details(tag, doc)
|
||||||
else:
|
else:
|
||||||
self.walk(tag, doc)
|
self.walk(tag, doc)
|
||||||
|
|
||||||
@ -201,6 +207,21 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
|
|
||||||
return ["".join(result) + " "]
|
return ["".join(result) + " "]
|
||||||
|
|
||||||
|
def handle_details(self, element: Tag, doc: DoclingDocument) -> None:
|
||||||
|
"""Handle details tag (details) and its content."""
|
||||||
|
|
||||||
|
self.parents[self.level + 1] = doc.add_group(
|
||||||
|
name="details",
|
||||||
|
label=GroupLabel.SECTION,
|
||||||
|
parent=self.parents[self.level],
|
||||||
|
content_layer=self.content_layer,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.level += 1
|
||||||
|
self.walk(element, doc)
|
||||||
|
self.parents[self.level + 1] = None
|
||||||
|
self.level -= 1
|
||||||
|
|
||||||
def handle_header(self, element: Tag, doc: DoclingDocument) -> None:
|
def handle_header(self, element: Tag, doc: DoclingDocument) -> None:
|
||||||
"""Handles header tags (h1, h2, etc.)."""
|
"""Handles header tags (h1, h2, etc.)."""
|
||||||
hlevel = int(element.name.replace("h", ""))
|
hlevel = int(element.name.replace("h", ""))
|
||||||
@ -258,7 +279,7 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def handle_paragraph(self, element: Tag, doc: DoclingDocument) -> None:
|
def handle_paragraph(self, element: Tag, doc: DoclingDocument) -> None:
|
||||||
"""Handles paragraph tags (p)."""
|
"""Handles paragraph tags (p) or equivalent ones."""
|
||||||
if element.text is None:
|
if element.text is None:
|
||||||
return
|
return
|
||||||
text = element.text.strip()
|
text = element.text.strip()
|
||||||
@ -370,46 +391,64 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
_log.debug(f"list-item has no text: {element}")
|
_log.debug(f"list-item has no text: {element}")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def parse_table_data(element: Tag) -> Optional[TableData]:
|
def parse_table_data(element: Tag) -> Optional[TableData]: # noqa: C901
|
||||||
nested_tables = element.find("table")
|
nested_tables = element.find("table")
|
||||||
if nested_tables is not None:
|
if nested_tables is not None:
|
||||||
_log.debug("Skipping nested table.")
|
_log.debug("Skipping nested table.")
|
||||||
return None
|
return None
|
||||||
|
|
||||||
# Count the number of rows (number of <tr> elements)
|
# Find the number of rows and columns (taking into account spans)
|
||||||
num_rows = len(element("tr"))
|
num_rows = 0
|
||||||
|
|
||||||
# Find the number of columns (taking into account colspan)
|
|
||||||
num_cols = 0
|
num_cols = 0
|
||||||
for row in element("tr"):
|
for row in element("tr"):
|
||||||
col_count = 0
|
col_count = 0
|
||||||
|
is_row_header = True
|
||||||
if not isinstance(row, Tag):
|
if not isinstance(row, Tag):
|
||||||
continue
|
continue
|
||||||
for cell in row(["td", "th"]):
|
for cell in row(["td", "th"]):
|
||||||
if not isinstance(row, Tag):
|
if not isinstance(row, Tag):
|
||||||
continue
|
continue
|
||||||
val = cast(Tag, cell).get("colspan", "1")
|
cell_tag = cast(Tag, cell)
|
||||||
|
val = cell_tag.get("colspan", "1")
|
||||||
colspan = int(val) if (isinstance(val, str) and val.isnumeric()) else 1
|
colspan = int(val) if (isinstance(val, str) and val.isnumeric()) else 1
|
||||||
col_count += colspan
|
col_count += colspan
|
||||||
|
if cell_tag.name == "td" or cell_tag.get("rowspan") is None:
|
||||||
|
is_row_header = False
|
||||||
num_cols = max(num_cols, col_count)
|
num_cols = max(num_cols, col_count)
|
||||||
|
if not is_row_header:
|
||||||
|
num_rows += 1
|
||||||
|
|
||||||
|
_log.debug(f"The table has {num_rows} rows and {num_cols} cols.")
|
||||||
|
|
||||||
grid: list = [[None for _ in range(num_cols)] for _ in range(num_rows)]
|
grid: list = [[None for _ in range(num_cols)] for _ in range(num_rows)]
|
||||||
|
|
||||||
data = TableData(num_rows=num_rows, num_cols=num_cols, table_cells=[])
|
data = TableData(num_rows=num_rows, num_cols=num_cols, table_cells=[])
|
||||||
|
|
||||||
# Iterate over the rows in the table
|
# Iterate over the rows in the table
|
||||||
for row_idx, row in enumerate(element("tr")):
|
start_row_span = 0
|
||||||
|
row_idx = -1
|
||||||
|
for row in element("tr"):
|
||||||
if not isinstance(row, Tag):
|
if not isinstance(row, Tag):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# For each row, find all the column cells (both <td> and <th>)
|
# For each row, find all the column cells (both <td> and <th>)
|
||||||
cells = row(["td", "th"])
|
cells = row(["td", "th"])
|
||||||
|
|
||||||
# Check if each cell in the row is a header -> means it is a column header
|
# Check if cell is in a column header or row header
|
||||||
col_header = True
|
col_header = True
|
||||||
|
row_header = True
|
||||||
for html_cell in cells:
|
for html_cell in cells:
|
||||||
if isinstance(html_cell, Tag) and html_cell.name == "td":
|
if isinstance(html_cell, Tag):
|
||||||
col_header = False
|
if html_cell.name == "td":
|
||||||
|
col_header = False
|
||||||
|
row_header = False
|
||||||
|
elif html_cell.get("rowspan") is None:
|
||||||
|
row_header = False
|
||||||
|
if not row_header:
|
||||||
|
row_idx += 1
|
||||||
|
start_row_span = 0
|
||||||
|
else:
|
||||||
|
start_row_span += 1
|
||||||
|
|
||||||
# Extract the text content of each cell
|
# Extract the text content of each cell
|
||||||
col_idx = 0
|
col_idx = 0
|
||||||
@ -440,19 +479,24 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
if isinstance(row_val, str) and row_val.isnumeric()
|
if isinstance(row_val, str) and row_val.isnumeric()
|
||||||
else 1
|
else 1
|
||||||
)
|
)
|
||||||
|
if row_header:
|
||||||
while grid[row_idx][col_idx] is not None:
|
row_span -= 1
|
||||||
|
while (
|
||||||
|
col_idx < num_cols
|
||||||
|
and grid[row_idx + start_row_span][col_idx] is not None
|
||||||
|
):
|
||||||
col_idx += 1
|
col_idx += 1
|
||||||
for r in range(row_span):
|
for r in range(start_row_span, start_row_span + row_span):
|
||||||
for c in range(col_span):
|
for c in range(col_span):
|
||||||
grid[row_idx + r][col_idx + c] = text
|
if row_idx + r < num_rows and col_idx + c < num_cols:
|
||||||
|
grid[row_idx + r][col_idx + c] = text
|
||||||
|
|
||||||
table_cell = TableCell(
|
table_cell = TableCell(
|
||||||
text=text,
|
text=text,
|
||||||
row_span=row_span,
|
row_span=row_span,
|
||||||
col_span=col_span,
|
col_span=col_span,
|
||||||
start_row_offset_idx=row_idx,
|
start_row_offset_idx=start_row_span + row_idx,
|
||||||
end_row_offset_idx=row_idx + row_span,
|
end_row_offset_idx=start_row_span + row_idx + row_span,
|
||||||
start_col_offset_idx=col_idx,
|
start_col_offset_idx=col_idx,
|
||||||
end_col_offset_idx=col_idx + col_span,
|
end_col_offset_idx=col_idx + col_span,
|
||||||
column_header=col_header,
|
column_header=col_header,
|
||||||
|
@ -409,7 +409,7 @@ class MarkdownDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
)
|
)
|
||||||
return _txt
|
return _txt
|
||||||
|
|
||||||
# restore original HTML by removing previouly added markers
|
# restore original HTML by removing previously added markers
|
||||||
for regex in [
|
for regex in [
|
||||||
rf"<pre>\s*<code>\s*{_START_MARKER}",
|
rf"<pre>\s*<code>\s*{_START_MARKER}",
|
||||||
rf"{_STOP_MARKER}\s*</code>\s*</pre>",
|
rf"{_STOP_MARKER}\s*</code>\s*</pre>",
|
||||||
|
@ -436,7 +436,7 @@ class MsWordDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
|
|
||||||
# Common styles for bullet and numbered lists.
|
# Common styles for bullet and numbered lists.
|
||||||
# "List Bullet", "List Number", "List Paragraph"
|
# "List Bullet", "List Number", "List Paragraph"
|
||||||
# Identify wether list is a numbered list or not
|
# Identify whether list is a numbered list or not
|
||||||
# is_numbered = "List Bullet" not in paragraph.style.name
|
# is_numbered = "List Bullet" not in paragraph.style.name
|
||||||
is_numbered = False
|
is_numbered = False
|
||||||
p_style_id, p_level = self._get_label_and_level(paragraph)
|
p_style_id, p_level = self._get_label_and_level(paragraph)
|
||||||
|
@ -91,7 +91,7 @@ class JatsDocumentBackend(DeclarativeDocumentBackend):
|
|||||||
super().__init__(in_doc, path_or_stream)
|
super().__init__(in_doc, path_or_stream)
|
||||||
self.path_or_stream = path_or_stream
|
self.path_or_stream = path_or_stream
|
||||||
|
|
||||||
# Initialize the root of the document hiearchy
|
# Initialize the root of the document hierarchy
|
||||||
self.root: Optional[NodeItem] = None
|
self.root: Optional[NodeItem] = None
|
||||||
|
|
||||||
self.valid = False
|
self.valid = False
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
"""Backend to parse patents from the United States Patent Office (USPTO).
|
"""Backend to parse patents from the United States Patent Office (USPTO).
|
||||||
|
|
||||||
The parsers included in this module can handle patent grants pubished since 1976 and
|
The parsers included in this module can handle patent grants published since 1976 and
|
||||||
patent applications since 2001.
|
patent applications since 2001.
|
||||||
The original files can be found in https://bulkdata.uspto.gov.
|
The original files can be found in https://bulkdata.uspto.gov.
|
||||||
"""
|
"""
|
||||||
@ -440,7 +440,7 @@ class PatentUsptoIce(PatentUspto):
|
|||||||
)
|
)
|
||||||
|
|
||||||
elif name == self.Element.PARAGRAPH.value and text:
|
elif name == self.Element.PARAGRAPH.value and text:
|
||||||
# remmove blank spaces added in paragraphs
|
# remove blank spaces added in paragraphs
|
||||||
text = re.sub("\\s+", " ", text)
|
text = re.sub("\\s+", " ", text)
|
||||||
if self.Element.ABSTRACT.value in self.property:
|
if self.Element.ABSTRACT.value in self.property:
|
||||||
self.abstract = (
|
self.abstract = (
|
||||||
@ -1697,7 +1697,7 @@ class XmlTable:
|
|||||||
class HtmlEntity:
|
class HtmlEntity:
|
||||||
"""Provide utility functions to get the HTML entities of styled characters.
|
"""Provide utility functions to get the HTML entities of styled characters.
|
||||||
|
|
||||||
This class has been developped from:
|
This class has been developed from:
|
||||||
https://unicode-table.com/en/html-entities/
|
https://unicode-table.com/en/html-entities/
|
||||||
https://www.w3.org/TR/WD-math-970515/table03.html
|
https://www.w3.org/TR/WD-math-970515/table03.html
|
||||||
"""
|
"""
|
||||||
@ -1896,7 +1896,7 @@ class HtmlEntity:
|
|||||||
"""Get an HTML entity of a greek letter in ISO 8879.
|
"""Get an HTML entity of a greek letter in ISO 8879.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
The text to transform, as an ISO 8879 entitiy.
|
The text to transform, as an ISO 8879 entity.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
The HTML entity representing a greek letter. If the input text is not
|
The HTML entity representing a greek letter. If the input text is not
|
||||||
|
@ -421,7 +421,7 @@ def convert( # noqa: C901
|
|||||||
logging.basicConfig(level=logging.WARNING)
|
logging.basicConfig(level=logging.WARNING)
|
||||||
elif verbose == 1:
|
elif verbose == 1:
|
||||||
logging.basicConfig(level=logging.INFO)
|
logging.basicConfig(level=logging.INFO)
|
||||||
elif verbose == 2:
|
else:
|
||||||
logging.basicConfig(level=logging.DEBUG)
|
logging.basicConfig(level=logging.DEBUG)
|
||||||
|
|
||||||
settings.debug.visualize_cells = debug_visualize_cells
|
settings.debug.visualize_cells = debug_visualize_cells
|
||||||
@ -521,7 +521,7 @@ def convert( # noqa: C901
|
|||||||
if image_export_mode != ImageRefMode.PLACEHOLDER:
|
if image_export_mode != ImageRefMode.PLACEHOLDER:
|
||||||
pipeline_options.generate_page_images = True
|
pipeline_options.generate_page_images = True
|
||||||
pipeline_options.generate_picture_images = (
|
pipeline_options.generate_picture_images = (
|
||||||
True # FIXME: to be deprecated in verson 3
|
True # FIXME: to be deprecated in version 3
|
||||||
)
|
)
|
||||||
pipeline_options.images_scale = 2
|
pipeline_options.images_scale = 2
|
||||||
|
|
||||||
|
@ -32,6 +32,8 @@ class _AvailableModels(str, Enum):
|
|||||||
CODE_FORMULA = "code_formula"
|
CODE_FORMULA = "code_formula"
|
||||||
PICTURE_CLASSIFIER = "picture_classifier"
|
PICTURE_CLASSIFIER = "picture_classifier"
|
||||||
SMOLVLM = "smolvlm"
|
SMOLVLM = "smolvlm"
|
||||||
|
SMOLDOCLING = "smoldocling"
|
||||||
|
SMOLDOCLING_MLX = "smoldocling_mlx"
|
||||||
GRANITE_VISION = "granite_vision"
|
GRANITE_VISION = "granite_vision"
|
||||||
EASYOCR = "easyocr"
|
EASYOCR = "easyocr"
|
||||||
|
|
||||||
@ -105,6 +107,8 @@ def download(
|
|||||||
with_code_formula=_AvailableModels.CODE_FORMULA in to_download,
|
with_code_formula=_AvailableModels.CODE_FORMULA in to_download,
|
||||||
with_picture_classifier=_AvailableModels.PICTURE_CLASSIFIER in to_download,
|
with_picture_classifier=_AvailableModels.PICTURE_CLASSIFIER in to_download,
|
||||||
with_smolvlm=_AvailableModels.SMOLVLM in to_download,
|
with_smolvlm=_AvailableModels.SMOLVLM in to_download,
|
||||||
|
with_smoldocling=_AvailableModels.SMOLDOCLING in to_download,
|
||||||
|
with_smoldocling_mlx=_AvailableModels.SMOLDOCLING_MLX in to_download,
|
||||||
with_granite_vision=_AvailableModels.GRANITE_VISION in to_download,
|
with_granite_vision=_AvailableModels.GRANITE_VISION in to_download,
|
||||||
with_easyocr=_AvailableModels.EASYOCR in to_download,
|
with_easyocr=_AvailableModels.EASYOCR in to_download,
|
||||||
)
|
)
|
||||||
|
@ -303,6 +303,14 @@ class _DocumentConversionInput(BaseModel):
|
|||||||
else ""
|
else ""
|
||||||
)
|
)
|
||||||
mime = _DocumentConversionInput._mime_from_extension(ext)
|
mime = _DocumentConversionInput._mime_from_extension(ext)
|
||||||
|
if mime is not None and mime.lower() == "application/zip":
|
||||||
|
objname = obj.name.lower()
|
||||||
|
if objname.endswith(".xlsx"):
|
||||||
|
mime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||||
|
elif objname.endswith(".docx"):
|
||||||
|
mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
||||||
|
elif objname.endswith(".pptx"):
|
||||||
|
mime = "application/vnd.openxmlformats-officedocument.presentationml.presentation"
|
||||||
|
|
||||||
mime = mime or _DocumentConversionInput._detect_html_xhtml(content)
|
mime = mime or _DocumentConversionInput._detect_html_xhtml(content)
|
||||||
mime = mime or _DocumentConversionInput._detect_csv(content)
|
mime = mime or _DocumentConversionInput._detect_csv(content)
|
||||||
|
@ -189,7 +189,9 @@ class DocumentConverter:
|
|||||||
def _get_pipeline_options_hash(self, pipeline_options: PipelineOptions) -> str:
|
def _get_pipeline_options_hash(self, pipeline_options: PipelineOptions) -> str:
|
||||||
"""Generate a hash of pipeline options to use as part of the cache key."""
|
"""Generate a hash of pipeline options to use as part of the cache key."""
|
||||||
options_str = str(pipeline_options.model_dump())
|
options_str = str(pipeline_options.model_dump())
|
||||||
return hashlib.md5(options_str.encode("utf-8")).hexdigest()
|
return hashlib.md5(
|
||||||
|
options_str.encode("utf-8"), usedforsecurity=False
|
||||||
|
).hexdigest()
|
||||||
|
|
||||||
def initialize_pipeline(self, format: InputFormat):
|
def initialize_pipeline(self, format: InputFormat):
|
||||||
"""Initialize the conversion pipeline for the selected format."""
|
"""Initialize the conversion pipeline for the selected format."""
|
||||||
|
@ -57,7 +57,10 @@ class PictureDescriptionVlmModel(PictureDescriptionBaseModel):
|
|||||||
artifacts_path,
|
artifacts_path,
|
||||||
torch_dtype=torch.bfloat16,
|
torch_dtype=torch.bfloat16,
|
||||||
_attn_implementation=(
|
_attn_implementation=(
|
||||||
"flash_attention_2" if self.device.startswith("cuda") else "eager"
|
"flash_attention_2"
|
||||||
|
if self.device.startswith("cuda")
|
||||||
|
and accelerator_options.cuda_use_flash_attention2
|
||||||
|
else "eager"
|
||||||
),
|
),
|
||||||
).to(self.device)
|
).to(self.device)
|
||||||
|
|
||||||
|
@ -346,7 +346,7 @@ class ReadingOrderModel:
|
|||||||
new_item.prov.append(prov)
|
new_item.prov.append(prov)
|
||||||
|
|
||||||
def __call__(self, conv_res: ConversionResult) -> DoclingDocument:
|
def __call__(self, conv_res: ConversionResult) -> DoclingDocument:
|
||||||
with TimeRecorder(conv_res, "glm", scope=ProfilingScope.DOCUMENT):
|
with TimeRecorder(conv_res, "reading_order", scope=ProfilingScope.DOCUMENT):
|
||||||
page_elements = self._assembled_to_readingorder_elements(conv_res)
|
page_elements = self._assembled_to_readingorder_elements(conv_res)
|
||||||
|
|
||||||
# Apply reading order
|
# Apply reading order
|
||||||
|
@ -234,7 +234,7 @@ class TableStructureModel(BasePageModel):
|
|||||||
tcells = table_cluster.cells
|
tcells = table_cluster.cells
|
||||||
tokens = []
|
tokens = []
|
||||||
for c in tcells:
|
for c in tcells:
|
||||||
# Only allow non empty stings (spaces) into the cells of a table
|
# Only allow non empty strings (spaces) into the cells of a table
|
||||||
if len(c.text.strip()) > 0:
|
if len(c.text.strip()) > 0:
|
||||||
new_cell = copy.deepcopy(c)
|
new_cell = copy.deepcopy(c)
|
||||||
new_cell.rect = BoundingRectangle.from_bounding_box(
|
new_cell.rect = BoundingRectangle.from_bounding_box(
|
||||||
@ -267,7 +267,7 @@ class TableStructureModel(BasePageModel):
|
|||||||
element["bbox"]["token"] = text_piece
|
element["bbox"]["token"] = text_piece
|
||||||
|
|
||||||
tc = TableCell.model_validate(element)
|
tc = TableCell.model_validate(element)
|
||||||
if self.do_cell_matching and tc.bbox is not None:
|
if tc.bbox is not None:
|
||||||
tc.bbox = tc.bbox.scaled(1 / self.scale)
|
tc.bbox = tc.bbox.scaled(1 / self.scale)
|
||||||
table_cells.append(tc)
|
table_cells.append(tc)
|
||||||
|
|
||||||
|
@ -1,3 +1,5 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from collections.abc import Iterable
|
from collections.abc import Iterable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@ -38,6 +40,8 @@ class TesseractOcrModel(BaseOcrModel):
|
|||||||
self.options: TesseractOcrOptions
|
self.options: TesseractOcrOptions
|
||||||
|
|
||||||
self.scale = 3 # multiplier for 72 dpi == 216 dpi.
|
self.scale = 3 # multiplier for 72 dpi == 216 dpi.
|
||||||
|
self.reader = None
|
||||||
|
self.script_readers: dict[str, tesserocr.PyTessBaseAPI] = {}
|
||||||
|
|
||||||
if self.enabled:
|
if self.enabled:
|
||||||
install_errmsg = (
|
install_errmsg = (
|
||||||
@ -84,9 +88,7 @@ class TesseractOcrModel(BaseOcrModel):
|
|||||||
"oem": tesserocr.OEM.DEFAULT,
|
"oem": tesserocr.OEM.DEFAULT,
|
||||||
}
|
}
|
||||||
|
|
||||||
self.reader = None
|
|
||||||
self.osd_reader = None
|
self.osd_reader = None
|
||||||
self.script_readers: dict[str, tesserocr.PyTessBaseAPI] = {}
|
|
||||||
|
|
||||||
if self.options.path is not None:
|
if self.options.path is not None:
|
||||||
tesserocr_kwargs["path"] = self.options.path
|
tesserocr_kwargs["path"] = self.options.path
|
||||||
@ -151,7 +153,7 @@ class TesseractOcrModel(BaseOcrModel):
|
|||||||
script = map_tesseract_script(script)
|
script = map_tesseract_script(script)
|
||||||
lang = f"{self.script_prefix}{script}"
|
lang = f"{self.script_prefix}{script}"
|
||||||
|
|
||||||
# Check if the detected languge is present in the system
|
# Check if the detected language is present in the system
|
||||||
if lang not in self._tesserocr_languages:
|
if lang not in self._tesserocr_languages:
|
||||||
msg = f"Tesseract detected the script '{script}' and language '{lang}'."
|
msg = f"Tesseract detected the script '{script}' and language '{lang}'."
|
||||||
msg += " However this language is not installed in your system and will be ignored."
|
msg += " However this language is not installed in your system and will be ignored."
|
||||||
|
@ -4,12 +4,15 @@ from typing import Optional
|
|||||||
|
|
||||||
from docling.datamodel.pipeline_options import (
|
from docling.datamodel.pipeline_options import (
|
||||||
granite_picture_description,
|
granite_picture_description,
|
||||||
|
smoldocling_vlm_conversion_options,
|
||||||
|
smoldocling_vlm_mlx_conversion_options,
|
||||||
smolvlm_picture_description,
|
smolvlm_picture_description,
|
||||||
)
|
)
|
||||||
from docling.datamodel.settings import settings
|
from docling.datamodel.settings import settings
|
||||||
from docling.models.code_formula_model import CodeFormulaModel
|
from docling.models.code_formula_model import CodeFormulaModel
|
||||||
from docling.models.document_picture_classifier import DocumentPictureClassifier
|
from docling.models.document_picture_classifier import DocumentPictureClassifier
|
||||||
from docling.models.easyocr_model import EasyOcrModel
|
from docling.models.easyocr_model import EasyOcrModel
|
||||||
|
from docling.models.hf_vlm_model import HuggingFaceVlmModel
|
||||||
from docling.models.layout_model import LayoutModel
|
from docling.models.layout_model import LayoutModel
|
||||||
from docling.models.picture_description_vlm_model import PictureDescriptionVlmModel
|
from docling.models.picture_description_vlm_model import PictureDescriptionVlmModel
|
||||||
from docling.models.table_structure_model import TableStructureModel
|
from docling.models.table_structure_model import TableStructureModel
|
||||||
@ -27,6 +30,8 @@ def download_models(
|
|||||||
with_code_formula: bool = True,
|
with_code_formula: bool = True,
|
||||||
with_picture_classifier: bool = True,
|
with_picture_classifier: bool = True,
|
||||||
with_smolvlm: bool = False,
|
with_smolvlm: bool = False,
|
||||||
|
with_smoldocling: bool = False,
|
||||||
|
with_smoldocling_mlx: bool = False,
|
||||||
with_granite_vision: bool = False,
|
with_granite_vision: bool = False,
|
||||||
with_easyocr: bool = True,
|
with_easyocr: bool = True,
|
||||||
):
|
):
|
||||||
@ -77,6 +82,25 @@ def download_models(
|
|||||||
progress=progress,
|
progress=progress,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if with_smoldocling:
|
||||||
|
_log.info("Downloading SmolDocling model...")
|
||||||
|
HuggingFaceVlmModel.download_models(
|
||||||
|
repo_id=smoldocling_vlm_conversion_options.repo_id,
|
||||||
|
local_dir=output_dir / smoldocling_vlm_conversion_options.repo_cache_folder,
|
||||||
|
force=force,
|
||||||
|
progress=progress,
|
||||||
|
)
|
||||||
|
|
||||||
|
if with_smoldocling_mlx:
|
||||||
|
_log.info("Downloading SmolDocling MLX model...")
|
||||||
|
HuggingFaceVlmModel.download_models(
|
||||||
|
repo_id=smoldocling_vlm_mlx_conversion_options.repo_id,
|
||||||
|
local_dir=output_dir
|
||||||
|
/ smoldocling_vlm_mlx_conversion_options.repo_cache_folder,
|
||||||
|
force=force,
|
||||||
|
progress=progress,
|
||||||
|
)
|
||||||
|
|
||||||
if with_granite_vision:
|
if with_granite_vision:
|
||||||
_log.info("Downloading Granite Vision model...")
|
_log.info("Downloading Granite Vision model...")
|
||||||
PictureDescriptionVlmModel.download_models(
|
PictureDescriptionVlmModel.download_models(
|
||||||
|
@ -20,7 +20,7 @@ def create_file_hash(path_or_stream: Union[BytesIO, Path]) -> str:
|
|||||||
"""Create a stable page_hash of the path_or_stream of a file"""
|
"""Create a stable page_hash of the path_or_stream of a file"""
|
||||||
|
|
||||||
block_size = 65536
|
block_size = 65536
|
||||||
hasher = hashlib.sha256()
|
hasher = hashlib.sha256(usedforsecurity=False)
|
||||||
|
|
||||||
def _hash_buf(binary_stream):
|
def _hash_buf(binary_stream):
|
||||||
buf = binary_stream.read(block_size) # read and page_hash in chunks
|
buf = binary_stream.read(block_size) # read and page_hash in chunks
|
||||||
@ -38,7 +38,7 @@ def create_file_hash(path_or_stream: Union[BytesIO, Path]) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def create_hash(string: str):
|
def create_hash(string: str):
|
||||||
hasher = hashlib.sha256()
|
hasher = hashlib.sha256(usedforsecurity=False)
|
||||||
hasher.update(string.encode("utf-8"))
|
hasher.update(string.encode("utf-8"))
|
||||||
|
|
||||||
return hasher.hexdigest()
|
return hasher.hexdigest()
|
||||||
|
@ -6,11 +6,12 @@ For each document format, the *document converter* knows which format-specific *
|
|||||||
|
|
||||||
!!! tip
|
!!! tip
|
||||||
|
|
||||||
While the document converter holds a default mapping, this configuration is parametrizable, so e.g. for the PDF format, different backends and different pipeline options can be used — see [Usage](../usage.md#adjust-pipeline-features).
|
While the document converter holds a default mapping, this configuration is parametrizable, so e.g. for the PDF format, different backends and different pipeline options can be used — see [Usage](../usage/index.md#adjust-pipeline-features).
|
||||||
|
|
||||||
The *conversion result* contains the [*Docling document*](./docling_document.md), Docling's fundamental document representation.
|
The *conversion result* contains the [*Docling document*](./docling_document.md), Docling's fundamental document representation.
|
||||||
|
|
||||||
Some typical scenarios for using a Docling document include directly calling its *export methods*, such as for markdown, dictionary etc., or having it chunked by a [*chunker*](./chunking.md).
|
Some typical scenarios for using a Docling document include directly calling its *export methods*, such as for markdown, dictionary etc., or having it serialized by a
|
||||||
|
[*serializer*](./serialization.md) or chunked by a [*chunker*](./chunking.md).
|
||||||
|
|
||||||
For more details on Docling's architecture, check out the [Docling Technical Report](https://arxiv.org/abs/2408.09869).
|
For more details on Docling's architecture, check out the [Docling Technical Report](https://arxiv.org/abs/2408.09869).
|
||||||
|
|
||||||
|
@ -31,7 +31,7 @@ The `BaseChunker` base class API defines that any chunker should provide the fol
|
|||||||
|
|
||||||
- `def chunk(self, dl_doc: DoclingDocument, **kwargs) -> Iterator[BaseChunk]`:
|
- `def chunk(self, dl_doc: DoclingDocument, **kwargs) -> Iterator[BaseChunk]`:
|
||||||
Returning the chunks for the provided document.
|
Returning the chunks for the provided document.
|
||||||
- `def serialize(self, chunk: BaseChunk) -> str`:
|
- `def contextualize(self, chunk: BaseChunk) -> str`:
|
||||||
Returning the potentially metadata-enriched serialization of the chunk, typically
|
Returning the potentially metadata-enriched serialization of the chunk, typically
|
||||||
used to feed an embedding model (or generation model).
|
used to feed an embedding model (or generation model).
|
||||||
|
|
||||||
@ -44,10 +44,14 @@ The `BaseChunker` base class API defines that any chunker should provide the fol
|
|||||||
from docling.chunking import HybridChunker
|
from docling.chunking import HybridChunker
|
||||||
```
|
```
|
||||||
- If you are only using the `docling-core` package, you must ensure to install
|
- If you are only using the `docling-core` package, you must ensure to install
|
||||||
the `chunking` extra, e.g.
|
the `chunking` extra if you want to use HuggingFace tokenizers, e.g.
|
||||||
```shell
|
```shell
|
||||||
pip install 'docling-core[chunking]'
|
pip install 'docling-core[chunking]'
|
||||||
```
|
```
|
||||||
|
or the `chunking-openai` extra if you prefer Open AI tokenizers (tiktoken), e.g.
|
||||||
|
```shell
|
||||||
|
pip install 'docling-core[chunking-openai]'
|
||||||
|
```
|
||||||
and then you
|
and then you
|
||||||
can import as follows:
|
can import as follows:
|
||||||
```python
|
```python
|
||||||
|
@ -31,7 +31,7 @@ The first category is the _content items_, which are stored in these fields:
|
|||||||
All of the above fields are lists and store items inheriting from the `DocItem` type. They can express different
|
All of the above fields are lists and store items inheriting from the `DocItem` type. They can express different
|
||||||
data structures depending on their type, and reference parents and children through JSON pointers.
|
data structures depending on their type, and reference parents and children through JSON pointers.
|
||||||
|
|
||||||
The second category is _content structure_, which is encapsualted in:
|
The second category is _content structure_, which is encapsulated in:
|
||||||
|
|
||||||
- `body`: The root node of a tree-structure for the main document body
|
- `body`: The root node of a tree-structure for the main document body
|
||||||
- `furniture`: The root node of a tree-structure for all items that don't belong into the body (headers, footers, ...)
|
- `furniture`: The root node of a tree-structure for all items that don't belong into the body (headers, footers, ...)
|
||||||
@ -49,7 +49,7 @@ Below example shows how all items in the first page are nested below the `title`
|
|||||||
|
|
||||||
### Grouping
|
### Grouping
|
||||||
|
|
||||||
Below example shows how all items under the heading "Let's swim" (`#/texts/5`) are nested as chilrden. The children of
|
Below example shows how all items under the heading "Let's swim" (`#/texts/5`) are nested as children. The children of
|
||||||
"Let's swim" are both text items and groups, which contain the list elements. The group items are stored in the
|
"Let's swim" are both text items and groups, which contain the list elements. The group items are stored in the
|
||||||
top-level `groups` field.
|
top-level `groups` field.
|
||||||
|
|
||||||
|
40
docs/concepts/serialization.md
Normal file
40
docs/concepts/serialization.md
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
## Introduction
|
||||||
|
|
||||||
|
A *document serializer* (AKA simply *serializer*) is a Docling abstraction that is
|
||||||
|
initialized with a given [`DoclingDocument`](./docling_document.md) and returns a
|
||||||
|
textual representation for that document.
|
||||||
|
|
||||||
|
Besides the document serializer, Docling defines similar abstractions for several
|
||||||
|
document subcomponents, for example: *text serializer*, *table serializer*,
|
||||||
|
*picture serializer*, *list serializer*, *inline serializer*, and more.
|
||||||
|
|
||||||
|
Last but not least, a *serializer provider* is a wrapper that abstracts the
|
||||||
|
document serialization strategy from the document instance.
|
||||||
|
|
||||||
|
## Base classes
|
||||||
|
|
||||||
|
To enable both flexibility for downstream applications and out-of-the-box utility,
|
||||||
|
Docling defines a serialization class hierarchy, providing:
|
||||||
|
|
||||||
|
- base types for the above abstractions: `BaseDocSerializer`, as well as
|
||||||
|
`BaseTextSerializer`, `BaseTableSerializer` etc, and `BaseSerializerProvider`, and
|
||||||
|
- specific subclasses for the above-mentioned base types, e.g. `MarkdownDocSerializer`.
|
||||||
|
|
||||||
|
You can review all methods required to define the above base classes [here](https://github.com/docling-project/docling-core/blob/main/docling_core/transforms/serializer/base.py).
|
||||||
|
|
||||||
|
From a client perspective, the most relevant is `BaseDocSerializer.serialize()`, which
|
||||||
|
returns the textual representation, as well as relevant metadata on which document
|
||||||
|
components contributed to that serialization.
|
||||||
|
|
||||||
|
## Use in `DoclingDocument` export methods
|
||||||
|
|
||||||
|
Docling provides predefined serializers for Markdown, HTML, and DocTags.
|
||||||
|
|
||||||
|
The respective `DoclingDocument` export methods (e.g. `export_to_markdown()`) are
|
||||||
|
provided as user shorthands — internally directly instantiating and delegating to
|
||||||
|
respective serializers.
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
For an example showcasing how to use serializers, see
|
||||||
|
[here](../examples/serialization.ipynb).
|
@ -569,7 +569,7 @@
|
|||||||
"The `DoclingDocument` format of the converted patents has a rich hierarchical structure, inherited from the original XML document and preserved by the Docling custom backend.\n",
|
"The `DoclingDocument` format of the converted patents has a rich hierarchical structure, inherited from the original XML document and preserved by the Docling custom backend.\n",
|
||||||
"In this notebook, we will leverage:\n",
|
"In this notebook, we will leverage:\n",
|
||||||
"- The `SimpleDirectoryReader` pattern to iterate over the exported XML files created in section [Fetch the data](#fetch-the-data).\n",
|
"- The `SimpleDirectoryReader` pattern to iterate over the exported XML files created in section [Fetch the data](#fetch-the-data).\n",
|
||||||
"- The LlamaIndex extensions, `DoclingReader` and `DoclingNodeParser`, to ingest the patent chunks into a Milvus vectore store.\n",
|
"- The LlamaIndex extensions, `DoclingReader` and `DoclingNodeParser`, to ingest the patent chunks into a Milvus vector store.\n",
|
||||||
"- The `HierarchicalChunker` implementation, which applies a document-based hierarchical chunking, to leverage the patent structures like sections and paragraphs within sections.\n",
|
"- The `HierarchicalChunker` implementation, which applies a document-based hierarchical chunking, to leverage the patent structures like sections and paragraphs within sections.\n",
|
||||||
"\n",
|
"\n",
|
||||||
"Refer to other possible implementations and usage patterns in the [Chunking](../../concepts/chunking/) documentation and the [RAG with LlamaIndex](../rag_llamaindex/) notebook."
|
"Refer to other possible implementations and usage patterns in the [Chunking](../../concepts/chunking/) documentation and the [RAG with LlamaIndex](../rag_llamaindex/) notebook."
|
||||||
|
@ -44,14 +44,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"source": [
|
"source": [
|
||||||
"%pip install -qU docling transformers"
|
"%pip install -qU pip docling transformers"
|
||||||
]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"cell_type": "markdown",
|
|
||||||
"metadata": {},
|
|
||||||
"source": [
|
|
||||||
"## Conversion"
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -59,11 +52,32 @@
|
|||||||
"execution_count": 2,
|
"execution_count": 2,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"DOC_SOURCE = \"../../tests/data/md/wiki.md\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Basic usage"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We first convert the document:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
"from docling.document_converter import DocumentConverter\n",
|
"from docling.document_converter import DocumentConverter\n",
|
||||||
"\n",
|
"\n",
|
||||||
"DOC_SOURCE = \"../../tests/data/md/wiki.md\"\n",
|
|
||||||
"\n",
|
|
||||||
"doc = DocumentConverter().convert(source=DOC_SOURCE).document"
|
"doc = DocumentConverter().convert(source=DOC_SOURCE).document"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
@ -71,17 +85,13 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"## Chunking\n",
|
"For a basic chunking scenario, we can just instantiate a `HybridChunker`, which will use\n",
|
||||||
"\n",
|
|
||||||
"### Basic usage\n",
|
|
||||||
"\n",
|
|
||||||
"For a basic usage scenario, we can just instantiate a `HybridChunker`, which will use\n",
|
|
||||||
"the default parameters."
|
"the default parameters."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": 3,
|
"execution_count": 4,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
@ -111,12 +121,12 @@
|
|||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"Note that the text you would typically want to embed is the context-enriched one as\n",
|
"Note that the text you would typically want to embed is the context-enriched one as\n",
|
||||||
"returned by the `serialize()` method:"
|
"returned by the `contextualize()` method:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": 4,
|
"execution_count": 5,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
@ -126,25 +136,25 @@
|
|||||||
"=== 0 ===\n",
|
"=== 0 ===\n",
|
||||||
"chunk.text:\n",
|
"chunk.text:\n",
|
||||||
"'International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Aver…'\n",
|
"'International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Aver…'\n",
|
||||||
"chunker.serialize(chunk):\n",
|
"chunker.contextualize(chunk):\n",
|
||||||
"'IBM\\nInternational Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial …'\n",
|
"'IBM\\nInternational Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial …'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 1 ===\n",
|
"=== 1 ===\n",
|
||||||
"chunk.text:\n",
|
"chunk.text:\n",
|
||||||
"'IBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine (1889);[19] and Willa…'\n",
|
"'IBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine (1889);[19] and Willa…'\n",
|
||||||
"chunker.serialize(chunk):\n",
|
"chunker.contextualize(chunk):\n",
|
||||||
"'IBM\\n1910s–1950s\\nIBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine (1889…'\n",
|
"'IBM\\n1910s–1950s\\nIBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine (1889…'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 2 ===\n",
|
"=== 2 ===\n",
|
||||||
"chunk.text:\n",
|
"chunk.text:\n",
|
||||||
"'Collectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson,…'\n",
|
"'Collectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson,…'\n",
|
||||||
"chunker.serialize(chunk):\n",
|
"chunker.contextualize(chunk):\n",
|
||||||
"'IBM\\n1910s–1950s\\nCollectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John …'\n",
|
"'IBM\\n1910s–1950s\\nCollectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John …'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 3 ===\n",
|
"=== 3 ===\n",
|
||||||
"chunk.text:\n",
|
"chunk.text:\n",
|
||||||
"'In 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.…'\n",
|
"'In 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.…'\n",
|
||||||
"chunker.serialize(chunk):\n",
|
"chunker.contextualize(chunk):\n",
|
||||||
"'IBM\\n1960s–1980s\\nIn 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.…'\n",
|
"'IBM\\n1960s–1980s\\nIn 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.…'\n",
|
||||||
"\n"
|
"\n"
|
||||||
]
|
]
|
||||||
@ -155,8 +165,8 @@
|
|||||||
" print(f\"=== {i} ===\")\n",
|
" print(f\"=== {i} ===\")\n",
|
||||||
" print(f\"chunk.text:\\n{f'{chunk.text[:300]}…'!r}\")\n",
|
" print(f\"chunk.text:\\n{f'{chunk.text[:300]}…'!r}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" enriched_text = chunker.serialize(chunk=chunk)\n",
|
" enriched_text = chunker.contextualize(chunk=chunk)\n",
|
||||||
" print(f\"chunker.serialize(chunk):\\n{f'{enriched_text[:300]}…'!r}\")\n",
|
" print(f\"chunker.contextualize(chunk):\\n{f'{enriched_text[:300]}…'!r}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" print()"
|
" print()"
|
||||||
]
|
]
|
||||||
@ -165,23 +175,23 @@
|
|||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"### Advanced usage\n",
|
"## Configuring tokenization\n",
|
||||||
"\n",
|
"\n",
|
||||||
"For more control on the chunking, we can parametrize through the `HybridChunker`\n",
|
"For more control on the chunking, we can parametrize tokenization as shown below.\n",
|
||||||
"arguments illustrated below.\n",
|
|
||||||
"\n",
|
"\n",
|
||||||
"Notice how `tokenizer` and `embed_model` further below are single-sourced from\n",
|
"In a RAG / retrieval context, it is important to make sure that the chunker and\n",
|
||||||
"`EMBED_MODEL_ID`.\n",
|
"embedding model are using the same tokenizer.\n",
|
||||||
"This is important for making sure the chunker and the embedding model are using the same\n",
|
"\n",
|
||||||
"tokenizer."
|
"👉 HuggingFace transformers tokenizers can be used as shown in the following example:"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": 5,
|
"execution_count": 6,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
"from docling_core.transforms.chunker.tokenizer.huggingface import HuggingFaceTokenizer\n",
|
||||||
"from transformers import AutoTokenizer\n",
|
"from transformers import AutoTokenizer\n",
|
||||||
"\n",
|
"\n",
|
||||||
"from docling.chunking import HybridChunker\n",
|
"from docling.chunking import HybridChunker\n",
|
||||||
@ -189,11 +199,50 @@
|
|||||||
"EMBED_MODEL_ID = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
|
"EMBED_MODEL_ID = \"sentence-transformers/all-MiniLM-L6-v2\"\n",
|
||||||
"MAX_TOKENS = 64 # set to a small number for illustrative purposes\n",
|
"MAX_TOKENS = 64 # set to a small number for illustrative purposes\n",
|
||||||
"\n",
|
"\n",
|
||||||
"tokenizer = AutoTokenizer.from_pretrained(EMBED_MODEL_ID)\n",
|
"tokenizer = HuggingFaceTokenizer(\n",
|
||||||
|
" tokenizer=AutoTokenizer.from_pretrained(EMBED_MODEL_ID),\n",
|
||||||
|
" max_tokens=MAX_TOKENS, # optional, by default derived from `tokenizer` for HF case\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"👉 Alternatively, [OpenAI tokenizers](https://github.com/openai/tiktoken) can be used as shown in the example below (uncomment to use — requires installing `docling-core[chunking-openai]`):"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"# import tiktoken\n",
|
||||||
"\n",
|
"\n",
|
||||||
|
"# from docling_core.transforms.chunker.tokenizer.openai import OpenAITokenizer\n",
|
||||||
|
"\n",
|
||||||
|
"# tokenizer = OpenAITokenizer(\n",
|
||||||
|
"# tokenizer=tiktoken.encoding_for_model(\"gpt-4o\"),\n",
|
||||||
|
"# max_tokens=128 * 1024, # context window length required for OpenAI tokenizers\n",
|
||||||
|
"# )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can now instantiate our chunker:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
"chunker = HybridChunker(\n",
|
"chunker = HybridChunker(\n",
|
||||||
" tokenizer=tokenizer, # instance or model name, defaults to \"sentence-transformers/all-MiniLM-L6-v2\"\n",
|
" tokenizer=tokenizer,\n",
|
||||||
" max_tokens=MAX_TOKENS, # optional, by default derived from `tokenizer`\n",
|
|
||||||
" merge_peers=True, # optional, defaults to True\n",
|
" merge_peers=True, # optional, defaults to True\n",
|
||||||
")\n",
|
")\n",
|
||||||
"chunk_iter = chunker.chunk(dl_doc=doc)\n",
|
"chunk_iter = chunker.chunk(dl_doc=doc)\n",
|
||||||
@ -206,14 +255,14 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"Points to notice looking at the output chunks below:\n",
|
"Points to notice looking at the output chunks below:\n",
|
||||||
"- Where possible, we fit the limit of 64 tokens for the metadata-enriched serialization form (see chunk 2)\n",
|
"- Where possible, we fit the limit of 64 tokens for the metadata-enriched serialization form (see chunk 2)\n",
|
||||||
"- Where neeeded, we stop before the limit, e.g. see cases of 63 as it would otherwise run into a comma (see chunk 6)\n",
|
"- Where needed, we stop before the limit, e.g. see cases of 63 as it would otherwise run into a comma (see chunk 6)\n",
|
||||||
"- Where possible, we merge undersized peer chunks (see chunk 0)\n",
|
"- Where possible, we merge undersized peer chunks (see chunk 0)\n",
|
||||||
"- \"Tail\" chunks trailing right after merges may still be undersized (see chunk 8)"
|
"- \"Tail\" chunks trailing right after merges may still be undersized (see chunk 8)"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": 6,
|
"execution_count": 9,
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [
|
"outputs": [
|
||||||
{
|
{
|
||||||
@ -223,127 +272,127 @@
|
|||||||
"=== 0 ===\n",
|
"=== 0 ===\n",
|
||||||
"chunk.text (55 tokens):\n",
|
"chunk.text (55 tokens):\n",
|
||||||
"'International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Average.'\n",
|
"'International Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Average.'\n",
|
||||||
"chunker.serialize(chunk) (56 tokens):\n",
|
"chunker.contextualize(chunk) (56 tokens):\n",
|
||||||
"'IBM\\nInternational Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Average.'\n",
|
"'IBM\\nInternational Business Machines Corporation (using the trademark IBM), nicknamed Big Blue, is an American multinational technology company headquartered in Armonk, New York and present in over 175 countries.\\nIt is a publicly traded company and one of the 30 companies in the Dow Jones Industrial Average.'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 1 ===\n",
|
"=== 1 ===\n",
|
||||||
"chunk.text (45 tokens):\n",
|
"chunk.text (45 tokens):\n",
|
||||||
"'IBM is the largest industrial research organization in the world, with 19 research facilities across a dozen countries, having held the record for most annual U.S. patents generated by a business for 29 consecutive years from 1993 to 2021.'\n",
|
"'IBM is the largest industrial research organization in the world, with 19 research facilities across a dozen countries, having held the record for most annual U.S. patents generated by a business for 29 consecutive years from 1993 to 2021.'\n",
|
||||||
"chunker.serialize(chunk) (46 tokens):\n",
|
"chunker.contextualize(chunk) (46 tokens):\n",
|
||||||
"'IBM\\nIBM is the largest industrial research organization in the world, with 19 research facilities across a dozen countries, having held the record for most annual U.S. patents generated by a business for 29 consecutive years from 1993 to 2021.'\n",
|
"'IBM\\nIBM is the largest industrial research organization in the world, with 19 research facilities across a dozen countries, having held the record for most annual U.S. patents generated by a business for 29 consecutive years from 1993 to 2021.'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 2 ===\n",
|
"=== 2 ===\n",
|
||||||
"chunk.text (63 tokens):\n",
|
"chunk.text (63 tokens):\n",
|
||||||
"'IBM was founded in 1911 as the Computing-Tabulating-Recording Company (CTR), a holding company of manufacturers of record-keeping and measuring systems. It was renamed \"International Business Machines\" in 1924 and soon became the leading manufacturer of punch-card tabulating systems. During the 1960s and 1970s, the'\n",
|
"'IBM was founded in 1911 as the Computing-Tabulating-Recording Company (CTR), a holding company of manufacturers of record-keeping and measuring systems. It was renamed \"International Business Machines\" in 1924 and soon became the leading manufacturer of punch-card tabulating systems. During the 1960s and 1970s, the'\n",
|
||||||
"chunker.serialize(chunk) (64 tokens):\n",
|
"chunker.contextualize(chunk) (64 tokens):\n",
|
||||||
"'IBM\\nIBM was founded in 1911 as the Computing-Tabulating-Recording Company (CTR), a holding company of manufacturers of record-keeping and measuring systems. It was renamed \"International Business Machines\" in 1924 and soon became the leading manufacturer of punch-card tabulating systems. During the 1960s and 1970s, the'\n",
|
"'IBM\\nIBM was founded in 1911 as the Computing-Tabulating-Recording Company (CTR), a holding company of manufacturers of record-keeping and measuring systems. It was renamed \"International Business Machines\" in 1924 and soon became the leading manufacturer of punch-card tabulating systems. During the 1960s and 1970s, the'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 3 ===\n",
|
"=== 3 ===\n",
|
||||||
"chunk.text (44 tokens):\n",
|
"chunk.text (44 tokens):\n",
|
||||||
"\"IBM mainframe, exemplified by the System/360, was the world's dominant computing platform, with the company producing 80 percent of computers in the U.S. and 70 percent of computers worldwide.[11]\"\n",
|
"\"IBM mainframe, exemplified by the System/360, was the world's dominant computing platform, with the company producing 80 percent of computers in the U.S. and 70 percent of computers worldwide.[11]\"\n",
|
||||||
"chunker.serialize(chunk) (45 tokens):\n",
|
"chunker.contextualize(chunk) (45 tokens):\n",
|
||||||
"\"IBM\\nIBM mainframe, exemplified by the System/360, was the world's dominant computing platform, with the company producing 80 percent of computers in the U.S. and 70 percent of computers worldwide.[11]\"\n",
|
"\"IBM\\nIBM mainframe, exemplified by the System/360, was the world's dominant computing platform, with the company producing 80 percent of computers in the U.S. and 70 percent of computers worldwide.[11]\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 4 ===\n",
|
"=== 4 ===\n",
|
||||||
"chunk.text (63 tokens):\n",
|
"chunk.text (63 tokens):\n",
|
||||||
"'IBM debuted in the microcomputer market in 1981 with the IBM Personal Computer, — its DOS software provided by Microsoft, — which became the basis for the majority of personal computers to the present day.[12] The company later also found success in the portable space with the ThinkPad. Since the 1990s,'\n",
|
"'IBM debuted in the microcomputer market in 1981 with the IBM Personal Computer, — its DOS software provided by Microsoft, — which became the basis for the majority of personal computers to the present day.[12] The company later also found success in the portable space with the ThinkPad. Since the 1990s,'\n",
|
||||||
"chunker.serialize(chunk) (64 tokens):\n",
|
"chunker.contextualize(chunk) (64 tokens):\n",
|
||||||
"'IBM\\nIBM debuted in the microcomputer market in 1981 with the IBM Personal Computer, — its DOS software provided by Microsoft, — which became the basis for the majority of personal computers to the present day.[12] The company later also found success in the portable space with the ThinkPad. Since the 1990s,'\n",
|
"'IBM\\nIBM debuted in the microcomputer market in 1981 with the IBM Personal Computer, — its DOS software provided by Microsoft, — which became the basis for the majority of personal computers to the present day.[12] The company later also found success in the portable space with the ThinkPad. Since the 1990s,'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 5 ===\n",
|
"=== 5 ===\n",
|
||||||
"chunk.text (61 tokens):\n",
|
"chunk.text (61 tokens):\n",
|
||||||
"'IBM has concentrated on computer services, software, supercomputers, and scientific research; it sold its microcomputer division to Lenovo in 2005. IBM continues to develop mainframes, and its supercomputers have consistently ranked among the most powerful in the world in the 21st century.'\n",
|
"'IBM has concentrated on computer services, software, supercomputers, and scientific research; it sold its microcomputer division to Lenovo in 2005. IBM continues to develop mainframes, and its supercomputers have consistently ranked among the most powerful in the world in the 21st century.'\n",
|
||||||
"chunker.serialize(chunk) (62 tokens):\n",
|
"chunker.contextualize(chunk) (62 tokens):\n",
|
||||||
"'IBM\\nIBM has concentrated on computer services, software, supercomputers, and scientific research; it sold its microcomputer division to Lenovo in 2005. IBM continues to develop mainframes, and its supercomputers have consistently ranked among the most powerful in the world in the 21st century.'\n",
|
"'IBM\\nIBM has concentrated on computer services, software, supercomputers, and scientific research; it sold its microcomputer division to Lenovo in 2005. IBM continues to develop mainframes, and its supercomputers have consistently ranked among the most powerful in the world in the 21st century.'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 6 ===\n",
|
"=== 6 ===\n",
|
||||||
"chunk.text (62 tokens):\n",
|
"chunk.text (62 tokens):\n",
|
||||||
"\"As one of the world's oldest and largest technology companies, IBM has been responsible for several technological innovations, including the automated teller machine (ATM), dynamic random-access memory (DRAM), the floppy disk, the hard disk drive, the magnetic stripe card, the relational database, the SQL programming\"\n",
|
"\"As one of the world's oldest and largest technology companies, IBM has been responsible for several technological innovations, including the automated teller machine (ATM), dynamic random-access memory (DRAM), the floppy disk, the hard disk drive, the magnetic stripe card, the relational database, the SQL programming\"\n",
|
||||||
"chunker.serialize(chunk) (63 tokens):\n",
|
"chunker.contextualize(chunk) (63 tokens):\n",
|
||||||
"\"IBM\\nAs one of the world's oldest and largest technology companies, IBM has been responsible for several technological innovations, including the automated teller machine (ATM), dynamic random-access memory (DRAM), the floppy disk, the hard disk drive, the magnetic stripe card, the relational database, the SQL programming\"\n",
|
"\"IBM\\nAs one of the world's oldest and largest technology companies, IBM has been responsible for several technological innovations, including the automated teller machine (ATM), dynamic random-access memory (DRAM), the floppy disk, the hard disk drive, the magnetic stripe card, the relational database, the SQL programming\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 7 ===\n",
|
"=== 7 ===\n",
|
||||||
"chunk.text (63 tokens):\n",
|
"chunk.text (63 tokens):\n",
|
||||||
"'language, and the UPC barcode. The company has made inroads in advanced computer chips, quantum computing, artificial intelligence, and data infrastructure.[13][14][15] IBM employees and alumni have won various recognitions for their scientific research and inventions, including six Nobel Prizes and six Turing'\n",
|
"'language, and the UPC barcode. The company has made inroads in advanced computer chips, quantum computing, artificial intelligence, and data infrastructure.[13][14][15] IBM employees and alumni have won various recognitions for their scientific research and inventions, including six Nobel Prizes and six Turing'\n",
|
||||||
"chunker.serialize(chunk) (64 tokens):\n",
|
"chunker.contextualize(chunk) (64 tokens):\n",
|
||||||
"'IBM\\nlanguage, and the UPC barcode. The company has made inroads in advanced computer chips, quantum computing, artificial intelligence, and data infrastructure.[13][14][15] IBM employees and alumni have won various recognitions for their scientific research and inventions, including six Nobel Prizes and six Turing'\n",
|
"'IBM\\nlanguage, and the UPC barcode. The company has made inroads in advanced computer chips, quantum computing, artificial intelligence, and data infrastructure.[13][14][15] IBM employees and alumni have won various recognitions for their scientific research and inventions, including six Nobel Prizes and six Turing'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 8 ===\n",
|
"=== 8 ===\n",
|
||||||
"chunk.text (5 tokens):\n",
|
"chunk.text (5 tokens):\n",
|
||||||
"'Awards.[16]'\n",
|
"'Awards.[16]'\n",
|
||||||
"chunker.serialize(chunk) (6 tokens):\n",
|
"chunker.contextualize(chunk) (6 tokens):\n",
|
||||||
"'IBM\\nAwards.[16]'\n",
|
"'IBM\\nAwards.[16]'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 9 ===\n",
|
"=== 9 ===\n",
|
||||||
"chunk.text (56 tokens):\n",
|
"chunk.text (56 tokens):\n",
|
||||||
"'IBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine'\n",
|
"'IBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine'\n",
|
||||||
"chunker.serialize(chunk) (60 tokens):\n",
|
"chunker.contextualize(chunk) (60 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\nIBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine'\n",
|
"'IBM\\n1910s–1950s\\nIBM originated with several technological innovations developed and commercialized in the late 19th century. Julius E. Pitrap patented the computing scale in 1885;[17] Alexander Dey invented the dial recorder (1888);[18] Herman Hollerith patented the Electric Tabulating Machine'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 10 ===\n",
|
"=== 10 ===\n",
|
||||||
"chunk.text (60 tokens):\n",
|
"chunk.text (60 tokens):\n",
|
||||||
"\"(1889);[19] and Willard Bundy invented a time clock to record workers' arrival and departure times on a paper tape (1889).[20] On June 16, 1911, their four companies were amalgamated in New York State by Charles Ranlett Flint forming a fifth company, the\"\n",
|
"\"(1889);[19] and Willard Bundy invented a time clock to record workers' arrival and departure times on a paper tape (1889).[20] On June 16, 1911, their four companies were amalgamated in New York State by Charles Ranlett Flint forming a fifth company, the\"\n",
|
||||||
"chunker.serialize(chunk) (64 tokens):\n",
|
"chunker.contextualize(chunk) (64 tokens):\n",
|
||||||
"\"IBM\\n1910s–1950s\\n(1889);[19] and Willard Bundy invented a time clock to record workers' arrival and departure times on a paper tape (1889).[20] On June 16, 1911, their four companies were amalgamated in New York State by Charles Ranlett Flint forming a fifth company, the\"\n",
|
"\"IBM\\n1910s–1950s\\n(1889);[19] and Willard Bundy invented a time clock to record workers' arrival and departure times on a paper tape (1889).[20] On June 16, 1911, their four companies were amalgamated in New York State by Charles Ranlett Flint forming a fifth company, the\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 11 ===\n",
|
"=== 11 ===\n",
|
||||||
"chunk.text (59 tokens):\n",
|
"chunk.text (59 tokens):\n",
|
||||||
"'Computing-Tabulating-Recording Company (CTR) based in Endicott, New York.[1][21] The five companies had 1,300 employees and offices and plants in Endicott and Binghamton, New York; Dayton, Ohio; Detroit, Michigan; Washington,'\n",
|
"'Computing-Tabulating-Recording Company (CTR) based in Endicott, New York.[1][21] The five companies had 1,300 employees and offices and plants in Endicott and Binghamton, New York; Dayton, Ohio; Detroit, Michigan; Washington,'\n",
|
||||||
"chunker.serialize(chunk) (63 tokens):\n",
|
"chunker.contextualize(chunk) (63 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\nComputing-Tabulating-Recording Company (CTR) based in Endicott, New York.[1][21] The five companies had 1,300 employees and offices and plants in Endicott and Binghamton, New York; Dayton, Ohio; Detroit, Michigan; Washington,'\n",
|
"'IBM\\n1910s–1950s\\nComputing-Tabulating-Recording Company (CTR) based in Endicott, New York.[1][21] The five companies had 1,300 employees and offices and plants in Endicott and Binghamton, New York; Dayton, Ohio; Detroit, Michigan; Washington,'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 12 ===\n",
|
"=== 12 ===\n",
|
||||||
"chunk.text (13 tokens):\n",
|
"chunk.text (13 tokens):\n",
|
||||||
"'D.C.; and Toronto, Canada.[22]'\n",
|
"'D.C.; and Toronto, Canada.[22]'\n",
|
||||||
"chunker.serialize(chunk) (17 tokens):\n",
|
"chunker.contextualize(chunk) (17 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\nD.C.; and Toronto, Canada.[22]'\n",
|
"'IBM\\n1910s–1950s\\nD.C.; and Toronto, Canada.[22]'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 13 ===\n",
|
"=== 13 ===\n",
|
||||||
"chunk.text (60 tokens):\n",
|
"chunk.text (60 tokens):\n",
|
||||||
"'Collectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson, called'\n",
|
"'Collectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson, called'\n",
|
||||||
"chunker.serialize(chunk) (64 tokens):\n",
|
"chunker.contextualize(chunk) (64 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\nCollectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson, called'\n",
|
"'IBM\\n1910s–1950s\\nCollectively, the companies manufactured a wide array of machinery for sale and lease, ranging from commercial scales and industrial time recorders, meat and cheese slicers, to tabulators and punched cards. Thomas J. Watson, Sr., fired from the National Cash Register Company by John Henry Patterson, called'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 14 ===\n",
|
"=== 14 ===\n",
|
||||||
"chunk.text (59 tokens):\n",
|
"chunk.text (59 tokens):\n",
|
||||||
"\"on Flint and, in 1914, was offered a position at CTR.[23] Watson joined CTR as general manager and then, 11 months later, was made President when antitrust cases relating to his time at NCR were resolved.[24] Having learned Patterson's pioneering business\"\n",
|
"\"on Flint and, in 1914, was offered a position at CTR.[23] Watson joined CTR as general manager and then, 11 months later, was made President when antitrust cases relating to his time at NCR were resolved.[24] Having learned Patterson's pioneering business\"\n",
|
||||||
"chunker.serialize(chunk) (63 tokens):\n",
|
"chunker.contextualize(chunk) (63 tokens):\n",
|
||||||
"\"IBM\\n1910s–1950s\\non Flint and, in 1914, was offered a position at CTR.[23] Watson joined CTR as general manager and then, 11 months later, was made President when antitrust cases relating to his time at NCR were resolved.[24] Having learned Patterson's pioneering business\"\n",
|
"\"IBM\\n1910s–1950s\\non Flint and, in 1914, was offered a position at CTR.[23] Watson joined CTR as general manager and then, 11 months later, was made President when antitrust cases relating to his time at NCR were resolved.[24] Having learned Patterson's pioneering business\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 15 ===\n",
|
"=== 15 ===\n",
|
||||||
"chunk.text (23 tokens):\n",
|
"chunk.text (23 tokens):\n",
|
||||||
"\"practices, Watson proceeded to put the stamp of NCR onto CTR's companies.[23]:\\n105\"\n",
|
"\"practices, Watson proceeded to put the stamp of NCR onto CTR's companies.[23]:\\n105\"\n",
|
||||||
"chunker.serialize(chunk) (27 tokens):\n",
|
"chunker.contextualize(chunk) (27 tokens):\n",
|
||||||
"\"IBM\\n1910s–1950s\\npractices, Watson proceeded to put the stamp of NCR onto CTR's companies.[23]:\\n105\"\n",
|
"\"IBM\\n1910s–1950s\\npractices, Watson proceeded to put the stamp of NCR onto CTR's companies.[23]:\\n105\"\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 16 ===\n",
|
"=== 16 ===\n",
|
||||||
"chunk.text (59 tokens):\n",
|
"chunk.text (59 tokens):\n",
|
||||||
"'He implemented sales conventions, \"generous sales incentives, a focus on customer service, an insistence on well-groomed, dark-suited salesmen and had an evangelical fervor for instilling company pride and loyalty in every worker\".[25][26] His favorite slogan,'\n",
|
"'He implemented sales conventions, \"generous sales incentives, a focus on customer service, an insistence on well-groomed, dark-suited salesmen and had an evangelical fervor for instilling company pride and loyalty in every worker\".[25][26] His favorite slogan,'\n",
|
||||||
"chunker.serialize(chunk) (63 tokens):\n",
|
"chunker.contextualize(chunk) (63 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\nHe implemented sales conventions, \"generous sales incentives, a focus on customer service, an insistence on well-groomed, dark-suited salesmen and had an evangelical fervor for instilling company pride and loyalty in every worker\".[25][26] His favorite slogan,'\n",
|
"'IBM\\n1910s–1950s\\nHe implemented sales conventions, \"generous sales incentives, a focus on customer service, an insistence on well-groomed, dark-suited salesmen and had an evangelical fervor for instilling company pride and loyalty in every worker\".[25][26] His favorite slogan,'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 17 ===\n",
|
"=== 17 ===\n",
|
||||||
"chunk.text (60 tokens):\n",
|
"chunk.text (60 tokens):\n",
|
||||||
"'\"THINK\", became a mantra for each company\\'s employees.[25] During Watson\\'s first four years, revenues reached $9 million ($158 million today) and the company\\'s operations expanded to Europe, South America, Asia and Australia.[25] Watson never liked the'\n",
|
"'\"THINK\", became a mantra for each company\\'s employees.[25] During Watson\\'s first four years, revenues reached $9 million ($158 million today) and the company\\'s operations expanded to Europe, South America, Asia and Australia.[25] Watson never liked the'\n",
|
||||||
"chunker.serialize(chunk) (64 tokens):\n",
|
"chunker.contextualize(chunk) (64 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\n\"THINK\", became a mantra for each company\\'s employees.[25] During Watson\\'s first four years, revenues reached $9 million ($158 million today) and the company\\'s operations expanded to Europe, South America, Asia and Australia.[25] Watson never liked the'\n",
|
"'IBM\\n1910s–1950s\\n\"THINK\", became a mantra for each company\\'s employees.[25] During Watson\\'s first four years, revenues reached $9 million ($158 million today) and the company\\'s operations expanded to Europe, South America, Asia and Australia.[25] Watson never liked the'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 18 ===\n",
|
"=== 18 ===\n",
|
||||||
"chunk.text (57 tokens):\n",
|
"chunk.text (57 tokens):\n",
|
||||||
"'clumsy hyphenated name \"Computing-Tabulating-Recording Company\" and chose to replace it with the more expansive title \"International Business Machines\" which had previously been used as the name of CTR\\'s Canadian Division;[27] the name was changed on February 14,'\n",
|
"'clumsy hyphenated name \"Computing-Tabulating-Recording Company\" and chose to replace it with the more expansive title \"International Business Machines\" which had previously been used as the name of CTR\\'s Canadian Division;[27] the name was changed on February 14,'\n",
|
||||||
"chunker.serialize(chunk) (61 tokens):\n",
|
"chunker.contextualize(chunk) (61 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\nclumsy hyphenated name \"Computing-Tabulating-Recording Company\" and chose to replace it with the more expansive title \"International Business Machines\" which had previously been used as the name of CTR\\'s Canadian Division;[27] the name was changed on February 14,'\n",
|
"'IBM\\n1910s–1950s\\nclumsy hyphenated name \"Computing-Tabulating-Recording Company\" and chose to replace it with the more expansive title \"International Business Machines\" which had previously been used as the name of CTR\\'s Canadian Division;[27] the name was changed on February 14,'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 19 ===\n",
|
"=== 19 ===\n",
|
||||||
"chunk.text (21 tokens):\n",
|
"chunk.text (21 tokens):\n",
|
||||||
"'1924.[28] By 1933, most of the subsidiaries had been merged into one company, IBM.'\n",
|
"'1924.[28] By 1933, most of the subsidiaries had been merged into one company, IBM.'\n",
|
||||||
"chunker.serialize(chunk) (25 tokens):\n",
|
"chunker.contextualize(chunk) (25 tokens):\n",
|
||||||
"'IBM\\n1910s–1950s\\n1924.[28] By 1933, most of the subsidiaries had been merged into one company, IBM.'\n",
|
"'IBM\\n1910s–1950s\\n1924.[28] By 1933, most of the subsidiaries had been merged into one company, IBM.'\n",
|
||||||
"\n",
|
"\n",
|
||||||
"=== 20 ===\n",
|
"=== 20 ===\n",
|
||||||
"chunk.text (22 tokens):\n",
|
"chunk.text (22 tokens):\n",
|
||||||
"'In 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.'\n",
|
"'In 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.'\n",
|
||||||
"chunker.serialize(chunk) (26 tokens):\n",
|
"chunker.contextualize(chunk) (26 tokens):\n",
|
||||||
"'IBM\\n1960s–1980s\\nIn 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.'\n",
|
"'IBM\\n1960s–1980s\\nIn 1961, IBM developed the SABRE reservation system for American Airlines and introduced the highly successful Selectric typewriter.'\n",
|
||||||
"\n"
|
"\n"
|
||||||
]
|
]
|
||||||
@ -352,15 +401,32 @@
|
|||||||
"source": [
|
"source": [
|
||||||
"for i, chunk in enumerate(chunks):\n",
|
"for i, chunk in enumerate(chunks):\n",
|
||||||
" print(f\"=== {i} ===\")\n",
|
" print(f\"=== {i} ===\")\n",
|
||||||
" txt_tokens = len(tokenizer.tokenize(chunk.text))\n",
|
" txt_tokens = tokenizer.count_tokens(chunk.text)\n",
|
||||||
" print(f\"chunk.text ({txt_tokens} tokens):\\n{chunk.text!r}\")\n",
|
" print(f\"chunk.text ({txt_tokens} tokens):\\n{chunk.text!r}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" ser_txt = chunker.serialize(chunk=chunk)\n",
|
" ser_txt = chunker.contextualize(chunk=chunk)\n",
|
||||||
" ser_tokens = len(tokenizer.tokenize(ser_txt))\n",
|
" ser_tokens = tokenizer.count_tokens(ser_txt)\n",
|
||||||
" print(f\"chunker.serialize(chunk) ({ser_tokens} tokens):\\n{ser_txt!r}\")\n",
|
" print(f\"chunker.contextualize(chunk) ({ser_tokens} tokens):\\n{ser_txt!r}\")\n",
|
||||||
"\n",
|
"\n",
|
||||||
" print()"
|
" print()"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Configuring serialization"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can additionally customize the serialization strategy via a user-provided\n",
|
||||||
|
"[serializer provider](../../concepts/serialization).\n",
|
||||||
|
"\n",
|
||||||
|
"For usage examples check out [this notebook](https://github.com/docling-project/docling-core/blob/main/examples/chunking_and_serialization.ipynb)."
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"metadata": {
|
"metadata": {
|
||||||
@ -379,7 +445,7 @@
|
|||||||
"name": "python",
|
"name": "python",
|
||||||
"nbconvert_exporter": "python",
|
"nbconvert_exporter": "python",
|
||||||
"pygments_lexer": "ipython3",
|
"pygments_lexer": "ipython3",
|
||||||
"version": "3.12.7"
|
"version": "3.13.2"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"nbformat": 4,
|
"nbformat": 4,
|
||||||
|
@ -80,7 +80,7 @@ for source in sources:
|
|||||||
fp.write(json.dumps(res.document.export_to_dict()))
|
fp.write(json.dumps(res.document.export_to_dict()))
|
||||||
|
|
||||||
res.document.save_as_json(
|
res.document.save_as_json(
|
||||||
out_path / f"{res.input.file.stem}.md",
|
out_path / f"{res.input.file.stem}.json",
|
||||||
image_mode=ImageRefMode.PLACEHOLDER,
|
image_mode=ImageRefMode.PLACEHOLDER,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -279,7 +279,7 @@
|
|||||||
"## Use other vision models\n",
|
"## Use other vision models\n",
|
||||||
"\n",
|
"\n",
|
||||||
"The examples above can also be reproduced using other vision model.\n",
|
"The examples above can also be reproduced using other vision model.\n",
|
||||||
"The Docling options `PictureDescriptionVlmOptions` allows to speficy your favorite vision model from the Hugging Face Hub."
|
"The Docling options `PictureDescriptionVlmOptions` allows to specify your favorite vision model from the Hugging Face Hub."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
551
docs/examples/rag_milvus.ipynb
Normal file
551
docs/examples/rag_milvus.ipynb
Normal file
@ -0,0 +1,551 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"<a href=\"https://colab.research.google.com/github/docling-project/docling/blob/main/docs/examples/rag_milvus.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# RAG with Milvus\n",
|
||||||
|
"\n",
|
||||||
|
"| Step | Tech | Execution |\n",
|
||||||
|
"| --- | --- | --- |\n",
|
||||||
|
"| Embedding | OpenAI (text-embedding-3-small) | 🌐 Remote |\n",
|
||||||
|
"| Vector store | Milvus | 💻 Local |\n",
|
||||||
|
"| Gen AI | OpenAI (gpt-4o) | 🌐 Remote |\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"## A recipe 🧑🍳 🐥 💚\n",
|
||||||
|
"\n",
|
||||||
|
"This is a code recipe that uses [Milvus](https://milvus.io/), the world's most advanced open-source vector database, to perform RAG over documents parsed by [Docling](https://docling-project.github.io/docling/).\n",
|
||||||
|
"\n",
|
||||||
|
"In this notebook, we accomplish the following:\n",
|
||||||
|
"* Parse documents using Docling's document conversion capabilities\n",
|
||||||
|
"* Perform hierarchical chunking of the documents using Docling\n",
|
||||||
|
"* Generate text embeddings with OpenAI\n",
|
||||||
|
"* Perform RAG using Milvus, the world's most advanced open-source vector database\n",
|
||||||
|
"\n",
|
||||||
|
"Note: For best results, please use **GPU acceleration** to run this notebook. Here are two options for running this notebook:\n",
|
||||||
|
"1. **Locally on a MacBook with an Apple Silicon chip.** Converting all documents in the notebook takes ~2 minutes on a MacBook M2 due to Docling's usage of MPS accelerators.\n",
|
||||||
|
"2. **Run this notebook on Google Colab.** Converting all documents in the notebook takes ~8 minutes on a Google Colab T4 GPU.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Preparation\n",
|
||||||
|
"\n",
|
||||||
|
"### Dependencies and Environment\n",
|
||||||
|
"\n",
|
||||||
|
"To start, install the required dependencies by running the following command:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": null,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"! pip install --upgrade pymilvus docling openai torch"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"> If you are using Google Colab, to enable dependencies just installed, you may need to **restart the runtime** (click on the \"Runtime\" menu at the top of the screen, and select \"Restart session\" from the dropdown menu)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### GPU Checking"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Part of what makes Docling so remarkable is the fact that it can run on commodity hardware. This means that this notebook can be run on a local machine with GPU acceleration. If you're using a MacBook with a silicon chip, Docling integrates seamlessly with Metal Performance Shaders (MPS). MPS provides out-of-the-box GPU acceleration for macOS, seamlessly integrating with PyTorch and TensorFlow, offering energy-efficient performance on Apple Silicon, and broad compatibility with all Metal-supported GPUs.\n",
|
||||||
|
"\n",
|
||||||
|
"The code below checks to see if a GPU is available, either via CUDA or MPS."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"MPS GPU is enabled.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import torch\n",
|
||||||
|
"\n",
|
||||||
|
"# Check if GPU or MPS is available\n",
|
||||||
|
"if torch.cuda.is_available():\n",
|
||||||
|
" device = torch.device(\"cuda\")\n",
|
||||||
|
" print(f\"CUDA GPU is enabled: {torch.cuda.get_device_name(0)}\")\n",
|
||||||
|
"elif torch.backends.mps.is_available():\n",
|
||||||
|
" device = torch.device(\"mps\")\n",
|
||||||
|
" print(\"MPS GPU is enabled.\")\n",
|
||||||
|
"else:\n",
|
||||||
|
" raise OSError(\n",
|
||||||
|
" \"No GPU or MPS device found. Please check your environment and ensure GPU or MPS support is configured.\"\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Setting Up API Keys\n",
|
||||||
|
"\n",
|
||||||
|
"We will use OpenAI as the LLM in this example. You should prepare the [OPENAI_API_KEY](https://platform.openai.com/docs/quickstart) as an environment variable."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"import os\n",
|
||||||
|
"\n",
|
||||||
|
"os.environ[\"OPENAI_API_KEY\"] = \"sk-***********\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Prepare the LLM and Embedding Model\n",
|
||||||
|
"\n",
|
||||||
|
"We initialize the OpenAI client to prepare the embedding model.\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from openai import OpenAI\n",
|
||||||
|
"\n",
|
||||||
|
"openai_client = OpenAI()"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Define a function to generate text embeddings using OpenAI client. We use the [text-embedding-3-small](https://platform.openai.com/docs/guides/embeddings) model as an example."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"def emb_text(text):\n",
|
||||||
|
" return (\n",
|
||||||
|
" openai_client.embeddings.create(input=text, model=\"text-embedding-3-small\")\n",
|
||||||
|
" .data[0]\n",
|
||||||
|
" .embedding\n",
|
||||||
|
" )"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Generate a test embedding and print its dimension and first few elements."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"1536\n",
|
||||||
|
"[0.009889289736747742, -0.005578675772994757, 0.00683477520942688, -0.03805781528353691, -0.01824733428657055, -0.04121600463986397, -0.007636285852640867, 0.03225184231996536, 0.018949154764413834, 9.352207416668534e-05]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"test_embedding = emb_text(\"This is a test\")\n",
|
||||||
|
"embedding_dim = len(test_embedding)\n",
|
||||||
|
"print(embedding_dim)\n",
|
||||||
|
"print(test_embedding[:10])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Process Data Using Docling\n",
|
||||||
|
"\n",
|
||||||
|
"Docling can parse various document formats into a unified representation (Docling Document), which can then be exported to different output formats. For a full list of supported input and output formats, please refer to [the official documentation](https://docling-project.github.io/docling/usage/supported_formats/).\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In this tutorial, we will use a Markdown file ([source](https://milvus.io/docs/overview.md)) as the input. We will process the document using a **HierarchicalChunker** provided by Docling to generate structured, hierarchical chunks suitable for downstream RAG tasks."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from docling_core.transforms.chunker import HierarchicalChunker\n",
|
||||||
|
"\n",
|
||||||
|
"from docling.document_converter import DocumentConverter\n",
|
||||||
|
"\n",
|
||||||
|
"converter = DocumentConverter()\n",
|
||||||
|
"chunker = HierarchicalChunker()\n",
|
||||||
|
"\n",
|
||||||
|
"# Convert the input file to Docling Document\n",
|
||||||
|
"source = \"https://milvus.io/docs/overview.md\"\n",
|
||||||
|
"doc = converter.convert(source).document\n",
|
||||||
|
"\n",
|
||||||
|
"# Perform hierarchical chunking\n",
|
||||||
|
"texts = [chunk.text for chunk in chunker.chunk(doc)]"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Load Data into Milvus\n",
|
||||||
|
"\n",
|
||||||
|
"### Create the collection\n",
|
||||||
|
"\n",
|
||||||
|
"With data in hand, we can create a `MilvusClient` instance and insert the data into a Milvus collection. "
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from pymilvus import MilvusClient\n",
|
||||||
|
"\n",
|
||||||
|
"milvus_client = MilvusClient(uri=\"./milvus_demo.db\")\n",
|
||||||
|
"collection_name = \"my_rag_collection\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"> As for the argument of `MilvusClient`:\n",
|
||||||
|
"> - Setting the `uri` as a local file, e.g.`./milvus.db`, is the most convenient method, as it automatically utilizes [Milvus Lite](https://milvus.io/docs/milvus_lite.md) to store all data in this file.\n",
|
||||||
|
"> - If you have large scale of data, you can set up a more performant Milvus server on [docker or kubernetes](https://milvus.io/docs/quickstart.md). In this setup, please use the server uri, e.g.`http://localhost:19530`, as your `uri`.\n",
|
||||||
|
"> - If you want to use [Zilliz Cloud](https://zilliz.com/cloud), the fully managed cloud service for Milvus, adjust the `uri` and `token`, which correspond to the [Public Endpoint and Api key](https://docs.zilliz.com/docs/on-zilliz-cloud-console#free-cluster-details) in Zilliz Cloud."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Check if the collection already exists and drop it if it does."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"if milvus_client.has_collection(collection_name):\n",
|
||||||
|
" milvus_client.drop_collection(collection_name)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Create a new collection with specified parameters.\n",
|
||||||
|
"\n",
|
||||||
|
"If we don’t specify any field information, Milvus will automatically create a default `id` field for primary key, and a `vector` field to store the vector data. A reserved JSON field is used to store non-schema-defined fields and their values."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"milvus_client.create_collection(\n",
|
||||||
|
" collection_name=collection_name,\n",
|
||||||
|
" dimension=embedding_dim,\n",
|
||||||
|
" metric_type=\"IP\", # Inner product distance\n",
|
||||||
|
" consistency_level=\"Strong\", # Supported values are (`\"Strong\"`, `\"Session\"`, `\"Bounded\"`, `\"Eventually\"`). See https://milvus.io/docs/consistency.md#Consistency-Level for more details.\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Insert data"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stderr",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Processing chunks: 100%|██████████| 38/38 [00:14<00:00, 2.59it/s]\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/plain": [
|
||||||
|
"{'insert_count': 38, 'ids': [0, 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], 'cost': 0}"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "execute_result"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"from tqdm import tqdm\n",
|
||||||
|
"\n",
|
||||||
|
"data = []\n",
|
||||||
|
"\n",
|
||||||
|
"for i, chunk in enumerate(tqdm(texts, desc=\"Processing chunks\")):\n",
|
||||||
|
" embedding = emb_text(chunk)\n",
|
||||||
|
" data.append({\"id\": i, \"vector\": embedding, \"text\": chunk})\n",
|
||||||
|
"\n",
|
||||||
|
"milvus_client.insert(collection_name=collection_name, data=data)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Build RAG"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Retrieve data for a query\n",
|
||||||
|
"\n",
|
||||||
|
"Let’s specify a query question about the website we just scraped."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 11,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"question = (\n",
|
||||||
|
" \"What are the three deployment modes of Milvus, and what are their differences?\"\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Search for the question in the collection and retrieve the semantic top-3 matches."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 12,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"search_res = milvus_client.search(\n",
|
||||||
|
" collection_name=collection_name,\n",
|
||||||
|
" data=[emb_text(question)],\n",
|
||||||
|
" limit=3,\n",
|
||||||
|
" search_params={\"metric_type\": \"IP\", \"params\": {}},\n",
|
||||||
|
" output_fields=[\"text\"],\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let’s take a look at the search results of the query\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 13,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"[\n",
|
||||||
|
" [\n",
|
||||||
|
" \"Milvus offers three deployment modes, covering a wide range of data scales\\u2014from local prototyping in Jupyter Notebooks to massive Kubernetes clusters managing tens of billions of vectors:\",\n",
|
||||||
|
" 0.6503315567970276\n",
|
||||||
|
" ],\n",
|
||||||
|
" [\n",
|
||||||
|
" \"Milvus Lite is a Python library that can be easily integrated into your applications. As a lightweight version of Milvus, it\\u2019s ideal for quick prototyping in Jupyter Notebooks or running on edge devices with limited resources. Learn more.\\nMilvus Standalone is a single-machine server deployment, with all components bundled into a single Docker image for convenient deployment. Learn more.\\nMilvus Distributed can be deployed on Kubernetes clusters, featuring a cloud-native architecture designed for billion-scale or even larger scenarios. This architecture ensures redundancy in critical components. Learn more.\",\n",
|
||||||
|
" 0.6281915903091431\n",
|
||||||
|
" ],\n",
|
||||||
|
" [\n",
|
||||||
|
" \"What is Milvus?\\nUnstructured Data, Embeddings, and Milvus\\nWhat Makes Milvus so Fast\\uff1f\\nWhat Makes Milvus so Scalable\\nTypes of Searches Supported by Milvus\\nComprehensive Feature Set\",\n",
|
||||||
|
" 0.6117826700210571\n",
|
||||||
|
" ]\n",
|
||||||
|
"]\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"import json\n",
|
||||||
|
"\n",
|
||||||
|
"retrieved_lines_with_distances = [\n",
|
||||||
|
" (res[\"entity\"][\"text\"], res[\"distance\"]) for res in search_res[0]\n",
|
||||||
|
"]\n",
|
||||||
|
"print(json.dumps(retrieved_lines_with_distances, indent=4))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"### Use LLM to get a RAG response\n",
|
||||||
|
"\n",
|
||||||
|
"Convert the retrieved documents into a string format.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 14,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"context = \"\\n\".join(\n",
|
||||||
|
" [line_with_distance[0] for line_with_distance in retrieved_lines_with_distances]\n",
|
||||||
|
")"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Define system and user prompts for the Lanage Model. This prompt is assembled with the retrieved documents from Milvus.\n",
|
||||||
|
"\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 16,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"SYSTEM_PROMPT = \"\"\"\n",
|
||||||
|
"Human: You are an AI assistant. You are able to find answers to the questions from the contextual passage snippets provided.\n",
|
||||||
|
"\"\"\"\n",
|
||||||
|
"USER_PROMPT = f\"\"\"\n",
|
||||||
|
"Use the following pieces of information enclosed in <context> tags to provide an answer to the question enclosed in <question> tags.\n",
|
||||||
|
"<context>\n",
|
||||||
|
"{context}\n",
|
||||||
|
"</context>\n",
|
||||||
|
"<question>\n",
|
||||||
|
"{question}\n",
|
||||||
|
"</question>\n",
|
||||||
|
"\"\"\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Use OpenAI ChatGPT to generate a response based on the prompts."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 17,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"The three deployment modes of Milvus are:\n",
|
||||||
|
"\n",
|
||||||
|
"1. **Milvus Lite**: This is a Python library that integrates easily into your applications. It's a lightweight version ideal for quick prototyping in Jupyter Notebooks or for running on edge devices with limited resources.\n",
|
||||||
|
"\n",
|
||||||
|
"2. **Milvus Standalone**: This mode is a single-machine server deployment where all components are bundled into a single Docker image, making it convenient to deploy.\n",
|
||||||
|
"\n",
|
||||||
|
"3. **Milvus Distributed**: This mode is designed for deployment on Kubernetes clusters. It features a cloud-native architecture suited for managing scenarios at a billion-scale or larger, ensuring redundancy in critical components.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"response = openai_client.chat.completions.create(\n",
|
||||||
|
" model=\"gpt-4o\",\n",
|
||||||
|
" messages=[\n",
|
||||||
|
" {\"role\": \"system\", \"content\": SYSTEM_PROMPT},\n",
|
||||||
|
" {\"role\": \"user\", \"content\": USER_PROMPT},\n",
|
||||||
|
" ],\n",
|
||||||
|
")\n",
|
||||||
|
"print(response.choices[0].message.content)"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": "base",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.11.5"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
@ -43,7 +43,7 @@
|
|||||||
"\n",
|
"\n",
|
||||||
"Note: For best results, please use **GPU acceleration** to run this notebook. Here are two options for running this notebook:\n",
|
"Note: For best results, please use **GPU acceleration** to run this notebook. Here are two options for running this notebook:\n",
|
||||||
"1. **Locally on a MacBook with an Apple Silicon chip.** Converting all documents in the notebook takes ~2 minutes on a MacBook M2 due to Docling's usage of MPS accelerators.\n",
|
"1. **Locally on a MacBook with an Apple Silicon chip.** Converting all documents in the notebook takes ~2 minutes on a MacBook M2 due to Docling's usage of MPS accelerators.\n",
|
||||||
"2. **Run this notebook on Google Colab.** Converting all documents in the notebook takes ~8 mintutes on a Google Colab T4 GPU."
|
"2. **Run this notebook on Google Colab.** Converting all documents in the notebook takes ~8 minutes on a Google Colab T4 GPU."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@ -716,7 +716,7 @@
|
|||||||
"id": "7tGz49nfUegG"
|
"id": "7tGz49nfUegG"
|
||||||
},
|
},
|
||||||
"source": [
|
"source": [
|
||||||
"We can see that our RAG pipeline performs relatively well for simple queries, especially given the small size of the dataset. Scaling this method for converting a larger sample of PDFs would require more compute (GPUs) and a more advanced deployment of Weaviate (like Docker, Kubernetes, or Weaviate Cloud). For more information on available Weaviate configurations, check out the [documetation](https://weaviate.io/developers/weaviate/starter-guides/which-weaviate)."
|
"We can see that our RAG pipeline performs relatively well for simple queries, especially given the small size of the dataset. Scaling this method for converting a larger sample of PDFs would require more compute (GPUs) and a more advanced deployment of Weaviate (like Docker, Kubernetes, or Weaviate Cloud). For more information on available Weaviate configurations, check out the [documentation](https://weaviate.io/developers/weaviate/starter-guides/which-weaviate)."
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
|
665
docs/examples/serialization.ipynb
Normal file
665
docs/examples/serialization.ipynb
Normal file
@ -0,0 +1,665 @@
|
|||||||
|
{
|
||||||
|
"cells": [
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"# Serialization"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Overview"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In this notebook we showcase the usage of Docling [serializers](../../concepts/serialization)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Setup"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 1,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stdout",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"Note: you may need to restart the kernel to use updated packages.\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"%pip install -qU pip docling docling-core~=2.29 rich"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 2,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"DOC_SOURCE = \"https://arxiv.org/pdf/2311.18481\"\n",
|
||||||
|
"\n",
|
||||||
|
"# we set some start-stop cues for defining an excerpt to print\n",
|
||||||
|
"start_cue = \"Copyright © 2024\"\n",
|
||||||
|
"stop_cue = \"Application of NLP to ESG\""
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 3,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from rich.console import Console\n",
|
||||||
|
"from rich.panel import Panel\n",
|
||||||
|
"\n",
|
||||||
|
"console = Console(width=210) # for preventing Markdown table wrapped rendering\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"def print_in_console(text):\n",
|
||||||
|
" console.print(Panel(text))"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Basic usage"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We first convert the document:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 4,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stderr",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"/Users/pva/work/github.com/DS4SD/docling/.venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:683: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, then device pinned memory won't be used.\n",
|
||||||
|
" warnings.warn(warn_msg)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"from docling.document_converter import DocumentConverter\n",
|
||||||
|
"\n",
|
||||||
|
"converter = DocumentConverter()\n",
|
||||||
|
"doc = converter.convert(source=DOC_SOURCE).document"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can now apply any `BaseDocSerializer` on the produced document.\n",
|
||||||
|
"\n",
|
||||||
|
"👉 Note that, to keep the shown output brief, we only print an excerpt.\n",
|
||||||
|
"\n",
|
||||||
|
"E.g. below we apply an `HTMLDocSerializer`:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 5,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/html": [
|
||||||
|
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.</p> │\n",
|
||||||
|
"│ <table><tbody><tr><th>Report</th><th>Question</th><th>Answer</th></tr><tr><td>IBM 2022</td><td>How many hours were spent on employee learning in 2021?</td><td>22.5 million hours</td></tr><tr><td>IBM │\n",
|
||||||
|
"│ 2022</td><td>What was the rate of fatalities in 2021?</td><td>The rate of fatalities in 2021 was 0.0016.</td></tr><tr><td>IBM 2022</td><td>How many full audits were con- ducted in 2022 in │\n",
|
||||||
|
"│ India?</td><td>2</td></tr><tr><td>Starbucks 2022</td><td>What is the percentage of women in the Board of Directors?</td><td>25%</td></tr><tr><td>Starbucks 2022</td><td>What was the total energy con- │\n",
|
||||||
|
"│ sumption in 2021?</td><td>According to the table, the total energy consumption in 2021 was 2,491,543 MWh.</td></tr><tr><td>Starbucks 2022</td><td>How much packaging material was made from renewable mate- │\n",
|
||||||
|
"│ rials?</td><td>According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22.</td></tr></tbody></table> │\n",
|
||||||
|
"│ <p>Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.</p> │\n",
|
||||||
|
"│ <p>ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response.</p> │\n",
|
||||||
|
"│ <h2>Related Work</h2> │\n",
|
||||||
|
"│ <p>The DocQA integrates multiple AI technologies, namely:</p> │\n",
|
||||||
|
"│ <p>Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric │\n",
|
||||||
|
"│ layout analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et │\n",
|
||||||
|
"│ al. 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-</p> │\n",
|
||||||
|
"│ <figure><figcaption>Figure 1: System architecture: Simplified sketch of document question-answering pipeline.</figcaption></figure> │\n",
|
||||||
|
"│ <p>based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).</p> │\n",
|
||||||
|
"│ <p> │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
|
||||||
|
"</pre>\n"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
"╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved.</p> │\n",
|
||||||
|
"│ <table><tbody><tr><th>Report</th><th>Question</th><th>Answer</th></tr><tr><td>IBM 2022</td><td>How many hours were spent on employee learning in 2021?</td><td>22.5 million hours</td></tr><tr><td>IBM │\n",
|
||||||
|
"│ 2022</td><td>What was the rate of fatalities in 2021?</td><td>The rate of fatalities in 2021 was 0.0016.</td></tr><tr><td>IBM 2022</td><td>How many full audits were con- ducted in 2022 in │\n",
|
||||||
|
"│ India?</td><td>2</td></tr><tr><td>Starbucks 2022</td><td>What is the percentage of women in the Board of Directors?</td><td>25%</td></tr><tr><td>Starbucks 2022</td><td>What was the total energy con- │\n",
|
||||||
|
"│ sumption in 2021?</td><td>According to the table, the total energy consumption in 2021 was 2,491,543 MWh.</td></tr><tr><td>Starbucks 2022</td><td>How much packaging material was made from renewable mate- │\n",
|
||||||
|
"│ rials?</td><td>According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22.</td></tr></tbody></table> │\n",
|
||||||
|
"│ <p>Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system.</p> │\n",
|
||||||
|
"│ <p>ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response.</p> │\n",
|
||||||
|
"│ <h2>Related Work</h2> │\n",
|
||||||
|
"│ <p>The DocQA integrates multiple AI technologies, namely:</p> │\n",
|
||||||
|
"│ <p>Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric │\n",
|
||||||
|
"│ layout analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et │\n",
|
||||||
|
"│ al. 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning-</p> │\n",
|
||||||
|
"│ <figure><figcaption>Figure 1: System architecture: Simplified sketch of document question-answering pipeline.</figcaption></figure> │\n",
|
||||||
|
"│ <p>based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018).</p> │\n",
|
||||||
|
"│ <p> │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"from docling_core.transforms.serializer.html import HTMLDocSerializer\n",
|
||||||
|
"\n",
|
||||||
|
"serializer = HTMLDocSerializer(doc=doc)\n",
|
||||||
|
"ser_result = serializer.serialize()\n",
|
||||||
|
"ser_text = ser_result.text\n",
|
||||||
|
"\n",
|
||||||
|
"# we here only print an excerpt to keep the output brief:\n",
|
||||||
|
"print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In the following example, we use a `MarkdownDocSerializer`:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 6,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/html": [
|
||||||
|
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ | Report | Question | Answer | │\n",
|
||||||
|
"│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| │\n",
|
||||||
|
"│ | IBM 2022 | How many hours were spent on employee learning in 2021? | 22.5 million hours | │\n",
|
||||||
|
"│ | IBM 2022 | What was the rate of fatalities in 2021? | The rate of fatalities in 2021 was 0.0016. | │\n",
|
||||||
|
"│ | IBM 2022 | How many full audits were con- ducted in 2022 in India? | 2 | │\n",
|
||||||
|
"│ | Starbucks 2022 | What is the percentage of women in the Board of Directors? | 25% | │\n",
|
||||||
|
"│ | Starbucks 2022 | What was the total energy con- sumption in 2021? | According to the table, the total energy consumption in 2021 was 2,491,543 MWh. | │\n",
|
||||||
|
"│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. | │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ## Related Work │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ The DocQA integrates multiple AI technologies, namely: │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
|
||||||
|
"│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al. │\n",
|
||||||
|
"│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning- │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ <!-- image --> │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018). │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
|
||||||
|
"</pre>\n"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
"╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ | Report | Question | Answer | │\n",
|
||||||
|
"│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| │\n",
|
||||||
|
"│ | IBM 2022 | How many hours were spent on employee learning in 2021? | 22.5 million hours | │\n",
|
||||||
|
"│ | IBM 2022 | What was the rate of fatalities in 2021? | The rate of fatalities in 2021 was 0.0016. | │\n",
|
||||||
|
"│ | IBM 2022 | How many full audits were con- ducted in 2022 in India? | 2 | │\n",
|
||||||
|
"│ | Starbucks 2022 | What is the percentage of women in the Board of Directors? | 25% | │\n",
|
||||||
|
"│ | Starbucks 2022 | What was the total energy con- sumption in 2021? | According to the table, the total energy consumption in 2021 was 2,491,543 MWh. | │\n",
|
||||||
|
"│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. | │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ## Related Work │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ The DocQA integrates multiple AI technologies, namely: │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
|
||||||
|
"│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al. │\n",
|
||||||
|
"│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning- │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ <!-- image --> │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018). │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"from docling_core.transforms.serializer.markdown import MarkdownDocSerializer\n",
|
||||||
|
"\n",
|
||||||
|
"serializer = MarkdownDocSerializer(doc=doc)\n",
|
||||||
|
"ser_result = serializer.serialize()\n",
|
||||||
|
"ser_text = ser_result.text\n",
|
||||||
|
"\n",
|
||||||
|
"print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Configuring a serializer"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Let's now assume we would like to reconfigure the Markdown serialization such that:\n",
|
||||||
|
"- it uses a different component serializer, e.g. if we'd prefer tables to be printed in a triplet format (which could potentially improve the vector representation compared to Markdown tables)\n",
|
||||||
|
"- it uses specific user-defined parameters, e.g. if we'd prefer a different image placeholder text than the default one\n",
|
||||||
|
"\n",
|
||||||
|
"Check out the following configuration and notice the serialization differences in the output further below:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 7,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/html": [
|
||||||
|
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ IBM 2022, Question = How many hours were spent on employee learning in 2021?. IBM 2022, Answer = 22.5 million hours. IBM 2022, Question = What was the rate of fatalities in 2021?. IBM 2022, Answer = The │\n",
|
||||||
|
"│ rate of fatalities in 2021 was 0.0016.. IBM 2022, Question = How many full audits were con- ducted in 2022 in India?. IBM 2022, Answer = 2. Starbucks 2022, Question = What is the percentage of women in the │\n",
|
||||||
|
"│ Board of Directors?. Starbucks 2022, Answer = 25%. Starbucks 2022, Question = What was the total energy con- sumption in 2021?. Starbucks 2022, Answer = According to the table, the total energy consumption │\n",
|
||||||
|
"│ in 2021 was 2,491,543 MWh.. Starbucks 2022, Question = How much packaging material was made from renewable mate- rials?. Starbucks 2022, Answer = According to the given data, 31% of packaging materials were │\n",
|
||||||
|
"│ made from recycled or renewable materials in FY22. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ## Related Work │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ The DocQA integrates multiple AI technologies, namely: │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
|
||||||
|
"│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al. │\n",
|
||||||
|
"│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning- │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ <!-- demo picture placeholder --> │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018). │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
|
||||||
|
"</pre>\n"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
"╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ IBM 2022, Question = How many hours were spent on employee learning in 2021?. IBM 2022, Answer = 22.5 million hours. IBM 2022, Question = What was the rate of fatalities in 2021?. IBM 2022, Answer = The │\n",
|
||||||
|
"│ rate of fatalities in 2021 was 0.0016.. IBM 2022, Question = How many full audits were con- ducted in 2022 in India?. IBM 2022, Answer = 2. Starbucks 2022, Question = What is the percentage of women in the │\n",
|
||||||
|
"│ Board of Directors?. Starbucks 2022, Answer = 25%. Starbucks 2022, Question = What was the total energy con- sumption in 2021?. Starbucks 2022, Answer = According to the table, the total energy consumption │\n",
|
||||||
|
"│ in 2021 was 2,491,543 MWh.. Starbucks 2022, Question = How much packaging material was made from renewable mate- rials?. Starbucks 2022, Answer = According to the given data, 31% of packaging materials were │\n",
|
||||||
|
"│ made from recycled or renewable materials in FY22. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ## Related Work │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ The DocQA integrates multiple AI technologies, namely: │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
|
||||||
|
"│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al. │\n",
|
||||||
|
"│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning- │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ <!-- demo picture placeholder --> │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018). │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"from docling_core.transforms.chunker.hierarchical_chunker import TripletTableSerializer\n",
|
||||||
|
"from docling_core.transforms.serializer.markdown import MarkdownParams\n",
|
||||||
|
"\n",
|
||||||
|
"serializer = MarkdownDocSerializer(\n",
|
||||||
|
" doc=doc,\n",
|
||||||
|
" table_serializer=TripletTableSerializer(),\n",
|
||||||
|
" params=MarkdownParams(\n",
|
||||||
|
" image_placeholder=\"<!-- demo picture placeholder -->\",\n",
|
||||||
|
" # ...\n",
|
||||||
|
" ),\n",
|
||||||
|
")\n",
|
||||||
|
"ser_result = serializer.serialize()\n",
|
||||||
|
"ser_text = ser_result.text\n",
|
||||||
|
"\n",
|
||||||
|
"print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"## Creating a custom serializer"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"In the examples above, we were able to reuse existing implementations for our desired\n",
|
||||||
|
"serialization strategy, but let's now assume we want to define a custom serialization\n",
|
||||||
|
"logic, e.g. we would like picture serialization to include any available picture\n",
|
||||||
|
"description (captioning) annotations.\n",
|
||||||
|
"\n",
|
||||||
|
"To that end, we first need to revisit our conversion and include all pipeline options\n",
|
||||||
|
"needed for\n",
|
||||||
|
"[picture description enrichment](https://docling-project.github.io/docling/usage/enrichments/#picture-description)."
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 8,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"name": "stderr",
|
||||||
|
"output_type": "stream",
|
||||||
|
"text": [
|
||||||
|
"/Users/pva/work/github.com/DS4SD/docling/.venv/lib/python3.13/site-packages/torch/utils/data/dataloader.py:683: UserWarning: 'pin_memory' argument is set as true but not supported on MPS now, then device pinned memory won't be used.\n",
|
||||||
|
" warnings.warn(warn_msg)\n"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"from docling.datamodel.base_models import InputFormat\n",
|
||||||
|
"from docling.datamodel.pipeline_options import (\n",
|
||||||
|
" PdfPipelineOptions,\n",
|
||||||
|
" PictureDescriptionVlmOptions,\n",
|
||||||
|
")\n",
|
||||||
|
"from docling.document_converter import DocumentConverter, PdfFormatOption\n",
|
||||||
|
"\n",
|
||||||
|
"pipeline_options = PdfPipelineOptions(\n",
|
||||||
|
" do_picture_description=True,\n",
|
||||||
|
" picture_description_options=PictureDescriptionVlmOptions(\n",
|
||||||
|
" repo_id=\"HuggingFaceTB/SmolVLM-256M-Instruct\",\n",
|
||||||
|
" prompt=\"Describe this picture in three to five sentences. Be precise and concise.\",\n",
|
||||||
|
" ),\n",
|
||||||
|
" generate_picture_images=True,\n",
|
||||||
|
" images_scale=2,\n",
|
||||||
|
")\n",
|
||||||
|
"\n",
|
||||||
|
"converter = DocumentConverter(\n",
|
||||||
|
" format_options={InputFormat.PDF: PdfFormatOption(pipeline_options=pipeline_options)}\n",
|
||||||
|
")\n",
|
||||||
|
"doc = converter.convert(source=DOC_SOURCE).document"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"We can then define our custom picture serializer:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 9,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [],
|
||||||
|
"source": [
|
||||||
|
"from typing import Any, Optional\n",
|
||||||
|
"\n",
|
||||||
|
"from docling_core.transforms.serializer.base import (\n",
|
||||||
|
" BaseDocSerializer,\n",
|
||||||
|
" SerializationResult,\n",
|
||||||
|
")\n",
|
||||||
|
"from docling_core.transforms.serializer.common import create_ser_result\n",
|
||||||
|
"from docling_core.transforms.serializer.markdown import (\n",
|
||||||
|
" MarkdownParams,\n",
|
||||||
|
" MarkdownPictureSerializer,\n",
|
||||||
|
")\n",
|
||||||
|
"from docling_core.types.doc.document import (\n",
|
||||||
|
" DoclingDocument,\n",
|
||||||
|
" ImageRefMode,\n",
|
||||||
|
" PictureDescriptionData,\n",
|
||||||
|
" PictureItem,\n",
|
||||||
|
")\n",
|
||||||
|
"from typing_extensions import override\n",
|
||||||
|
"\n",
|
||||||
|
"\n",
|
||||||
|
"class AnnotationPictureSerializer(MarkdownPictureSerializer):\n",
|
||||||
|
" @override\n",
|
||||||
|
" def serialize(\n",
|
||||||
|
" self,\n",
|
||||||
|
" *,\n",
|
||||||
|
" item: PictureItem,\n",
|
||||||
|
" doc_serializer: BaseDocSerializer,\n",
|
||||||
|
" doc: DoclingDocument,\n",
|
||||||
|
" separator: Optional[str] = None,\n",
|
||||||
|
" **kwargs: Any,\n",
|
||||||
|
" ) -> SerializationResult:\n",
|
||||||
|
" text_parts: list[str] = []\n",
|
||||||
|
"\n",
|
||||||
|
" # reusing the existing result:\n",
|
||||||
|
" parent_res = super().serialize(\n",
|
||||||
|
" item=item,\n",
|
||||||
|
" doc_serializer=doc_serializer,\n",
|
||||||
|
" doc=doc,\n",
|
||||||
|
" **kwargs,\n",
|
||||||
|
" )\n",
|
||||||
|
" text_parts.append(parent_res.text)\n",
|
||||||
|
"\n",
|
||||||
|
" # appending annotations:\n",
|
||||||
|
" for annotation in item.annotations:\n",
|
||||||
|
" if isinstance(annotation, PictureDescriptionData):\n",
|
||||||
|
" text_parts.append(f\"<!-- Picture description: {annotation.text} -->\")\n",
|
||||||
|
"\n",
|
||||||
|
" text_res = (separator or \"\\n\").join(text_parts)\n",
|
||||||
|
" return create_ser_result(text=text_res, span_source=item)"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "markdown",
|
||||||
|
"metadata": {},
|
||||||
|
"source": [
|
||||||
|
"Last but not least, we define a new doc serializer which leverages our custom picture\n",
|
||||||
|
"serializer.\n",
|
||||||
|
"\n",
|
||||||
|
"Notice the picture description annotations in the output below:"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"cell_type": "code",
|
||||||
|
"execution_count": 10,
|
||||||
|
"metadata": {},
|
||||||
|
"outputs": [
|
||||||
|
{
|
||||||
|
"data": {
|
||||||
|
"text/html": [
|
||||||
|
"<pre style=\"white-space:pre;overflow-x:auto;line-height:normal;font-family:Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace\">╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ | Report | Question | Answer | │\n",
|
||||||
|
"│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| │\n",
|
||||||
|
"│ | IBM 2022 | How many hours were spent on employee learning in 2021? | 22.5 million hours | │\n",
|
||||||
|
"│ | IBM 2022 | What was the rate of fatalities in 2021? | The rate of fatalities in 2021 was 0.0016. | │\n",
|
||||||
|
"│ | IBM 2022 | How many full audits were con- ducted in 2022 in India? | 2 | │\n",
|
||||||
|
"│ | Starbucks 2022 | What is the percentage of women in the Board of Directors? | 25% | │\n",
|
||||||
|
"│ | Starbucks 2022 | What was the total energy con- sumption in 2021? | According to the table, the total energy consumption in 2021 was 2,491,543 MWh. | │\n",
|
||||||
|
"│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. | │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ## Related Work │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ The DocQA integrates multiple AI technologies, namely: │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
|
||||||
|
"│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al. │\n",
|
||||||
|
"│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning- │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline. │\n",
|
||||||
|
"│ <!-- Picture description: The image depicts a document conversion process. It is a sequence of steps that includes document conversion, information retrieval, and response generation. The document │\n",
|
||||||
|
"│ conversion step involves converting the document from a text format to a markdown format. The information retrieval step involves retrieving the document from a database or other source. The response │\n",
|
||||||
|
"│ generation step involves generating a response from the information retrieval step. --> │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018). │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n",
|
||||||
|
"</pre>\n"
|
||||||
|
],
|
||||||
|
"text/plain": [
|
||||||
|
"╭────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮\n",
|
||||||
|
"│ Copyright © 2024, Association for the Advancement of Artificial Intelligence (www.aaai.org). All rights reserved. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ | Report | Question | Answer | │\n",
|
||||||
|
"│ |----------------|------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| │\n",
|
||||||
|
"│ | IBM 2022 | How many hours were spent on employee learning in 2021? | 22.5 million hours | │\n",
|
||||||
|
"│ | IBM 2022 | What was the rate of fatalities in 2021? | The rate of fatalities in 2021 was 0.0016. | │\n",
|
||||||
|
"│ | IBM 2022 | How many full audits were con- ducted in 2022 in India? | 2 | │\n",
|
||||||
|
"│ | Starbucks 2022 | What is the percentage of women in the Board of Directors? | 25% | │\n",
|
||||||
|
"│ | Starbucks 2022 | What was the total energy con- sumption in 2021? | According to the table, the total energy consumption in 2021 was 2,491,543 MWh. | │\n",
|
||||||
|
"│ | Starbucks 2022 | How much packaging material was made from renewable mate- rials? | According to the given data, 31% of packaging materials were made from recycled or renewable materials in FY22. | │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Table 1: Example question answers from the ESG reports of IBM and Starbucks using Deep Search DocQA system. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ESG report in our library via our QA conversational assistant. Our assistant generates answers and also presents the information (paragraph or table), in the ESG report, from which it has generated the │\n",
|
||||||
|
"│ response. │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ ## Related Work │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ The DocQA integrates multiple AI technologies, namely: │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Document Conversion: Converting unstructured documents, such as PDF files, into a machine-readable format is a challenging task in AI. Early strategies for document conversion were based on geometric layout │\n",
|
||||||
|
"│ analysis (Cattoni et al. 2000; Breuel 2002). Thanks to the availability of large annotated datasets (PubLayNet (Zhong et al. 2019), DocBank (Li et al. 2020), DocLayNet (Pfitzmann et al. 2022; Auer et al. │\n",
|
||||||
|
"│ 2023), deep learning-based methods are routinely used. Modern approaches for recovering the structure of a document can be broadly divided into two categories: image-based or PDF representation-based . │\n",
|
||||||
|
"│ Imagebased methods usually employ Transformer or CNN architectures on the images of pages (Zhang et al. 2023; Li et al. 2022; Huang et al. 2022). On the other hand, deep learning- │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ Figure 1: System architecture: Simplified sketch of document question-answering pipeline. │\n",
|
||||||
|
"│ <!-- Picture description: The image depicts a document conversion process. It is a sequence of steps that includes document conversion, information retrieval, and response generation. The document │\n",
|
||||||
|
"│ conversion step involves converting the document from a text format to a markdown format. The information retrieval step involves retrieving the document from a database or other source. The response │\n",
|
||||||
|
"│ generation step involves generating a response from the information retrieval step. --> │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ based language processing methods are applied on the native PDF content (generated by a single PDF printing command) (Auer et al. 2022; Livathinos et al. 2021; Staar et al. 2018). │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"│ │\n",
|
||||||
|
"╰────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯\n"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"metadata": {},
|
||||||
|
"output_type": "display_data"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"source": [
|
||||||
|
"serializer = MarkdownDocSerializer(\n",
|
||||||
|
" doc=doc,\n",
|
||||||
|
" picture_serializer=AnnotationPictureSerializer(),\n",
|
||||||
|
" params=MarkdownParams(\n",
|
||||||
|
" image_mode=ImageRefMode.PLACEHOLDER,\n",
|
||||||
|
" image_placeholder=\"\",\n",
|
||||||
|
" ),\n",
|
||||||
|
")\n",
|
||||||
|
"ser_result = serializer.serialize()\n",
|
||||||
|
"ser_text = ser_result.text\n",
|
||||||
|
"\n",
|
||||||
|
"print_in_console(ser_text[ser_text.find(start_cue) : ser_text.find(stop_cue)])"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"metadata": {
|
||||||
|
"kernelspec": {
|
||||||
|
"display_name": ".venv",
|
||||||
|
"language": "python",
|
||||||
|
"name": "python3"
|
||||||
|
},
|
||||||
|
"language_info": {
|
||||||
|
"codemirror_mode": {
|
||||||
|
"name": "ipython",
|
||||||
|
"version": 3
|
||||||
|
},
|
||||||
|
"file_extension": ".py",
|
||||||
|
"mimetype": "text/x-python",
|
||||||
|
"name": "python",
|
||||||
|
"nbconvert_exporter": "python",
|
||||||
|
"pygments_lexer": "ipython3",
|
||||||
|
"version": "3.13.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nbformat": 4,
|
||||||
|
"nbformat_minor": 2
|
||||||
|
}
|
@ -137,7 +137,7 @@ This is a collection of FAQ collected from the user questions on <https://github
|
|||||||
### Some images are missing from MS Word and Powerpoint
|
### Some images are missing from MS Word and Powerpoint
|
||||||
|
|
||||||
The image processing library used by Docling is able to handle embedded WMF images only on Windows platform.
|
The image processing library used by Docling is able to handle embedded WMF images only on Windows platform.
|
||||||
If you are on other operaring systems, these images will be ignored.
|
If you are on other operating systems, these images will be ignored.
|
||||||
|
|
||||||
|
|
||||||
??? question "`HybridChunker` triggers warning: 'Token indices sequence length is longer than the specified maximum sequence length for this model'"
|
??? question "`HybridChunker` triggers warning: 'Token indices sequence length is longer than the specified maximum sequence length for this model'"
|
||||||
|
@ -13,6 +13,7 @@
|
|||||||
[](https://github.com/pre-commit/pre-commit)
|
[](https://github.com/pre-commit/pre-commit)
|
||||||
[](https://opensource.org/licenses/MIT)
|
[](https://opensource.org/licenses/MIT)
|
||||||
[](https://pepy.tech/projects/docling)
|
[](https://pepy.tech/projects/docling)
|
||||||
|
[](https://www.bestpractices.dev/projects/10101)
|
||||||
[](https://lfaidata.foundation/projects/)
|
[](https://lfaidata.foundation/projects/)
|
||||||
|
|
||||||
Docling simplifies document processing, parsing diverse formats — including advanced PDF understanding — and providing seamless integrations with the gen AI ecosystem.
|
Docling simplifies document processing, parsing diverse formats — including advanced PDF understanding — and providing seamless integrations with the gen AI ecosystem.
|
||||||
|
@ -1,10 +1,10 @@
|
|||||||
Docling is used by the [Data Prep Kit](https://ibm.github.io/data-prep-kit/) open-source toolkit for preparing unstructured data for LLM application development ranging from laptop scale to datacenter scale.
|
Docling is used by the [Data Prep Kit](https://data-prep-kit.github.io/data-prep-kit/) open-source toolkit for preparing unstructured data for LLM application development ranging from laptop scale to datacenter scale.
|
||||||
|
|
||||||
## Components
|
## Components
|
||||||
### PDF ingestion to Parquet
|
### PDF ingestion to Parquet
|
||||||
- 💻 [PDF-to-Parquet GitHub](https://github.com/IBM/data-prep-kit/tree/dev/transforms/language/pdf2parquet)
|
- 💻 [Docling2Parquet source](https://github.com/data-prep-kit/data-prep-kit/tree/dev/transforms/language/docling2parquet)
|
||||||
- 📖 [PDF-to-Parquet docs](https://ibm.github.io/data-prep-kit/transforms/language/pdf2parquet/python/)
|
- 📖 [Docling2Parquet docs](https://data-prep-kit.github.io/data-prep-kit/transforms/language/pdf2parquet/)
|
||||||
|
|
||||||
### Document chunking
|
### Document chunking
|
||||||
- 💻 [Doc Chunking GitHub](https://github.com/IBM/data-prep-kit/tree/dev/transforms/language/doc_chunk)
|
- 💻 [Doc Chunking source](https://github.com/data-prep-kit/data-prep-kit/tree/dev/transforms/language/doc_chunk)
|
||||||
- 📖 [Doc Chunking docs](https://ibm.github.io/data-prep-kit/transforms/language/doc_chunk/python/)
|
- 📖 [Doc Chunking docs](https://data-prep-kit.github.io/data-prep-kit/transforms/language/doc_chunk/)
|
||||||
|
@ -200,7 +200,7 @@ You can limit the CPU threads used by Docling by setting the environment variabl
|
|||||||
using a `DocumentConverter` (high-level API) as discussed in the sections above
|
using a `DocumentConverter` (high-level API) as discussed in the sections above
|
||||||
should suffice — and is the recommended way.
|
should suffice — and is the recommended way.
|
||||||
|
|
||||||
By default, Docling will try to identify the document format to apply the appropriate conversion backend (see the list of [supported formats](../supported_formats.md)).
|
By default, Docling will try to identify the document format to apply the appropriate conversion backend (see the list of [supported formats](supported_formats.md)).
|
||||||
You can restrict the `DocumentConverter` to a set of allowed document formats, as shown in the [Multi-format conversion](../examples/run_with_formats.py) example.
|
You can restrict the `DocumentConverter` to a set of allowed document formats, as shown in the [Multi-format conversion](../examples/run_with_formats.py) example.
|
||||||
Alternatively, you can also use the specific backend that matches your document content. For instance, you can use `HTMLDocumentBackend` for HTML pages:
|
Alternatively, you can also use the specific backend that matches your document content. For instance, you can use `HTMLDocumentBackend` for HTML pages:
|
||||||
|
|
||||||
|
@ -37,7 +37,7 @@ docling ./input/dir --output ./scratch --abort-on-error
|
|||||||
|
|
||||||
### Setting up a `DocumentConverter`
|
### Setting up a `DocumentConverter`
|
||||||
|
|
||||||
To accomodate many input formats, we changed the way you need to set up your `DocumentConverter` object.
|
To accommodate many input formats, we changed the way you need to set up your `DocumentConverter` object.
|
||||||
You can now define a list of allowed formats on the `DocumentConverter` initialization, and specify custom options
|
You can now define a list of allowed formats on the `DocumentConverter` initialization, and specify custom options
|
||||||
per-format if desired. By default, all supported formats are allowed. If you don't provide `format_options`, defaults
|
per-format if desired. By default, all supported formats are allowed. If you don't provide `format_options`, defaults
|
||||||
will be used for all `allowed_formats`.
|
will be used for all `allowed_formats`.
|
||||||
@ -151,7 +151,7 @@ conv_result: ConversionResult = doc_converter.convert("https://arxiv.org/pdf/240
|
|||||||
## Inspect the converted document:
|
## Inspect the converted document:
|
||||||
conv_result.document.print_element_tree()
|
conv_result.document.print_element_tree()
|
||||||
|
|
||||||
## Iterate the elements in reading order, including hierachy level:
|
## Iterate the elements in reading order, including hierarchy level:
|
||||||
for item, level in conv_result.document.iterate_items():
|
for item, level in conv_result.document.iterate_items():
|
||||||
if isinstance(item, TextItem):
|
if isinstance(item, TextItem):
|
||||||
print(item.text)
|
print(item.text)
|
||||||
|
@ -66,6 +66,7 @@ nav:
|
|||||||
- Concepts: concepts/index.md
|
- Concepts: concepts/index.md
|
||||||
- Architecture: concepts/architecture.md
|
- Architecture: concepts/architecture.md
|
||||||
- Docling Document: concepts/docling_document.md
|
- Docling Document: concepts/docling_document.md
|
||||||
|
- Serialization: concepts/serialization.md
|
||||||
- Chunking: concepts/chunking.md
|
- Chunking: concepts/chunking.md
|
||||||
- Plugins: concepts/plugins.md
|
- Plugins: concepts/plugins.md
|
||||||
- Examples:
|
- Examples:
|
||||||
@ -87,6 +88,8 @@ nav:
|
|||||||
- "Simple translation": examples/translate.py
|
- "Simple translation": examples/translate.py
|
||||||
- examples/backend_csv.ipynb
|
- examples/backend_csv.ipynb
|
||||||
- examples/backend_xml_rag.ipynb
|
- examples/backend_xml_rag.ipynb
|
||||||
|
- 📤 Serialization:
|
||||||
|
- examples/serialization.ipynb
|
||||||
- ✂️ Chunking:
|
- ✂️ Chunking:
|
||||||
- examples/hybrid_chunking.ipynb
|
- examples/hybrid_chunking.ipynb
|
||||||
- 🤖 RAG with AI dev frameworks:
|
- 🤖 RAG with AI dev frameworks:
|
||||||
@ -101,6 +104,7 @@ nav:
|
|||||||
- "Figure enrichment": examples/develop_picture_enrichment.py
|
- "Figure enrichment": examples/develop_picture_enrichment.py
|
||||||
- "Formula enrichment": examples/develop_formula_understanding.py
|
- "Formula enrichment": examples/develop_formula_understanding.py
|
||||||
- 🗂️ More examples:
|
- 🗂️ More examples:
|
||||||
|
- examples/rag_milvus.ipynb
|
||||||
- examples/rag_weaviate.ipynb
|
- examples/rag_weaviate.ipynb
|
||||||
- RAG with Granite [↗]: https://github.com/ibm-granite-community/granite-snack-cookbook/blob/main/recipes/RAG/Granite_Docling_RAG.ipynb
|
- RAG with Granite [↗]: https://github.com/ibm-granite-community/granite-snack-cookbook/blob/main/recipes/RAG/Granite_Docling_RAG.ipynb
|
||||||
- examples/rag_azuresearch.ipynb
|
- examples/rag_azuresearch.ipynb
|
||||||
|
2352
poetry.lock
generated
2352
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
|||||||
[tool.poetry]
|
[tool.poetry]
|
||||||
name = "docling"
|
name = "docling"
|
||||||
version = "2.30.0" # DO NOT EDIT, updated automatically
|
version = "2.31.2" # DO NOT EDIT, updated automatically
|
||||||
description = "SDK and CLI for parsing PDF, DOCX, HTML, and more, to a unified document representation for powering downstream workflows such as gen AI applications."
|
description = "SDK and CLI for parsing PDF, DOCX, HTML, and more, to a unified document representation for powering downstream workflows such as gen AI applications."
|
||||||
authors = [
|
authors = [
|
||||||
"Christoph Auer <cau@zurich.ibm.com>",
|
"Christoph Auer <cau@zurich.ibm.com>",
|
||||||
@ -90,8 +90,10 @@ pillow = ">=10.0.0,<12.0.0"
|
|||||||
tqdm = "^4.65.0"
|
tqdm = "^4.65.0"
|
||||||
pluggy = "^1.0.0"
|
pluggy = "^1.0.0"
|
||||||
pylatexenc = "^2.10"
|
pylatexenc = "^2.10"
|
||||||
|
click = "<8.2.0"
|
||||||
|
|
||||||
[tool.poetry.group.dev.dependencies]
|
[tool.poetry.group.dev.dependencies]
|
||||||
|
python = "^3.9.2"
|
||||||
black = { extras = ["jupyter"], version = "^24.4.2" }
|
black = { extras = ["jupyter"], version = "^24.4.2" }
|
||||||
pytest = "^7.2.2"
|
pytest = "^7.2.2"
|
||||||
pre-commit = "^3.7.1"
|
pre-commit = "^3.7.1"
|
||||||
|
@ -23,6 +23,7 @@
|
|||||||
<location><page_1><loc_52><loc_37><loc_88><loc_45></location>
|
<location><page_1><loc_52><loc_37><loc_88><loc_45></location>
|
||||||
<caption>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'.</caption>
|
<caption>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'.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_1><loc_50><loc_29><loc_89><loc_35></location>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'.</caption>
|
||||||
<table>
|
<table>
|
||||||
<location><page_1><loc_52><loc_37><loc_88><loc_45></location>
|
<location><page_1><loc_52><loc_37><loc_88><loc_45></location>
|
||||||
<row_0><col_0><body>0</col_0><col_1><body>1 2 1</col_1><col_2><body>1 2 1</col_2><col_3><body>1 2 1</col_3><col_4><body>1 2 1</col_4></row_0>
|
<row_0><col_0><body>0</col_0><col_1><body>1 2 1</col_1><col_2><body>1 2 1</col_2><col_3><body>1 2 1</col_3><col_4><body>1 2 1</col_4></row_0>
|
||||||
@ -57,6 +58,7 @@
|
|||||||
<location><page_3><loc_51><loc_68><loc_90><loc_90></location>
|
<location><page_3><loc_51><loc_68><loc_90><loc_90></location>
|
||||||
<caption>Figure 2: Distribution of the tables across different table dimensions in PubTabNet + FinTabNet datasets</caption>
|
<caption>Figure 2: Distribution of the tables across different table dimensions in PubTabNet + FinTabNet datasets</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_3><loc_50><loc_64><loc_89><loc_66></location>Figure 2: Distribution of the tables across different table dimensions in PubTabNet + FinTabNet datasets</caption>
|
||||||
<paragraph><location><page_3><loc_50><loc_59><loc_71><loc_60></location>balance in the previous datasets.</paragraph>
|
<paragraph><location><page_3><loc_50><loc_59><loc_71><loc_60></location>balance in the previous datasets.</paragraph>
|
||||||
<paragraph><location><page_3><loc_50><loc_21><loc_89><loc_58></location>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.</paragraph>
|
<paragraph><location><page_3><loc_50><loc_21><loc_89><loc_58></location>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.</paragraph>
|
||||||
<paragraph><location><page_3><loc_50><loc_10><loc_89><loc_20></location>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</paragraph>
|
<paragraph><location><page_3><loc_50><loc_10><loc_89><loc_20></location>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</paragraph>
|
||||||
@ -88,10 +90,12 @@
|
|||||||
<location><page_5><loc_12><loc_77><loc_85><loc_90></location>
|
<location><page_5><loc_12><loc_77><loc_85><loc_90></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_5><loc_8><loc_72><loc_89><loc_74></location>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.</caption>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_5><loc_9><loc_36><loc_47><loc_67></location>
|
<location><page_5><loc_9><loc_36><loc_47><loc_67></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_5><loc_8><loc_14><loc_47><loc_33></location>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.</caption>
|
||||||
<paragraph><location><page_5><loc_50><loc_63><loc_89><loc_68></location>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 .</paragraph>
|
<paragraph><location><page_5><loc_50><loc_63><loc_89><loc_68></location>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 .</paragraph>
|
||||||
<paragraph><location><page_5><loc_50><loc_48><loc_89><loc_62></location>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.</paragraph>
|
<paragraph><location><page_5><loc_50><loc_48><loc_89><loc_62></location>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.</paragraph>
|
||||||
<paragraph><location><page_5><loc_50><loc_31><loc_89><loc_47></location>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.</paragraph>
|
<paragraph><location><page_5><loc_50><loc_31><loc_89><loc_47></location>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.</paragraph>
|
||||||
@ -167,6 +171,7 @@
|
|||||||
<location><page_8><loc_50><loc_77><loc_91><loc_88></location>
|
<location><page_8><loc_50><loc_77><loc_91><loc_88></location>
|
||||||
<caption>b. Structure predicted by TableFormer, with superimposed matched PDF cell text:</caption>
|
<caption>b. Structure predicted by TableFormer, with superimposed matched PDF cell text:</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_8><loc_9><loc_73><loc_63><loc_74></location>b. Structure predicted by TableFormer, with superimposed matched PDF cell text:</caption>
|
||||||
<table>
|
<table>
|
||||||
<location><page_8><loc_9><loc_63><loc_49><loc_72></location>
|
<location><page_8><loc_9><loc_63><loc_49><loc_72></location>
|
||||||
<caption>Text is aligned to match original for ease of viewing</caption>
|
<caption>Text is aligned to match original for ease of viewing</caption>
|
||||||
@ -196,10 +201,12 @@
|
|||||||
<location><page_8><loc_8><loc_44><loc_35><loc_52></location>
|
<location><page_8><loc_8><loc_44><loc_35><loc_52></location>
|
||||||
<caption>Figure 6: An example of TableFormer predictions (bounding boxes and structure) from generated SynthTabNet table.</caption>
|
<caption>Figure 6: An example of TableFormer predictions (bounding boxes and structure) from generated SynthTabNet table.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_8><loc_10><loc_41><loc_87><loc_42></location>Figure 6: An example of TableFormer predictions (bounding boxes and structure) from generated SynthTabNet table.</caption>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_8><loc_35><loc_44><loc_61><loc_52></location>
|
<location><page_8><loc_35><loc_44><loc_61><loc_52></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_8><loc_8><loc_54><loc_89><loc_59></location>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.</caption>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_8><loc_63><loc_44><loc_89><loc_52></location>
|
<location><page_8><loc_63><loc_44><loc_89><loc_52></location>
|
||||||
</figure>
|
</figure>
|
||||||
@ -269,6 +276,7 @@
|
|||||||
<location><page_12><loc_9><loc_81><loc_89><loc_91></location>
|
<location><page_12><loc_9><loc_81><loc_89><loc_91></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_12><loc_8><loc_76><loc_89><loc_79></location>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.</caption>
|
||||||
<paragraph><location><page_12><loc_10><loc_71><loc_47><loc_73></location>- · TableFormer output does not include the table cell content.</paragraph>
|
<paragraph><location><page_12><loc_10><loc_71><loc_47><loc_73></location>- · TableFormer output does not include the table cell content.</paragraph>
|
||||||
<paragraph><location><page_12><loc_10><loc_67><loc_47><loc_69></location>- · There are occasional inaccuracies in the predictions of the bounding boxes.</paragraph>
|
<paragraph><location><page_12><loc_10><loc_67><loc_47><loc_69></location>- · There are occasional inaccuracies in the predictions of the bounding boxes.</paragraph>
|
||||||
<paragraph><location><page_12><loc_50><loc_68><loc_89><loc_73></location>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.</paragraph>
|
<paragraph><location><page_12><loc_50><loc_68><loc_89><loc_73></location>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.</paragraph>
|
||||||
@ -373,6 +381,7 @@
|
|||||||
<location><page_14><loc_52><loc_55><loc_87><loc_89></location>
|
<location><page_14><loc_52><loc_55><loc_87><loc_89></location>
|
||||||
<caption>Figure 13: Table predictions example on colorful table.</caption>
|
<caption>Figure 13: Table predictions example on colorful table.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_14><loc_52><loc_52><loc_88><loc_53></location>Figure 13: Table predictions example on colorful table.</caption>
|
||||||
<table>
|
<table>
|
||||||
<location><page_14><loc_52><loc_40><loc_85><loc_46></location>
|
<location><page_14><loc_52><loc_40><loc_85><loc_46></location>
|
||||||
<caption>Figure 14: Example with multi-line text.</caption>
|
<caption>Figure 14: Example with multi-line text.</caption>
|
||||||
@ -433,4 +442,5 @@
|
|||||||
<location><page_16><loc_11><loc_37><loc_86><loc_68></location>
|
<location><page_16><loc_11><loc_37><loc_86><loc_68></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_16><loc_8><loc_33><loc_89><loc_36></location>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.</caption>
|
||||||
</document>
|
</document>
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -18,6 +18,7 @@
|
|||||||
<location><page_1><loc_53><loc_34><loc_90><loc_68></location>
|
<location><page_1><loc_53><loc_34><loc_90><loc_68></location>
|
||||||
<caption>Figure 1: Four examples of complex page layouts across different document categories</caption>
|
<caption>Figure 1: Four examples of complex page layouts across different document categories</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_1><loc_52><loc_29><loc_91><loc_32></location>Figure 1: Four examples of complex page layouts across different document categories</caption>
|
||||||
<subtitle-level-1><location><page_1><loc_52><loc_24><loc_62><loc_25></location>KEYWORDS</subtitle-level-1>
|
<subtitle-level-1><location><page_1><loc_52><loc_24><loc_62><loc_25></location>KEYWORDS</subtitle-level-1>
|
||||||
<paragraph><location><page_1><loc_52><loc_21><loc_91><loc_23></location>PDF document conversion, layout segmentation, object-detection, data set, Machine Learning</paragraph>
|
<paragraph><location><page_1><loc_52><loc_21><loc_91><loc_23></location>PDF document conversion, layout segmentation, object-detection, data set, Machine Learning</paragraph>
|
||||||
<subtitle-level-1><location><page_1><loc_52><loc_18><loc_66><loc_19></location>ACM Reference Format:</subtitle-level-1>
|
<subtitle-level-1><location><page_1><loc_52><loc_18><loc_66><loc_19></location>ACM Reference Format:</subtitle-level-1>
|
||||||
@ -44,6 +45,7 @@
|
|||||||
<location><page_3><loc_14><loc_72><loc_43><loc_88></location>
|
<location><page_3><loc_14><loc_72><loc_43><loc_88></location>
|
||||||
<caption>Figure 2: Distribution of DocLayNet pages across document categories.</caption>
|
<caption>Figure 2: Distribution of DocLayNet pages across document categories.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_3><loc_9><loc_68><loc_48><loc_70></location>Figure 2: Distribution of DocLayNet pages across document categories.</caption>
|
||||||
<paragraph><location><page_3><loc_9><loc_54><loc_48><loc_64></location>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".</paragraph>
|
<paragraph><location><page_3><loc_9><loc_54><loc_48><loc_64></location>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".</paragraph>
|
||||||
<paragraph><location><page_3><loc_9><loc_36><loc_48><loc_53></location>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 Reports contain both free-style format annual reports 2 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.</paragraph>
|
<paragraph><location><page_3><loc_9><loc_36><loc_48><loc_53></location>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 Reports contain both free-style format annual reports 2 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.</paragraph>
|
||||||
<paragraph><location><page_3><loc_9><loc_23><loc_48><loc_35></location>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.</paragraph>
|
<paragraph><location><page_3><loc_9><loc_23><loc_48><loc_35></location>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.</paragraph>
|
||||||
@ -76,6 +78,7 @@
|
|||||||
<location><page_4><loc_9><loc_32><loc_48><loc_61></location>
|
<location><page_4><loc_9><loc_32><loc_48><loc_61></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_4><loc_9><loc_23><loc_48><loc_30></location>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.</caption>
|
||||||
<paragraph><location><page_4><loc_9><loc_15><loc_48><loc_20></location>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.</paragraph>
|
<paragraph><location><page_4><loc_9><loc_15><loc_48><loc_20></location>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.</paragraph>
|
||||||
<paragraph><location><page_4><loc_9><loc_11><loc_48><loc_14></location><location><page_4><loc_9><loc_11><loc_48><loc_14></location>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 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.</paragraph>
|
<paragraph><location><page_4><loc_9><loc_11><loc_48><loc_14></location><location><page_4><loc_9><loc_11><loc_48><loc_14></location>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 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.</paragraph>
|
||||||
<paragraph><location><page_4><loc_52><loc_36><loc_91><loc_52></location>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.</paragraph>
|
<paragraph><location><page_4><loc_52><loc_36><loc_91><loc_52></location>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.</paragraph>
|
||||||
@ -123,6 +126,7 @@
|
|||||||
<location><page_6><loc_53><loc_67><loc_90><loc_89></location>
|
<location><page_6><loc_53><loc_67><loc_90><loc_89></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_6><loc_52><loc_57><loc_91><loc_65></location>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.</caption>
|
||||||
<paragraph><location><page_6><loc_52><loc_49><loc_91><loc_52></location>paper and leave the detailed evaluation of more recent methods mentioned in Section 2 for future work.</paragraph>
|
<paragraph><location><page_6><loc_52><loc_49><loc_91><loc_52></location>paper and leave the detailed evaluation of more recent methods mentioned in Section 2 for future work.</paragraph>
|
||||||
<paragraph><location><page_6><loc_52><loc_39><loc_91><loc_49></location>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].</paragraph>
|
<paragraph><location><page_6><loc_52><loc_39><loc_91><loc_49></location>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].</paragraph>
|
||||||
<subtitle-level-1><location><page_6><loc_52><loc_36><loc_76><loc_37></location>Baselines for Object Detection</subtitle-level-1>
|
<subtitle-level-1><location><page_6><loc_52><loc_36><loc_76><loc_37></location>Baselines for Object Detection</subtitle-level-1>
|
||||||
@ -216,6 +220,7 @@
|
|||||||
<location><page_9><loc_9><loc_44><loc_91><loc_89></location>
|
<location><page_9><loc_9><loc_44><loc_91><loc_89></location>
|
||||||
<caption>Text Caption List-Item Formula Table Section-Header Picture Page-Header Page-Footer Title</caption>
|
<caption>Text Caption List-Item Formula Table Section-Header Picture Page-Header Page-Footer Title</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_9><loc_10><loc_43><loc_52><loc_44></location>Text Caption List-Item Formula Table Section-Header Picture Page-Header Page-Footer Title</caption>
|
||||||
<paragraph><location><page_9><loc_9><loc_36><loc_91><loc_41></location>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.</paragraph>
|
<paragraph><location><page_9><loc_9><loc_36><loc_91><loc_41></location>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.</paragraph>
|
||||||
<paragraph><location><page_9><loc_11><loc_31><loc_48><loc_33></location>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.</paragraph>
|
<paragraph><location><page_9><loc_11><loc_31><loc_48><loc_33></location>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.</paragraph>
|
||||||
<paragraph><location><page_9><loc_52><loc_32><loc_91><loc_33></location>- [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.</paragraph>
|
<paragraph><location><page_9><loc_52><loc_32><loc_91><loc_33></location>- [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.</paragraph>
|
||||||
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -13,6 +13,7 @@
|
|||||||
<location><page_2><loc_24><loc_46><loc_76><loc_74></location>
|
<location><page_2><loc_24><loc_46><loc_76><loc_74></location>
|
||||||
<caption>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).</caption>
|
<caption>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).</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_2><loc_22><loc_75><loc_79><loc_84></location>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).</caption>
|
||||||
<paragraph><location><page_2><loc_22><loc_34><loc_79><loc_43></location>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].</paragraph>
|
<paragraph><location><page_2><loc_22><loc_34><loc_79><loc_43></location>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].</paragraph>
|
||||||
<paragraph><location><page_2><loc_22><loc_16><loc_79><loc_34></location>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.</paragraph>
|
<paragraph><location><page_2><loc_22><loc_16><loc_79><loc_34></location>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.</paragraph>
|
||||||
<paragraph><location><page_3><loc_22><loc_73><loc_79><loc_85></location>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.</paragraph>
|
<paragraph><location><page_3><loc_22><loc_73><loc_79><loc_85></location>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.</paragraph>
|
||||||
@ -30,6 +31,7 @@
|
|||||||
<location><page_5><loc_22><loc_57><loc_78><loc_71></location>
|
<location><page_5><loc_22><loc_57><loc_78><loc_71></location>
|
||||||
<caption>Fig. 2. Frequency of tokens in HTML and OTSL as they appear in PubTabNet.</caption>
|
<caption>Fig. 2. Frequency of tokens in HTML and OTSL as they appear in PubTabNet.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_5><loc_24><loc_71><loc_77><loc_72></location>Fig. 2. Frequency of tokens in HTML and OTSL as they appear in PubTabNet.</caption>
|
||||||
<paragraph><location><page_5><loc_22><loc_33><loc_79><loc_54></location>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.</paragraph>
|
<paragraph><location><page_5><loc_22><loc_33><loc_79><loc_54></location>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.</paragraph>
|
||||||
<paragraph><location><page_5><loc_22><loc_27><loc_79><loc_32></location>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.</paragraph>
|
<paragraph><location><page_5><loc_22><loc_27><loc_79><loc_32></location>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.</paragraph>
|
||||||
<paragraph><location><page_5><loc_22><loc_16><loc_79><loc_26></location>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</paragraph>
|
<paragraph><location><page_5><loc_22><loc_16><loc_79><loc_26></location>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</paragraph>
|
||||||
@ -50,6 +52,7 @@
|
|||||||
<location><page_7><loc_27><loc_65><loc_73><loc_79></location>
|
<location><page_7><loc_27><loc_65><loc_73><loc_79></location>
|
||||||
<caption>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</caption>
|
<caption>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</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_7><loc_22><loc_80><loc_79><loc_84></location>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</caption>
|
||||||
<subtitle-level-1><location><page_7><loc_22><loc_60><loc_40><loc_61></location>4.2 Language Syntax</subtitle-level-1>
|
<subtitle-level-1><location><page_7><loc_22><loc_60><loc_40><loc_61></location>4.2 Language Syntax</subtitle-level-1>
|
||||||
<paragraph><location><page_7><loc_22><loc_58><loc_59><loc_59></location>The OTSL representation follows these syntax rules:</paragraph>
|
<paragraph><location><page_7><loc_22><loc_58><loc_59><loc_59></location>The OTSL representation follows these syntax rules:</paragraph>
|
||||||
<paragraph><location><page_7><loc_23><loc_54><loc_79><loc_56></location>- 1. Left-looking cell rule : The left neighbour of an "L" cell must be either another "L" cell or a "C" cell.</paragraph>
|
<paragraph><location><page_7><loc_23><loc_54><loc_79><loc_56></location>- 1. Left-looking cell rule : The left neighbour of an "L" cell must be either another "L" cell or a "C" cell.</paragraph>
|
||||||
@ -70,6 +73,7 @@
|
|||||||
<location><page_8><loc_23><loc_25><loc_77><loc_36></location>
|
<location><page_8><loc_23><loc_25><loc_77><loc_36></location>
|
||||||
<caption>Fig. 4. Architecture sketch of the TableFormer model, which is a representative for the Im2Seq approach.</caption>
|
<caption>Fig. 4. Architecture sketch of the TableFormer model, which is a representative for the Im2Seq approach.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_8><loc_22><loc_36><loc_79><loc_39></location>Fig. 4. Architecture sketch of the TableFormer model, which is a representative for the Im2Seq approach.</caption>
|
||||||
<paragraph><location><page_8><loc_22><loc_16><loc_79><loc_22></location>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</paragraph>
|
<paragraph><location><page_8><loc_22><loc_16><loc_79><loc_22></location>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</paragraph>
|
||||||
<paragraph><location><page_9><loc_22><loc_81><loc_79><loc_85></location>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.</paragraph>
|
<paragraph><location><page_9><loc_22><loc_81><loc_79><loc_85></location>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.</paragraph>
|
||||||
<subtitle-level-1><location><page_9><loc_22><loc_78><loc_52><loc_79></location>5.1 Hyper Parameter Optimization</subtitle-level-1>
|
<subtitle-level-1><location><page_9><loc_22><loc_78><loc_52><loc_79></location>5.1 Hyper Parameter Optimization</subtitle-level-1>
|
||||||
@ -104,12 +108,14 @@
|
|||||||
<location><page_10><loc_27><loc_16><loc_74><loc_44></location>
|
<location><page_10><loc_27><loc_16><loc_74><loc_44></location>
|
||||||
<caption>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. μ</caption>
|
<caption>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. μ</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_10><loc_22><loc_44><loc_79><loc_50></location>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. μ</caption>
|
||||||
<paragraph><location><page_10><loc_37><loc_15><loc_38><loc_16></location>μ</paragraph>
|
<paragraph><location><page_10><loc_37><loc_15><loc_38><loc_16></location>μ</paragraph>
|
||||||
<paragraph><location><page_10><loc_49><loc_12><loc_49><loc_14></location>≥</paragraph>
|
<paragraph><location><page_10><loc_49><loc_12><loc_49><loc_14></location>≥</paragraph>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_11><loc_28><loc_20><loc_73><loc_77></location>
|
<location><page_11><loc_28><loc_20><loc_73><loc_77></location>
|
||||||
<caption>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.</caption>
|
<caption>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.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_11><loc_22><loc_78><loc_79><loc_84></location>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.</caption>
|
||||||
<subtitle-level-1><location><page_12><loc_22><loc_84><loc_36><loc_85></location>6 Conclusion</subtitle-level-1>
|
<subtitle-level-1><location><page_12><loc_22><loc_84><loc_36><loc_85></location>6 Conclusion</subtitle-level-1>
|
||||||
<paragraph><location><page_12><loc_22><loc_74><loc_79><loc_81></location>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.</paragraph>
|
<paragraph><location><page_12><loc_22><loc_74><loc_79><loc_81></location>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.</paragraph>
|
||||||
<paragraph><location><page_12><loc_22><loc_59><loc_79><loc_74></location>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).</paragraph>
|
<paragraph><location><page_12><loc_22><loc_59><loc_79><loc_74></location>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).</paragraph>
|
||||||
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -10,6 +10,7 @@
|
|||||||
<location><page_1><loc_12><loc_10><loc_52><loc_31></location>
|
<location><page_1><loc_12><loc_10><loc_52><loc_31></location>
|
||||||
<caption>Figure 7-26. Self-locking nuts.</caption>
|
<caption>Figure 7-26. Self-locking nuts.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_1><loc_12><loc_8><loc_31><loc_9></location>Figure 7-26. Self-locking nuts.</caption>
|
||||||
<paragraph><location><page_1><loc_54><loc_85><loc_95><loc_94></location>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.</paragraph>
|
<paragraph><location><page_1><loc_54><loc_85><loc_95><loc_94></location>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.</paragraph>
|
||||||
<paragraph><location><page_1><loc_54><loc_83><loc_55><loc_85></location>.</paragraph>
|
<paragraph><location><page_1><loc_54><loc_83><loc_55><loc_85></location>.</paragraph>
|
||||||
<subtitle-level-1><location><page_1><loc_54><loc_82><loc_76><loc_83></location>Stainless Steel Self-Locking Nut</subtitle-level-1>
|
<subtitle-level-1><location><page_1><loc_54><loc_82><loc_76><loc_83></location>Stainless Steel Self-Locking Nut</subtitle-level-1>
|
||||||
@ -20,4 +21,5 @@
|
|||||||
<location><page_1><loc_54><loc_11><loc_94><loc_46></location>
|
<location><page_1><loc_54><loc_11><loc_94><loc_46></location>
|
||||||
<caption>Figure 7-27. Stainless steel self-locking nut.</caption>
|
<caption>Figure 7-27. Stainless steel self-locking nut.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_1><loc_54><loc_8><loc_81><loc_10></location>Figure 7-27. Stainless steel self-locking nut.</caption>
|
||||||
</document>
|
</document>
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -5,11 +5,13 @@
|
|||||||
<location><page_1><loc_22><loc_36><loc_78><loc_62></location>
|
<location><page_1><loc_22><loc_36><loc_78><loc_62></location>
|
||||||
<caption>Figure 1: This is an example image.</caption>
|
<caption>Figure 1: This is an example image.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_1><loc_37><loc_32><loc_63><loc_33></location>Figure 1: This is an example image.</caption>
|
||||||
<paragraph><location><page_1><loc_22><loc_15><loc_78><loc_30></location>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.</paragraph>
|
<paragraph><location><page_1><loc_22><loc_15><loc_78><loc_30></location>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.</paragraph>
|
||||||
<paragraph><location><page_2><loc_22><loc_66><loc_78><loc_84></location>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.</paragraph>
|
<paragraph><location><page_2><loc_22><loc_66><loc_78><loc_84></location>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.</paragraph>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_2><loc_36><loc_36><loc_64><loc_65></location>
|
<location><page_2><loc_36><loc_36><loc_64><loc_65></location>
|
||||||
<caption>Figure 2: This is an example image.</caption>
|
<caption>Figure 2: This is an example image.</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_2><loc_37><loc_33><loc_63><loc_34></location>Figure 2: This is an example image.</caption>
|
||||||
<paragraph><location><page_2><loc_22><loc_15><loc_78><loc_31></location>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.</paragraph>
|
<paragraph><location><page_2><loc_22><loc_15><loc_78><loc_31></location>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.</paragraph>
|
||||||
</document>
|
</document>
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -87,6 +87,7 @@
|
|||||||
<location><page_7><loc_22><loc_13><loc_89><loc_53></location>
|
<location><page_7><loc_22><loc_13><loc_89><loc_53></location>
|
||||||
<caption>Figure 1-2 Existing row and column controls</caption>
|
<caption>Figure 1-2 Existing row and column controls</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_7><loc_22><loc_12><loc_52><loc_13></location>Figure 1-2 Existing row and column controls</caption>
|
||||||
<subtitle-level-1><location><page_8><loc_11><loc_89><loc_55><loc_91></location>2.1.6 Change Function Usage CL command</subtitle-level-1>
|
<subtitle-level-1><location><page_8><loc_11><loc_89><loc_55><loc_91></location>2.1.6 Change Function Usage CL command</subtitle-level-1>
|
||||||
<paragraph><location><page_8><loc_22><loc_87><loc_89><loc_88></location>The following CL commands can be used to work with, display, or change function usage IDs:</paragraph>
|
<paragraph><location><page_8><loc_22><loc_87><loc_89><loc_88></location>The following CL commands can be used to work with, display, or change function usage IDs:</paragraph>
|
||||||
<paragraph><location><page_8><loc_22><loc_84><loc_49><loc_86></location>- GLYPH<SM590000> Work Function Usage ( WRKFCNUSG )</paragraph>
|
<paragraph><location><page_8><loc_22><loc_84><loc_49><loc_86></location>- GLYPH<SM590000> Work Function Usage ( WRKFCNUSG )</paragraph>
|
||||||
@ -150,6 +151,7 @@
|
|||||||
<location><page_10><loc_22><loc_48><loc_89><loc_86></location>
|
<location><page_10><loc_22><loc_48><loc_89><loc_86></location>
|
||||||
<caption>Figure 3-1 CREATE PERMISSION SQL statement</caption>
|
<caption>Figure 3-1 CREATE PERMISSION SQL statement</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_10><loc_22><loc_47><loc_56><loc_48></location>Figure 3-1 CREATE PERMISSION SQL statement</caption>
|
||||||
<subtitle-level-1><location><page_10><loc_22><loc_43><loc_35><loc_44></location>Column mask</subtitle-level-1>
|
<subtitle-level-1><location><page_10><loc_22><loc_43><loc_35><loc_44></location>Column mask</subtitle-level-1>
|
||||||
<paragraph><location><page_10><loc_22><loc_37><loc_89><loc_43></location>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.</paragraph>
|
<paragraph><location><page_10><loc_22><loc_37><loc_89><loc_43></location>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.</paragraph>
|
||||||
<caption><location><page_11><loc_22><loc_90><loc_67><loc_91></location>Table 3-1 summarizes these special registers and their values.</caption>
|
<caption><location><page_11><loc_22><loc_90><loc_67><loc_91></location>Table 3-1 summarizes these special registers and their values.</caption>
|
||||||
@ -172,6 +174,7 @@
|
|||||||
<location><page_11><loc_22><loc_25><loc_49><loc_51></location>
|
<location><page_11><loc_22><loc_25><loc_49><loc_51></location>
|
||||||
<caption>Figure 3-5 Special registers and adopted authority</caption>
|
<caption>Figure 3-5 Special registers and adopted authority</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_11><loc_22><loc_24><loc_56><loc_25></location>Figure 3-5 Special registers and adopted authority</caption>
|
||||||
<subtitle-level-1><location><page_11><loc_11><loc_20><loc_40><loc_21></location>3.2.2 Built-in global variables</subtitle-level-1>
|
<subtitle-level-1><location><page_11><loc_11><loc_20><loc_40><loc_21></location>3.2.2 Built-in global variables</subtitle-level-1>
|
||||||
<paragraph><location><page_11><loc_22><loc_15><loc_85><loc_18></location>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.</paragraph>
|
<paragraph><location><page_11><loc_22><loc_15><loc_85><loc_18></location>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.</paragraph>
|
||||||
<paragraph><location><page_11><loc_22><loc_9><loc_87><loc_13></location>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.</paragraph>
|
<paragraph><location><page_11><loc_22><loc_9><loc_87><loc_13></location>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.</paragraph>
|
||||||
@ -215,6 +218,7 @@
|
|||||||
<location><page_14><loc_10><loc_79><loc_89><loc_88></location>
|
<location><page_14><loc_10><loc_79><loc_89><loc_88></location>
|
||||||
<caption>Figure 3-10 Column masks shown in System i Navigator</caption>
|
<caption>Figure 3-10 Column masks shown in System i Navigator</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_14><loc_11><loc_77><loc_48><loc_78></location>Figure 3-10 Column masks shown in System i Navigator</caption>
|
||||||
<subtitle-level-1><location><page_14><loc_11><loc_73><loc_33><loc_74></location>3.6.6 Activating RCAC</subtitle-level-1>
|
<subtitle-level-1><location><page_14><loc_11><loc_73><loc_33><loc_74></location>3.6.6 Activating RCAC</subtitle-level-1>
|
||||||
<paragraph><location><page_14><loc_22><loc_67><loc_89><loc_71></location>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:</paragraph>
|
<paragraph><location><page_14><loc_22><loc_67><loc_89><loc_71></location>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:</paragraph>
|
||||||
<paragraph><location><page_14><loc_22><loc_65><loc_67><loc_66></location>- 1. Run the SQL statements that are shown in Example 3-10.</paragraph>
|
<paragraph><location><page_14><loc_22><loc_65><loc_67><loc_66></location>- 1. Run the SQL statements that are shown in Example 3-10.</paragraph>
|
||||||
@ -230,16 +234,19 @@
|
|||||||
<location><page_14><loc_10><loc_18><loc_87><loc_46></location>
|
<location><page_14><loc_10><loc_18><loc_87><loc_46></location>
|
||||||
<caption>Figure 3-11 Selecting the EMPLOYEES table from System i Navigator</caption>
|
<caption>Figure 3-11 Selecting the EMPLOYEES table from System i Navigator</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_14><loc_11><loc_17><loc_57><loc_18></location>Figure 3-11 Selecting the EMPLOYEES table from System i Navigator</caption>
|
||||||
<paragraph><location><page_15><loc_22><loc_87><loc_84><loc_91></location>- 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.</paragraph>
|
<paragraph><location><page_15><loc_22><loc_87><loc_84><loc_91></location>- 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.</paragraph>
|
||||||
<paragraph><location><page_15><loc_22><loc_32><loc_89><loc_36></location>- 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.</paragraph>
|
<paragraph><location><page_15><loc_22><loc_32><loc_89><loc_36></location>- 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.</paragraph>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_15><loc_22><loc_40><loc_89><loc_85></location>
|
<location><page_15><loc_22><loc_40><loc_89><loc_85></location>
|
||||||
<caption>Figure 4-68 Visual Explain with RCAC enabled</caption>
|
<caption>Figure 4-68 Visual Explain with RCAC enabled</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_15><loc_22><loc_38><loc_53><loc_39></location>Figure 4-68 Visual Explain with RCAC enabled</caption>
|
||||||
<figure>
|
<figure>
|
||||||
<location><page_15><loc_11><loc_16><loc_83><loc_30></location>
|
<location><page_15><loc_11><loc_16><loc_83><loc_30></location>
|
||||||
<caption>Figure 4-69 Index advice with no RCAC</caption>
|
<caption>Figure 4-69 Index advice with no RCAC</caption>
|
||||||
</figure>
|
</figure>
|
||||||
|
<caption><location><page_15><loc_11><loc_15><loc_37><loc_16></location>Figure 4-69 Index advice with no RCAC</caption>
|
||||||
<paragraph><location><page_16><loc_11><loc_11><loc_82><loc_91></location>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 ;</paragraph>
|
<paragraph><location><page_16><loc_11><loc_11><loc_82><loc_91></location>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 ;</paragraph>
|
||||||
<paragraph><location><page_18><loc_47><loc_94><loc_68><loc_96></location>Back cover</paragraph>
|
<paragraph><location><page_18><loc_47><loc_94><loc_68><loc_96></location>Back cover</paragraph>
|
||||||
<subtitle-level-1><location><page_18><loc_4><loc_82><loc_73><loc_91></location>Row and Column Access Control Support in IBM DB2 for i</subtitle-level-1>
|
<subtitle-level-1><location><page_18><loc_4><loc_82><loc_73><loc_91></location>Row and Column Access Control Support in IBM DB2 for i</subtitle-level-1>
|
||||||
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -4,4 +4,7 @@ item-0 at level 0: unspecified: group _root_
|
|||||||
item-3 at level 1: text: This is a regular paragraph.
|
item-3 at level 1: text: This is a regular paragraph.
|
||||||
item-4 at level 1: text: This is a third div
|
item-4 at level 1: text: This is a third div
|
||||||
with a new line.
|
with a new line.
|
||||||
item-5 at level 1: text: This is a fourth div with a bold paragraph.
|
item-5 at level 1: section: group details
|
||||||
|
item-6 at level 2: text: Heading for the details element
|
||||||
|
item-7 at level 2: text: Description of the details element.
|
||||||
|
item-8 at level 1: text: This is a fourth div with a bold paragraph.
|
@ -4,7 +4,7 @@
|
|||||||
"name": "example_06",
|
"name": "example_06",
|
||||||
"origin": {
|
"origin": {
|
||||||
"mimetype": "text/html",
|
"mimetype": "text/html",
|
||||||
"binary_hash": 14574683870626799530,
|
"binary_hash": 10224930410364781672,
|
||||||
"filename": "example_06.html"
|
"filename": "example_06.html"
|
||||||
},
|
},
|
||||||
"furniture": {
|
"furniture": {
|
||||||
@ -30,14 +30,35 @@
|
|||||||
"$ref": "#/texts/3"
|
"$ref": "#/texts/3"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"$ref": "#/texts/4"
|
"$ref": "#/groups/0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/texts/6"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"content_layer": "body",
|
"content_layer": "body",
|
||||||
"name": "_root_",
|
"name": "_root_",
|
||||||
"label": "unspecified"
|
"label": "unspecified"
|
||||||
},
|
},
|
||||||
"groups": [],
|
"groups": [
|
||||||
|
{
|
||||||
|
"self_ref": "#/groups/0",
|
||||||
|
"parent": {
|
||||||
|
"$ref": "#/body"
|
||||||
|
},
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"$ref": "#/texts/4"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"$ref": "#/texts/5"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"content_layer": "body",
|
||||||
|
"name": "details",
|
||||||
|
"label": "section"
|
||||||
|
}
|
||||||
|
],
|
||||||
"texts": [
|
"texts": [
|
||||||
{
|
{
|
||||||
"self_ref": "#/texts/0",
|
"self_ref": "#/texts/0",
|
||||||
@ -89,6 +110,30 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"self_ref": "#/texts/4",
|
"self_ref": "#/texts/4",
|
||||||
|
"parent": {
|
||||||
|
"$ref": "#/groups/0"
|
||||||
|
},
|
||||||
|
"children": [],
|
||||||
|
"content_layer": "body",
|
||||||
|
"label": "text",
|
||||||
|
"prov": [],
|
||||||
|
"orig": "Heading for the details element",
|
||||||
|
"text": "Heading for the details element"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"self_ref": "#/texts/5",
|
||||||
|
"parent": {
|
||||||
|
"$ref": "#/groups/0"
|
||||||
|
},
|
||||||
|
"children": [],
|
||||||
|
"content_layer": "body",
|
||||||
|
"label": "text",
|
||||||
|
"prov": [],
|
||||||
|
"orig": "Description of the details element.",
|
||||||
|
"text": "Description of the details element."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"self_ref": "#/texts/6",
|
||||||
"parent": {
|
"parent": {
|
||||||
"$ref": "#/body"
|
"$ref": "#/body"
|
||||||
},
|
},
|
||||||
|
@ -7,4 +7,8 @@ This is a regular paragraph.
|
|||||||
This is a third div
|
This is a third div
|
||||||
with a new line.
|
with a new line.
|
||||||
|
|
||||||
|
Heading for the details element
|
||||||
|
|
||||||
|
Description of the details element.
|
||||||
|
|
||||||
This is a fourth div with a bold paragraph.
|
This is a fourth div with a bold paragraph.
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -7,6 +7,10 @@
|
|||||||
<div>This is another div with text.</div>
|
<div>This is another div with text.</div>
|
||||||
<p>This is a regular paragraph.</p>
|
<p>This is a regular paragraph.</p>
|
||||||
<div>This is a third div<br/>with a new line.</div>
|
<div>This is a third div<br/>with a new line.</div>
|
||||||
|
<details>
|
||||||
|
<summary>Heading for the details element</summary>
|
||||||
|
<p>Description of the details element.</p>
|
||||||
|
</details>
|
||||||
<div><p>This is a fourth div with a <b>bold</b> paragraph.</p></div>
|
<div><p>This is a fourth div with a <b>bold</b> paragraph.</p></div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
145
tests/data/html/example_8.html
Normal file
145
tests/data/html/example_8.html
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<style>
|
||||||
|
table,
|
||||||
|
th,
|
||||||
|
td {
|
||||||
|
border: 1px solid black;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<h2>Pivot table with with 1 row header</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Year</th>
|
||||||
|
<th>Month</th>
|
||||||
|
<th>Revenue</th>
|
||||||
|
<th>Cost</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="6">2025</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>January</td>
|
||||||
|
<td>$134</td>
|
||||||
|
<td>$162</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>February</td>
|
||||||
|
<td>$150</td>
|
||||||
|
<td>$155</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>March</td>
|
||||||
|
<td>$160</td>
|
||||||
|
<td>$143</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>April</td>
|
||||||
|
<td>$210</td>
|
||||||
|
<td>$150</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>May</td>
|
||||||
|
<td>$280</td>
|
||||||
|
<td>$120</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>Pivot table with 2 row headers</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Year</th>
|
||||||
|
<th>Quarter</th>
|
||||||
|
<th>Month</th>
|
||||||
|
<th>Revenue</th>
|
||||||
|
<th>Cost</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="7">2025</th>
|
||||||
|
<th rowspan="4">Q1</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>January</td>
|
||||||
|
<td>$134</td>
|
||||||
|
<td>$162</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>February</td>
|
||||||
|
<td>$150</td>
|
||||||
|
<td>$155</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>March</td>
|
||||||
|
<td>$160</td>
|
||||||
|
<td>$143</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="3">Q2</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>April</td>
|
||||||
|
<td>$210</td>
|
||||||
|
<td>$150</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>May</td>
|
||||||
|
<td>$280</td>
|
||||||
|
<td>$120</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
<h2>Equivalent pivot table</h2>
|
||||||
|
|
||||||
|
<table>
|
||||||
|
<tr>
|
||||||
|
<th>Year</th>
|
||||||
|
<th>Quarter</th>
|
||||||
|
<th>Month</th>
|
||||||
|
<th>Revenue</th>
|
||||||
|
<th>Cost</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="8">2025</th>
|
||||||
|
<th rowspan="4">Q1</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>January</td>
|
||||||
|
<td>$134</td>
|
||||||
|
<td>$162</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>February</td>
|
||||||
|
<td>$150</td>
|
||||||
|
<td>$155</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>March</td>
|
||||||
|
<td>$160</td>
|
||||||
|
<td>$143</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<th rowspan="3">Q2</th>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>April</td>
|
||||||
|
<td>$210</td>
|
||||||
|
<td>$150</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td>May</td>
|
||||||
|
<td>$280</td>
|
||||||
|
<td>$120</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
@ -1 +1,83 @@
|
|||||||
{"_name": "", "type": "pdf-document", "description": {"title": null, "abstract": null, "authors": null, "affiliations": null, "subjects": null, "keywords": null, "publication_date": null, "languages": null, "license": null, "publishers": null, "url_refs": null, "references": null, "publication": null, "reference_count": null, "citation_count": null, "citation_date": null, "advanced": null, "analytics": null, "logs": [], "collection": null, "acquisition": null}, "file-info": {"filename": "ocr_test.pdf", "filename-prov": null, "document-hash": "80f38f5b87a84870681556176a9622186fd200dd32c5557be9e0c0af05b8bc61", "#-pages": 1, "collection-name": null, "description": null, "page-hashes": [{"hash": "14d896dc8bcb7ee7c08c0347eb6be8dcb92a3782501992f1ea14d2e58077d4e3", "model": "default", "page": 1}]}, "main-text": [{"prov": [{"bbox": [69.0, 688.5883585611979, 506.6666666666667, 767.2550252278646], "page": 1, "span": [0, 94], "__ref_s3_data": null}], "text": "Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package", "type": "paragraph", "payload": null, "name": "Text", "font": null}], "figures": [], "tables": [], "bitmaps": null, "equations": [], "footnotes": [], "page-dimensions": [{"height": 841.9216918945312, "page": 1, "width": 595.201171875}], "page-footers": [], "page-headers": [], "_s3_data": null, "identifiers": null}
|
{
|
||||||
|
"_name": "",
|
||||||
|
"type": "pdf-document",
|
||||||
|
"description": {
|
||||||
|
"title": null,
|
||||||
|
"abstract": null,
|
||||||
|
"authors": null,
|
||||||
|
"affiliations": null,
|
||||||
|
"subjects": null,
|
||||||
|
"keywords": null,
|
||||||
|
"publication_date": null,
|
||||||
|
"languages": null,
|
||||||
|
"license": null,
|
||||||
|
"publishers": null,
|
||||||
|
"url_refs": null,
|
||||||
|
"references": null,
|
||||||
|
"publication": null,
|
||||||
|
"reference_count": null,
|
||||||
|
"citation_count": null,
|
||||||
|
"citation_date": null,
|
||||||
|
"advanced": null,
|
||||||
|
"analytics": null,
|
||||||
|
"logs": [],
|
||||||
|
"collection": null,
|
||||||
|
"acquisition": null
|
||||||
|
},
|
||||||
|
"file-info": {
|
||||||
|
"filename": "ocr_test.pdf",
|
||||||
|
"filename-prov": null,
|
||||||
|
"document-hash": "80f38f5b87a84870681556176a9622186fd200dd32c5557be9e0c0af05b8bc61",
|
||||||
|
"#-pages": 1,
|
||||||
|
"collection-name": null,
|
||||||
|
"description": null,
|
||||||
|
"page-hashes": [
|
||||||
|
{
|
||||||
|
"hash": "14d896dc8bcb7ee7c08c0347eb6be8dcb92a3782501992f1ea14d2e58077d4e3",
|
||||||
|
"model": "default",
|
||||||
|
"page": 1
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"main-text": [
|
||||||
|
{
|
||||||
|
"prov": [
|
||||||
|
{
|
||||||
|
"bbox": [
|
||||||
|
69.0,
|
||||||
|
688.5883585611979,
|
||||||
|
506.6666666666667,
|
||||||
|
767.2550252278646
|
||||||
|
],
|
||||||
|
"page": 1,
|
||||||
|
"span": [
|
||||||
|
0,
|
||||||
|
94
|
||||||
|
],
|
||||||
|
"__ref_s3_data": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"text": "Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package",
|
||||||
|
"type": "paragraph",
|
||||||
|
"payload": null,
|
||||||
|
"name": "Text",
|
||||||
|
"font": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"figures": [],
|
||||||
|
"tables": [],
|
||||||
|
"bitmaps": null,
|
||||||
|
"equations": [],
|
||||||
|
"footnotes": [],
|
||||||
|
"page-dimensions": [
|
||||||
|
{
|
||||||
|
"height": 841.9216918945312,
|
||||||
|
"page": 1,
|
||||||
|
"width": 595.201171875
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"page-footers": [],
|
||||||
|
"page-headers": [],
|
||||||
|
"_s3_data": null,
|
||||||
|
"identifiers": null
|
||||||
|
}
|
File diff suppressed because one or more lines are too long
@ -1 +1,77 @@
|
|||||||
{"schema_name": "DoclingDocument", "version": "1.3.0", "name": "ocr_test", "origin": {"mimetype": "application/pdf", "binary_hash": 14853448746796404529, "filename": "ocr_test.pdf", "uri": null}, "furniture": {"self_ref": "#/furniture", "parent": null, "children": [], "content_layer": "furniture", "name": "_root_", "label": "unspecified"}, "body": {"self_ref": "#/body", "parent": null, "children": [{"cref": "#/texts/0"}], "content_layer": "body", "name": "_root_", "label": "unspecified"}, "groups": [], "texts": [{"self_ref": "#/texts/0", "parent": {"cref": "#/body"}, "children": [], "content_layer": "body", "label": "text", "prov": [{"page_no": 1, "bbox": {"l": 69.0, "t": 767.2550252278646, "r": 506.6666666666667, "b": 688.5883585611979, "coord_origin": "BOTTOMLEFT"}, "charspan": [0, 94]}], "orig": "Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package", "text": "Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package", "formatting": null, "hyperlink": null}], "pictures": [], "tables": [], "key_value_items": [], "form_items": [], "pages": {"1": {"size": {"width": 595.201171875, "height": 841.9216918945312}, "image": null, "page_no": 1}}}
|
{
|
||||||
|
"schema_name": "DoclingDocument",
|
||||||
|
"version": "1.3.0",
|
||||||
|
"name": "ocr_test",
|
||||||
|
"origin": {
|
||||||
|
"mimetype": "application/pdf",
|
||||||
|
"binary_hash": 14853448746796404529,
|
||||||
|
"filename": "ocr_test.pdf",
|
||||||
|
"uri": null
|
||||||
|
},
|
||||||
|
"furniture": {
|
||||||
|
"self_ref": "#/furniture",
|
||||||
|
"parent": null,
|
||||||
|
"children": [],
|
||||||
|
"content_layer": "furniture",
|
||||||
|
"name": "_root_",
|
||||||
|
"label": "unspecified"
|
||||||
|
},
|
||||||
|
"body": {
|
||||||
|
"self_ref": "#/body",
|
||||||
|
"parent": null,
|
||||||
|
"children": [
|
||||||
|
{
|
||||||
|
"cref": "#/texts/0"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"content_layer": "body",
|
||||||
|
"name": "_root_",
|
||||||
|
"label": "unspecified"
|
||||||
|
},
|
||||||
|
"groups": [],
|
||||||
|
"texts": [
|
||||||
|
{
|
||||||
|
"self_ref": "#/texts/0",
|
||||||
|
"parent": {
|
||||||
|
"cref": "#/body"
|
||||||
|
},
|
||||||
|
"children": [],
|
||||||
|
"content_layer": "body",
|
||||||
|
"label": "text",
|
||||||
|
"prov": [
|
||||||
|
{
|
||||||
|
"page_no": 1,
|
||||||
|
"bbox": {
|
||||||
|
"l": 69.0,
|
||||||
|
"t": 767.2550252278646,
|
||||||
|
"r": 506.6666666666667,
|
||||||
|
"b": 688.5883585611979,
|
||||||
|
"coord_origin": "BOTTOMLEFT"
|
||||||
|
},
|
||||||
|
"charspan": [
|
||||||
|
0,
|
||||||
|
94
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"orig": "Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package",
|
||||||
|
"text": "Docling bundles PDF document conversion to JSON and Markdown in an easy self contained package",
|
||||||
|
"formatting": null,
|
||||||
|
"hyperlink": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pictures": [],
|
||||||
|
"tables": [],
|
||||||
|
"key_value_items": [],
|
||||||
|
"form_items": [],
|
||||||
|
"pages": {
|
||||||
|
"1": {
|
||||||
|
"size": {
|
||||||
|
"width": 595.201171875,
|
||||||
|
"height": 841.9216918945312
|
||||||
|
},
|
||||||
|
"image": null,
|
||||||
|
"page_no": 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
File diff suppressed because one or more lines are too long
@ -293,6 +293,7 @@ def verify_conversion_result_v1(
|
|||||||
generate: bool = False,
|
generate: bool = False,
|
||||||
ocr_engine: Optional[str] = None,
|
ocr_engine: Optional[str] = None,
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
indent: int = 2,
|
||||||
):
|
):
|
||||||
PageList = TypeAdapter(List[Page])
|
PageList = TypeAdapter(List[Page])
|
||||||
|
|
||||||
@ -323,11 +324,13 @@ def verify_conversion_result_v1(
|
|||||||
if generate: # only used when re-generating truth
|
if generate: # only used when re-generating truth
|
||||||
pages_path.parent.mkdir(parents=True, exist_ok=True)
|
pages_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(pages_path, "w") as fw:
|
with open(pages_path, "w") as fw:
|
||||||
fw.write(json.dumps(doc_pred_pages, default=pydantic_encoder))
|
fw.write(
|
||||||
|
json.dumps(doc_pred_pages, default=pydantic_encoder, indent=indent)
|
||||||
|
)
|
||||||
|
|
||||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(json_path, "w") as fw:
|
with open(json_path, "w") as fw:
|
||||||
fw.write(json.dumps(doc_pred, default=pydantic_encoder))
|
fw.write(json.dumps(doc_pred, default=pydantic_encoder, indent=indent))
|
||||||
|
|
||||||
md_path.parent.mkdir(parents=True, exist_ok=True)
|
md_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(md_path, "w") as fw:
|
with open(md_path, "w") as fw:
|
||||||
@ -377,6 +380,7 @@ def verify_conversion_result_v2(
|
|||||||
generate: bool = False,
|
generate: bool = False,
|
||||||
ocr_engine: Optional[str] = None,
|
ocr_engine: Optional[str] = None,
|
||||||
fuzzy: bool = False,
|
fuzzy: bool = False,
|
||||||
|
indent: int = 2,
|
||||||
):
|
):
|
||||||
PageList = TypeAdapter(List[Page])
|
PageList = TypeAdapter(List[Page])
|
||||||
|
|
||||||
@ -405,11 +409,13 @@ def verify_conversion_result_v2(
|
|||||||
if generate: # only used when re-generating truth
|
if generate: # only used when re-generating truth
|
||||||
pages_path.parent.mkdir(parents=True, exist_ok=True)
|
pages_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(pages_path, "w") as fw:
|
with open(pages_path, "w") as fw:
|
||||||
fw.write(json.dumps(doc_pred_pages, default=pydantic_encoder))
|
fw.write(
|
||||||
|
json.dumps(doc_pred_pages, default=pydantic_encoder, indent=indent)
|
||||||
|
)
|
||||||
|
|
||||||
json_path.parent.mkdir(parents=True, exist_ok=True)
|
json_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(json_path, "w") as fw:
|
with open(json_path, "w") as fw:
|
||||||
fw.write(json.dumps(doc_pred, default=pydantic_encoder))
|
fw.write(json.dumps(doc_pred, default=pydantic_encoder, indent=indent))
|
||||||
|
|
||||||
md_path.parent.mkdir(parents=True, exist_ok=True)
|
md_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
with open(md_path, "w") as fw:
|
with open(md_path, "w") as fw:
|
||||||
|
Loading…
Reference in New Issue
Block a user