From 21f02c9fe3d0cda084bae26ac5b4ea1750716835 Mon Sep 17 00:00:00 2001 From: lanqing431 <359744414+lanqing431@users.noreply.github.com> Date: Mon, 30 Nov 2026 05:32:54 -0500 Subject: [PATCH] fix(docreader): preserve illustrations before EPUB chapter titles --- docreader/parser/epub_parser.py | 16 +++++++++----- docreader/tests/test_epub_preamble_order.py | 23 +++++++++++++++++++-- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/docreader/parser/epub_parser.py b/docreader/parser/epub_parser.py index efd9f5985ef..2b8e097da40 100644 --- a/docreader/parser/epub_parser.py +++ b/docreader/parser/epub_parser.py @@ -267,12 +267,18 @@ def _process_chapter( html_content = epub.EpubItem.get_content(html_item) soup = BeautifulSoup(html_content, "lxml") title_tag = soup.find(["h1", "h2"]) - if title_tag and any( - text.strip() and not text.find_parent("head") - for text in title_tag.find_all_previous(string=True) + if title_tag and ( + any( + text.strip() and not text.find_parent("head") + for text in title_tag.find_all_previous(string=True) + ) + or any( + image.get("src") and image.find_parent("body") + for image in title_tag.find_all_previous("img") + ) ): - # Text comes before the first heading. Lifting the heading to - # the top would put that text under it, so keep the order. + # Keep introductory content before the first heading instead of + # moving the heading ahead of the text or illustrations. title_tag.name = "h2" return self._html_to_markdown( str(soup.body), diff --git a/docreader/tests/test_epub_preamble_order.py b/docreader/tests/test_epub_preamble_order.py index 4443445c2bd..fe91f337bc3 100644 --- a/docreader/tests/test_epub_preamble_order.py +++ b/docreader/tests/test_epub_preamble_order.py @@ -11,8 +11,17 @@ def _parse(body): book.set_identifier("x") book.set_title("Book") book.set_language("en") - chapter = epub.EpubHtml(title="Ch", file_name="text/ch1.xhtml") - chapter.content = f"Ch{body}" + # EpubHtml adds a doctype and an XML declaration. Store the XHTML verbatim + # so those prologue nodes don't count as text before the chapter heading. + chapter = epub.EpubItem( + uid="chapter", + file_name="text/ch1.xhtml", + media_type="application/xhtml+xml", + content=( + f'' + f"Ch{body}" + ).encode(), + ) book.add_item(chapter) book.spine = [chapter] book.add_item(epub.EpubNcx()) @@ -36,6 +45,16 @@ def test_leading_heading_is_still_the_chapter_title(self): content = _parse("

Section A

Body of A.

") self.assertIn("## Section A\n\nBody of A.", content) + def test_image_before_the_first_heading_stays_before_it(self): + content = _parse( + '

Frontispiece

' + "

Section A

Body of A.

" + ) + self.assertLess( + content.index("![Frontispiece]("), content.index("## Section A") + ) + self.assertLess(content.index("## Section A"), content.index("Body of A.")) + if __name__ == "__main__": unittest.main()