Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use new add_code in html backend and add more typing hints #850

Merged
merged 1 commit into from
Jan 31, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 18 additions & 18 deletions docling/backend/html_backend.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import logging
from io import BytesIO
from pathlib import Path
from typing import Set, Union
from typing import Optional, Set, Union

from bs4 import BeautifulSoup
from bs4 import BeautifulSoup, Tag
from docling_core.types.doc import (
DocItemLabel,
DoclingDocument,
Expand All @@ -24,7 +24,7 @@ class HTMLDocumentBackend(DeclarativeDocumentBackend):
def __init__(self, in_doc: "InputDocument", path_or_stream: Union[BytesIO, Path]):
super().__init__(in_doc, path_or_stream)
_log.debug("About to init HTML backend...")
self.soup = None
self.soup: Optional[Tag] = None
# HTML file:
self.path_or_stream = path_or_stream
# Initialise the parents for the hierarchy
Expand Down Expand Up @@ -89,7 +89,7 @@ def convert(self) -> DoclingDocument:
)
return doc

def walk(self, element, doc):
def walk(self, element: Tag, doc: DoclingDocument):
try:
# Iterate over elements in the body of the document
for idx, element in enumerate(element.children):
Expand All @@ -106,7 +106,7 @@ def walk(self, element, doc):

return doc

def analyse_element(self, element, idx, doc):
def analyse_element(self, element: Tag, idx: int, doc: DoclingDocument):
"""
if element.name!=None:
_log.debug("\t"*self.level, idx, "\t", f"{element.name} ({self.level})")
Expand Down Expand Up @@ -136,7 +136,7 @@ def analyse_element(self, element, idx, doc):
else:
self.walk(element, doc)

def get_direct_text(self, item):
def get_direct_text(self, item: Tag):
"""Get the direct text of the <li> element (ignoring nested lists)."""
text = item.find(string=True, recursive=False)
if isinstance(text, str):
Expand All @@ -145,7 +145,7 @@ def get_direct_text(self, item):
return ""

# Function to recursively extract text from all child nodes
def extract_text_recursively(self, item):
def extract_text_recursively(self, item: Tag):
result = []

if isinstance(item, str):
Expand All @@ -166,7 +166,7 @@ def extract_text_recursively(self, item):

return "".join(result) + " "

def handle_header(self, element, idx, doc):
def handle_header(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles header tags (h1, h2, etc.)."""
hlevel = int(element.name.replace("h", ""))
slevel = hlevel - 1
Expand Down Expand Up @@ -208,17 +208,17 @@ def handle_header(self, element, idx, doc):
level=hlevel,
)

def handle_code(self, element, idx, doc):
def handle_code(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles monospace code snippets (pre)."""
if element.text is None:
return
text = element.text.strip()
label = DocItemLabel.CODE
if len(text) == 0:
return
doc.add_code(parent=self.parents[self.level], label=label, text=text)
doc.add_code(parent=self.parents[self.level], text=text)

def handle_paragraph(self, element, idx, doc):
def handle_paragraph(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles paragraph tags (p)."""
if element.text is None:
return
Expand All @@ -228,7 +228,7 @@ def handle_paragraph(self, element, idx, doc):
return
doc.add_text(parent=self.parents[self.level], label=label, text=text)

def handle_list(self, element, idx, doc):
def handle_list(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles list tags (ul, ol) and their list items."""

if element.name == "ul":
Expand All @@ -250,7 +250,7 @@ def handle_list(self, element, idx, doc):
self.parents[self.level + 1] = None
self.level -= 1

def handle_listitem(self, element, idx, doc):
def handle_listitem(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles listitem tags (li)."""
nested_lists = element.find(["ul", "ol"])

Expand Down Expand Up @@ -304,7 +304,7 @@ def handle_listitem(self, element, idx, doc):
else:
_log.warn("list-item has no text: ", element)

def handle_table(self, element, idx, doc):
def handle_table(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles table tags."""

nested_tables = element.find("table")
Expand Down Expand Up @@ -377,7 +377,7 @@ def handle_table(self, element, idx, doc):

doc.add_table(data=data, parent=self.parents[self.level])

def get_list_text(self, list_element, level=0):
def get_list_text(self, list_element: Tag, level=0):
"""Recursively extract text from <ul> or <ol> with proper indentation."""
result = []
bullet_char = "*" # Default bullet character for unordered lists
Expand All @@ -403,7 +403,7 @@ def get_list_text(self, list_element, level=0):

return result

def extract_table_cell_text(self, cell):
def extract_table_cell_text(self, cell: Tag):
"""Extract text from a table cell, including lists with indents."""
contains_lists = cell.find(["ul", "ol"])
if contains_lists is None:
Expand All @@ -414,7 +414,7 @@ def extract_table_cell_text(self, cell):
)
return cell.text

def handle_figure(self, element, idx, doc):
def handle_figure(self, element: Tag, idx: int, doc: DoclingDocument):
"""Handles image tags (img)."""

# Extract the image URI from the <img> tag
Expand All @@ -437,6 +437,6 @@ def handle_figure(self, element, idx, doc):
caption=fig_caption,
)

def handle_image(self, element, idx, doc):
def handle_image(self, element: Tag, idx, doc: DoclingDocument):
"""Handles image tags (img)."""
doc.add_picture(parent=self.parents[self.level], caption=None)