Skip to content

Commit

Permalink
Merge branch 'main' of github.com:DS4SD/docling into cau/vis-and-prof…
Browse files Browse the repository at this point in the history
…iling-options
  • Loading branch information
cau-git committed Oct 28, 2024
2 parents 747a190 + 189d3c2 commit a00f01c
Show file tree
Hide file tree
Showing 8 changed files with 310 additions and 282 deletions.
54 changes: 29 additions & 25 deletions docling/backend/html_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,6 @@ def analyse_element(self, element, idx, doc):
def get_direct_text(self, item):
"""Get the direct text of the <li> element (ignoring nested lists)."""
text = item.find(string=True, recursive=False)

if isinstance(text, str):
return text.strip()

Expand All @@ -149,21 +148,20 @@ def extract_text_recursively(self, item):
if isinstance(item, str):
return [item]

result.append(self.get_direct_text(item))

try:
# Iterate over the children (and their text and tails)
for child in item:
try:
# Recursively get the child's text content
result.extend(self.extract_text_recursively(child))
except:
pass
except:
_log.warn("item has no children")
pass

return " ".join(result)
if item.name not in ["ul", "ol"]:
try:
# Iterate over the children (and their text and tails)
for child in item:
try:
# Recursively get the child's text content
result.extend(self.extract_text_recursively(child))
except:
pass
except:
_log.warn("item has no children")
pass

return "".join(result) + " "

def handle_header(self, element, idx, doc):
"""Handles header tags (h1, h2, etc.)."""
Expand Down Expand Up @@ -255,22 +253,28 @@ def handle_listitem(self, element, idx, doc):

if nested_lists:
name = element.name
text = self.get_direct_text(element)
# Text in list item can be hidden within hierarchy, hence
# we need to extract it recursively
text = self.extract_text_recursively(element)
# Flatten text, remove break lines:
text = text.replace("\n", "").replace("\r", "")
text = " ".join(text.split()).strip()

marker = ""
enumerated = False
if parent_list_label == GroupLabel.ORDERED_LIST:
marker = str(index_in_list)
enumerated = True

# create a list-item
self.parents[self.level + 1] = doc.add_list_item(
text=text,
enumerated=enumerated,
marker=marker,
parent=self.parents[self.level],
)
self.level += 1
if len(text) > 0:
# create a list-item
self.parents[self.level + 1] = doc.add_list_item(
text=text,
enumerated=enumerated,
marker=marker,
parent=self.parents[self.level],
)
self.level += 1

self.walk(element, doc)

Expand Down
27 changes: 23 additions & 4 deletions docling/backend/md_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,29 @@ def iterate_elements(self, element, depth=0, doc=None, parent_element=None):
doc_label = DocItemLabel.TITLE
else:
doc_label = DocItemLabel.SECTION_HEADER
snippet_text = element.children[0].children.strip()

parent_element = doc.add_text(
label=doc_label, parent=parent_element, text=snippet_text
)
# Header could have arbitrary inclusion of bold, italic or emphasis,
# hence we need to traverse the tree to get full text of a header
strings = []

# Define a recursive function to traverse the tree
def traverse(node):
# Check if the node has a "children" attribute
if hasattr(node, "children"):
# If "children" is a list, continue traversal
if isinstance(node.children, list):
for child in node.children:
traverse(child)
# If "children" is text, add it to header text
elif isinstance(node.children, str):
strings.append(node.children)

traverse(element)
snippet_text = "".join(strings)
if len(snippet_text) > 0:
parent_element = doc.add_text(
label=doc_label, parent=parent_element, text=snippet_text
)

