[bug] BeautifulSoup HTML/EPUB extraction inserts newlines inside inline headings and code tokens
What happened
The BeautifulSoup text conversion inserts a newline between every text node, including nodes separated only by inline styling. A span inside a heading, word, or syntax-highlighted code block changes the extracted content.
This affects two current paths with the same cause:
- HTML: the bs4 fallback when Trafilatura is unavailable or does not return usable content.
- EPUB: the preferred ebooklib + bs4 parser. This path does not use Trafilatura.
On unmodified master, a synthetic two-chapter source using Chapter <span>1</span> produces 0 detected chapters. Removing only the span markup produces 2. The styled source still exits successfully through the full CLI, including HTML --mode technical.
For code, this source:
<pre><code>if enabled:
<span>print</span>("ok")
</code></pre>becomes:
if enabled:
print
("ok")Compiling that extracted snippet raises IndentationError; the same snippet without the styling spans, and the current stdlib output for this fixture, compile successfully. No extracted code was executed.
What you expected
Inline presentation markup should leave text continuous: Chapter 1: Syntax, hypertext, and the original code lines/indentation. Structural boundaries should still separate headings, paragraphs, lists and table rows; table cells need their own separators.
The result should not depend on whether a chapter number or code token is wrapped in an inline element.
Source document
- Formats: synthetic HTML and EPUB 3; English; two content chapters.
- No private or copyrighted book was used.
- EPUB fixtures include a navigation document. Content manifest order and spine order agree, isolating this from #257. No EPUBCheck conformance result is claimed.
- Actual libraries:
beautifulsoup4 4.14.3,ebooklib 0.20; Trafilatura was absent, not mocked, in the full CLI reproduction. The HTML trace reported:Trying trafilatura... not available Trying BeautifulSoup (bs4)... OK
Repro
Run the following from the repository root in an environment with BeautifulSoup installed and without Trafilatura. This explicitly selects the affected HTML fallback; it does not claim that every successful Trafilatura extraction has this defect.
import importlib.util
from pathlib import Path
from book_to_skill.parsers.html import extract_html_content, _HTMLTextExtractor
from book_to_skill.utils import detect_structure
assert importlib.util.find_spec("trafilatura") is None
raw = (
'<html><body>'
'<h2>Chapter <span>1</span>: Syntax</h2>'
'<p>A hyper<span>text</span> term remains continuous.</p>'
'<h2>Chapter <span>2</span>: Safety</h2>'
'<p>Only retry when the failure is temporary.</p>'
'</body></html>'
)
Path("inline-continuity.html").write_text(raw, encoding="utf-8")
styled = extract_html_content(raw)
plain = extract_html_content(raw.replace("<span>", "").replace("</span>", ""))
fallback = _HTMLTextExtractor()
fallback.feed(raw)
print(repr(styled))
print("styled/control/stdlib chapters:",
detect_structure(styled)["chapters_detected"],
detect_structure(plain)["chapters_detected"],
detect_structure(fallback.get_text())["chapters_detected"])
assert "hyper\ntext" in styled
assert detect_structure(styled)["chapters_detected"] == 0
assert detect_structure(plain)["chapters_detected"] == 2
code = '<pre><code>if enabled:\n <span>print</span>("ok")\n</code></pre>'
extracted_code = extract_html_content(code)
print(repr(extracted_code))
try:
compile(extracted_code, "<synthetic-not-executed>", "exec")
except SyntaxError as error:
print(type(error).__name__, error.msg)Observed:
styled/control/stdlib chapters: 0 2 2
'if enabled:\n \nprint\n("ok")\n'
IndentationError expected an indented block after 'if' statement on line 1The CLI also persists the fragmented heading/word:
python scripts/extract.py inline-continuity.html --mode text --install-missing no
python scripts/extract.py inline-continuity.html --mode technical --install-missing noBoth modes returned 0 and recorded chapters_detected: 0, extraction_method: "html-parser" in my reproduction. The style-free control returned 0 with 2 detected chapters. Selecting technical mode does not route HTML through the PDF Docling branch.
For an independent EPUB reproduction, with real ebooklib installed:
from ebooklib import epub
from book_to_skill.parsers.epub import extract_with_ebooklib, extract_with_zipfile
from book_to_skill.utils import detect_structure
book = epub.EpubBook()
book.set_identifier("synthetic-inline-continuity")
book.set_title("Synthetic continuity")
book.set_language("en")
chapters = []
for n, title in [(1, "Syntax"), (2, "Safety")]:
chapter = epub.EpubHtml(title=title, file_name=f"c{n}.xhtml", lang="en")
chapter.content = (
f'<h2>Chapter <span>{n}</span>: {title}</h2>'
'<p>A hyper<span>text</span> term remains continuous.</p>'
)
book.add_item(chapter)
chapters.append(chapter)
book.toc = tuple(chapters)
book.add_item(epub.EpubNav())
book.spine = chapters
epub.write_epub("inline-continuity.epub", book)
preferred = extract_with_ebooklib("inline-continuity.epub")
fallback = extract_with_zipfile("inline-continuity.epub")
print("ebooklib/stdlib chapters:",
detect_structure(preferred)["chapters_detected"],
detect_structure(fallback)["chapters_detected"])
assert "hyper\ntext" in preferred
assert detect_structure(preferred)["chapters_detected"] == 0
assert detect_structure(fallback)["chapters_detected"] == 2Observed: ebooklib/stdlib chapters: 0 2. A separate EPUB ZIP fixture with matching manifest/spine order also reproduced this through the unmodified CLI (extraction_method: "ebooklib", 0 chapters).
Environment and precise source
- Windows 11; Python 3.12.14 for independent parser and full CLI reproductions.
- book-to-skill 1.4.0, master
c108d25b0cb58e1bdc361f3de02ed9f37075152f. - BeautifulSoup 4.14.3; ebooklib 0.20; Trafilatura absent.
- Repository source remained unchanged.
Root cause:
- HTML bs4 conversion calls
soup.get_text(separator="\n"). - ebooklib conversion uses the same call for each content document.
- Cleanup and structure detection do not reconstruct inline text. Corpus serialization therefore preserves the damaged input.
The existing inline continuity tests exercise _HTMLTextExtractor, while bs4 convergence checks a table fixture without inline-styled chapter numbers. Those tests can pass while these two production branches fragment inline text.
Impact
Inline spans are used for styled chapter numbers and syntax highlighting. Splitting them can:
- remove usable chapter-heading evidence from metadata and later source lookup;
- split words or API names, compromising exact search and extraction statistics;
- alter code lines/indentation before the generator reads them.
This is a demonstrated input-fidelity defect. I have not run a live generator and do not claim an observed downstream model failure or a measured prevalence across real books. It also does not imply every code example or every heading is affected: the fixture needs inline text-node boundaries.
Minimal repair and compatibility
Use block-aware HTML-to-text traversal for the bs4/ebooklib conversions: concatenate inline descendants, emit separators at actual block boundaries and br, and handle table cells/rows separately. Preserve whitespace verbatim inside pre/code. A shared routine could prevent the two paths diverging, provided their existing filtering behavior is preserved explicitly.
Do not simply switch to separator="": that can join adjacent blocks and destroy headings/table structure. Do not blindly substitute the current stdlib helper either: it has no preformatted state, and its deferred-boundary whitespace suppression can lose a leading whitespace-only node inside pre.
Keep EPUB document ordering as a separate concern (#257), keep the existing Trafilatura-first policy, and keep sanitization/path/security checks unchanged. Correctly extracting styled text will intentionally change output bytes, word/token statistics and chapter counts. No new runtime dependency or generator-spec growth is needed.
Alternatives
Until repaired, preconvert the material with a tool that preserves inline/block semantics, or provide a verified plain-text/Markdown version with headings and code intact. The current stdlib path preserves the specific fixtures above, but is not a universal workaround for preformatted whitespace or all HTML structures. Do not strip all markup without first accounting for block boundaries.
Acceptance and verification limits
- The styled and style-free fixtures retain identical heading/word text and both report 2 chapters through HTML bs4 and real ebooklib.
- Syntax-highlighted code retains the same lines/indentation as the source; the nonexecuted compile check succeeds. Include leading spaces before the first highlighted token and multiline nested spans.
- Adjacent heading/body blocks, explicit
br, lists and tab-separated table rows retain boundaries; inlineb/i/a/spanand entity decoding do not add separators or double-decode. - Existing HTML filtering and EPUB document selection are explicitly regression-tested rather than silently changed. Exercise actual unavailable-Trafilatura fallback and controlled empty/error fallback cases separately.
- Full CLI tests inspect persisted
full_text.txtand metadata, not only a text helper. Existing stdlib controls remain covered.
Independent direct/parser and CLI checks passed their defect assertions. The existing relevant parser tests also passed 20 tests with 4 skips in a separate Python 3.14 environment. The four skips were tests gated by pytest.importorskip("trafilatura") because that optional package was absent (primary success, empty/whitespace results, and exception); the not-installed fallback case executed. This is not a full-suite pass, a Trafilatura quality evaluation, an EPUBCheck result, or a live model experiment.
Deduplication: #107 fixed only stdlib block/inline behavior; #142 introduced Trafilatura and retained this fallback; #235/#251 concern optional-dependency CI coverage; #257 concerns EPUB item order. This report concerns text-node separators with correct item order. I checked all-state issue history and open PRs before submission and found no matching repair for these two conversion calls.
Source: virgiliojr94/book-to-skill