Skip to content
Open
Show file tree
Hide file tree
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
16 changes: 11 additions & 5 deletions docreader/parser/epub_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
23 changes: 21 additions & 2 deletions docreader/tests/test_epub_preamble_order.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"<html><head><title>Ch</title></head><body>{body}</body></html>"
# 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'<html xmlns="http://www.w3.org/1999/xhtml">'
f"<head><title>Ch</title></head><body>{body}</body></html>"
).encode(),
)
book.add_item(chapter)
book.spine = [chapter]
book.add_item(epub.EpubNcx())
Expand All @@ -36,6 +45,16 @@ def test_leading_heading_is_still_the_chapter_title(self):
content = _parse("<h1>Section A</h1><p>Body of A.</p>")
self.assertIn("## Section A\n\nBody of A.", content)

def test_image_before_the_first_heading_stays_before_it(self):
content = _parse(
'<p><img src="https://example.invalid/cover.png" alt="Frontispiece" /></p>'
"<h1>Section A</h1><p>Body of A.</p>"
)
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()
Loading