elif isinstance(element, marko.block.List):
self.close_table(doc)
Expand Down Expand Up @@ -286,6 +304,7 @@ def convert(self) -> DoclingDocument:
parsed_ast = marko_parser.parse(self.markdown)
# Start iterating from the root of the AST
self.iterate_elements(parsed_ast, 0, doc, None)
self.process_inline_text(None, doc) # handle last hanging inline text
else:
raise RuntimeError(
f"Cannot convert md with {self.document_hash} because the backend failed to init."
Expand Down
4 changes: 2 additions & 2 deletions docs/examples/batch_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
_log = logging.getLogger(__name__)

USE_V2 = True
USE_LEGACY = False
USE_LEGACY = True


def export_documents(
Expand Down Expand Up @@ -78,7 +78,7 @@ def export_documents(
with (output_dir / f"{doc_filename}.legacy.doctags.txt").open(
"w", encoding="utf-8"
) as fp:
fp.write(conv_res.legacy_document.export_to_doctags())
fp.write(conv_res.legacy_document.export_to_document_tokens())

elif conv_res.status == ConversionStatus.PARTIAL_SUCCESS:
_log.info(
Expand Down
37 changes: 21 additions & 16 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ torchvision = [
######################
python = "^3.10"
pydantic = "^2.0.0"
docling-core = "^2.1.0"
docling-core = "^2.2.1"
docling-ibm-models = "^2.0.1"
deepsearch-glm = "^0.26.1"
filetype = "^1.2.0"
Expand Down
14 changes: 7 additions & 7 deletions tests/data/groundtruth/docling_v2/2203.01017v2.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,13 +139,13 @@ tention encoding is then multiplied to the encoded image to produce a feature fo

The output features for each table cell are then fed into the feed-forward network (FFN). The FFN consists of a Multi-Layer Perceptron (3 layers with ReLU activation function) that predicts the normalized coordinates for the bounding box of each table cell. Finally, the predicted bounding boxes are classified based on whether they are empty or not using a linear layer.

Loss Functions. We formulate a multi-task loss Eq. 2 to train our network. The Cross-Entropy loss (denoted as l$_{s}$ ) is used to train the Structure Decoder which predicts the structure tokens. As for the Cell BBox Decoder it is trained with a combination of losses denoted as l$_{box}$ . l$_{box}$ consists of the generally used l$_{1}$ loss for object detection and the IoU loss ( l$_{iou}$ ) to be scale invariant as explained in [25]. In comparison to DETR, we do not use the Hungarian algorithm [15] to match the predicted bounding boxes with the ground-truth boxes, as we have already achieved a one-toone match through two steps: 1) Our token input sequence is naturally ordered, therefore the hidden states of the table data cells are also in order when they are provided as input to the Cell BBox Decoder , and 2) Our bounding boxes generation mechanism (see Sec. 3) ensures a one-to-one mapping between the cell content and its bounding box for all post-processed datasets.
Loss Functions. We formulate a multi-task loss Eq. 2 to train our network. The Cross-Entropy loss (denoted as l$\_{s}$ ) is used to train the Structure Decoder which predicts the structure tokens. As for the Cell BBox Decoder it is trained with a combination of losses denoted as l$\_{box}$ . l$\_{box}$ consists of the generally used l$\_{1}$ loss for object detection and the IoU loss ( l$\_{iou}$ ) to be scale invariant as explained in [25]. In comparison to DETR, we do not use the Hungarian algorithm [15] to match the predicted bounding boxes with the ground-truth boxes, as we have already achieved a one-toone match through two steps: 1) Our token input sequence is naturally ordered, therefore the hidden states of the table data cells are also in order when they are provided as input to the Cell BBox Decoder , and 2) Our bounding boxes generation mechanism (see Sec. 3) ensures a one-to-one mapping between the cell content and its bounding box for all post-processed datasets.

The loss used to train the TableFormer can be defined as following:

l$_{box}$ = λ$_{iou}$l$_{iou}$ + λ$_{l}$$_{1}$ l = λl$_{s}$ + (1 - λ ) l$_{box}$ (1)
l$\_{box}$ = λ$\_{iou}$l$\_{iou}$ + λ$\_{l}$$\_{1}$ l = λl$\_{s}$ + (1 - λ ) l$\_{box}$ (1)

where λ ∈ [0, 1], and λ$_{iou}$, λ$_{l}$$_{1}$ ∈$_{R}$ are hyper-parameters.
where λ ∈ [0, 1], and λ$\_{iou}$, λ$\_{l}$$\_{1}$ ∈$\_{R}$ are hyper-parameters.

## 5. Experimental Results

Expand Down Expand Up @@ -175,9 +175,9 @@ We also share our baseline results on the challenging SynthTabNet dataset. Throu

The Tree-Edit-Distance-Based Similarity (TEDS) metric was introduced in [37]. It represents the prediction, and ground-truth as a tree structure of HTML tags. This similarity is calculated as:

TEDS ( T$_{a}$, T$_{b}$ ) = 1 - EditDist ( T$_{a}$, T$_{b}$ ) max ( | T$_{a}$ | , | T$_{b}$ | ) (3)
TEDS ( T$\_{a}$, T$\_{b}$ ) = 1 - EditDist ( T$\_{a}$, T$\_{b}$ ) max ( | T$\_{a}$ | , | T$\_{b}$ | ) (3)

where T$_{a}$ and T$_{b}$ represent tables in tree structure HTML format. EditDist denotes the tree-edit distance, and | T | represents the number of nodes in T .
where T$\_{a}$ and T$\_{b}$ represent tables in tree structure HTML format. EditDist denotes the tree-edit distance, and | T | represents the number of nodes in T .

## 5.4. Quantitative Analysis

Expand Down Expand Up @@ -376,9 +376,9 @@ Here is a step-by-step description of the prediction postprocessing:
- 3.a. If all IOU scores in a column are below the threshold, discard all predictions (structure and bounding boxes) for that column.
- 4. Find the best-fitting content alignment for the predicted cells with good IOU per each column. The alignment of the column can be identified by the following formula:

alignment = arg min c { D$_{c}$ } D$_{c}$ = max { x$_{c}$ } - min { x$_{c}$ } (4)
alignment = arg min c { D$\_{c}$ } D$\_{c}$ = max { x$\_{c}$ } - min { x$\_{c}$ } (4)

where c is one of { left, centroid, right } and x$_{c}$ is the xcoordinate for the corresponding point.
where c is one of { left, centroid, right } and x$\_{c}$ is the xcoordinate for the corresponding point.

- 5. Use the alignment computed in step 4, to compute the median x -coordinate for all table columns and the me-

Expand Down
4 changes: 2 additions & 2 deletions tests/data/groundtruth/docling_v2/2305.03393v1.md
Original file line number Diff line number Diff line change
Expand Up @@ -153,15 +153,15 @@ Table 2. TSR and cell detection results compared between OTSL and HTML on the Pu

To illustrate the qualitative differences between OTSL and HTML, Figure 5 demonstrates less overlap and more accurate bounding boxes with OTSL. In Figure 6, OTSL proves to be more effective in handling tables with longer token sequences, resulting in even more precise structure prediction and bounding boxes.

Fig. 5. The OTSL model produces more accurate bounding boxes with less overlap (E) than the HTML model (D), when predicting the structure of a sparse table (A), at twice the inference speed because of shorter sequence length (B),(C). "PMC2807444_006_00.png" PubTabNet. μ
Fig. 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. μ

<!-- image -->

μ


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.
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.

<!-- image -->

Expand Down
Loading

0 comments on commit a00f01c

Please sign in to comment.