Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(docreader): keep the space held by a whitespace-only inline element (#3978)
Lukase7aaf8ae0260
diff --git a/docreader/parser/mhtml_parser.py b/docreader/parser/mhtml_parser.pyindex 8103d11f7..d79ecdd41 100644--- a/docreader/parser/mhtml_parser.py+++ b/docreader/parser/mhtml_parser.py@@ -31,6 +31,23 @@ _AD_DOMAINS = (_UNKNOWN_8BIT = frozenset({"unknown-8bit", "unknown"})+# Inline elements that markdownify renders as "" when their text is only+# whitespace, taking that whitespace with them.+_WHITESPACE_DROPPING_INLINE_TAGS = (+ "a",+ "b",+ "code",+ "del",+ "em",+ "i",+ "kbd",+ "s",+ "samp",+ "strong",+ "sub",+ "sup",+)+def _header_str(value) -> str:"""Normalize a MIME header to str, recovering 8-bit UTF-8 bytes.@@ -270,6 +287,7 @@ class MHTMLParser(BaseParser):self._strip_internal_links(soup)if image_aliases:self._rewrite_image_sources(soup, image_aliases, base_location)+ self._unwrap_whitespace_only_inline(soup)text_fallback = soup.get_text(separator="\n", strip=True)markdown_text = md(str(soup), heading_style="ATX")result = self._normalize_markdown(markdown_text)@@ -295,6 +313,19 @@ class MHTMLParser(BaseParser):"""Backward-compatible wrapper for existing internal callers and tests."""return self.html_to_markdown(html_content, image_aliases, base_location)+ @staticmethod+ def _unwrap_whitespace_only_inline(soup: BeautifulSoup) -> None:+ """Keep the whitespace held by an otherwise empty inline element.++ markdownify drops such an element together with its whitespace, so+ ``further<strong> </strong>reference`` became ``furtherreference``.+ Unwrapping leaves the whitespace as plain text. Innermost elements go+ first, so ``<b><i> </i></b>`` is unwrapped completely.+ """+ for tag in reversed(soup.find_all(_WHITESPACE_DROPPING_INLINE_TAGS)):+ if tag.find(True) is None and not tag.get_text().strip():+ tag.unwrap()+@staticmethoddef _normalize_markdown(markdown_text: str) -> str:text = markdown_text.replace("\r\n", "\n").replace("\r", "\n")diff --git a/docreader/tests/test_html_parser.py b/docreader/tests/test_html_parser.pyindex 0694f7da0..68edd9018 100644--- a/docreader/tests/test_html_parser.py+++ b/docreader/tests/test_html_parser.py@@ -58,6 +58,13 @@ class HTMLParserTest(unittest.TestCase):self.assertIn("[Guide](./guide.html)", document.content)self.assertIn("[Section](#section)", document.content)+ def test_parse_keeps_space_held_by_whitespace_only_inline_element(self):+ html = b"<p>further<strong> </strong>reference</p>"++ document = HTMLParser(file_name="space.html", file_type="html").parse(html)++ self.assertEqual("further reference", document.content)+def test_registry_routes_html_extensions_to_html_parser(self):self.assertIs(registry.get_parser_class("", "html"), HTMLParser)self.assertIs(registry.get_parser_class("", "htm"), HTMLParser)diff --git a/docreader/tests/test_mhtml_parser.py b/docreader/tests/test_mhtml_parser.pyindex 1d98fa761..a0bd050b0 100644--- a/docreader/tests/test_mhtml_parser.py+++ b/docreader/tests/test_mhtml_parser.py@@ -242,6 +242,38 @@ class MHTMLParserTest(unittest.TestCase):self.assertEqual(markdown, "alpha \nbeta")+ def test_html_to_markdown_keeps_whitespace_of_whitespace_only_inline_elements(self):+ parser = MHTMLParser(file_name="article.mhtml", file_type="mhtml")+ cases = {+ "<p>further<strong> </strong>reference</p>": "further reference",+ "<p><b>First</b><b> </b><b>Last</b></p>": "**First** **Last**",+ "<p>Hello<code> </code>world</p>": "Hello world",+ "<p>one<em> </em>two</p>": "one\xa0two",+ '<p>see<a href="https://example.com"> </a>here</p>': "see here",+ "<p>a<b><i> </i></b>b</p>": "a b",+ "<p>x<sub> </sub>y<sup> </sup>z<kbd> </kbd>w</p>": "x y z w",+ "<p>v<del> </del>w<s> </s>x<samp> </samp>y</p>": "v w x y",+ }+ for html_content, expected in cases.items():+ with self.subTest(html=html_content):+ self.assertEqual(parser._html_to_markdown(html_content), expected)++ def test_html_to_markdown_still_converts_inline_elements_with_content(self):+ markdown = MHTMLParser(+ file_name="article.mhtml", file_type="mhtml"+ )._html_to_markdown(+ "<p><strong>bold</strong> <code>code</code> <em>em</em> "+ '<del>gone</del> <a href="https://example.com">link</a> '+ "keep<b></b>empty "+ '<a href="https://example.com"><img alt="pic" src="https://example.com/a.png"></a></p>'+ )++ self.assertEqual(+ markdown,+ "**bold** `code` *em* ~~gone~~ [link](https://example.com) keepempty "+ "[](https://example.com)",+ )+def test_normalize_markdown_preserves_two_space_hard_break(self):markdown = MHTMLParser._normalize_markdown("alpha \nbeta")