Skip to content

Commit ab58697

Browse files
committed
Keep all of an HTML article region's text, not only its <p> text (#121)
HTMLExtractor returned only <p> text whenever a scope held any <p>, so lists, tables, headings and bare <div> text were dropped from every HTML full-text path (PMC, OpenAlex, downloaded HTML), and an unclosed or block-holding <p> repeated and welded its children. The scope is now flattened with the same block-aware walk html_to_text uses. HTML_FULL_TEXT_CACHE_VERSION goes to 2 so cached HTML text is re-fetched. A version-1 entry already passed landing-page rejection, so when its refresh fails it is now served stale like other content types instead of withheld: otherwise this fix would remove the evidence of every HTML entry that cannot be re-fetched, such as a PMC-only article. Unstamped entries are still withheld. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Qm4PkMsSN3FVpzvBdZYahC
1 parent 9a3b58e commit ab58697

9 files changed

Lines changed: 214 additions & 49 deletions

File tree

‎docs/how-to/fetch-full-text-and-pdfs.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -405,13 +405,17 @@ fetcher does not crawl repository download links. If every provider completes
405405
without usable text or an error, the reference retains its original abstract
406406
and records `full_text_attempted: true`.
407407

408-
New `full_text_html` cache entries carry `html_full_text_version: 1`. Older
409-
Markdown HTML full-text entries without this stamp are refreshed on their next
410-
validation read. This migration covers all providers because cached plain text
408+
New `full_text_html` cache entries carry `html_full_text_version: 2`. Entries
409+
with an older stamp, or none, are refreshed on their next validation read.
410+
Version 2 keeps all of an article region's text rather than only its `<p>`
411+
text, so lists, tables, headings and bare `<div>` text can be quoted. This migration covers all providers because cached plain text
411412
cannot establish which HTML body structure was present. It does not invalidate
412413
current PDF, XML, or abstract caches.
413414

414-
If refreshing an old HTML entry fails, validation does **not** fall back to that
415+
If refreshing an entry stamped `html_full_text_version: 1` fails, validation
416+
falls back to it with a warning, as for other content types: it is a checked
417+
article body, though it may lack list and table text. If refreshing an entry with
418+
no stamp fails, validation does **not** fall back to that
415419
entry: its text may be repository metadata rather than article evidence. The
416420
file remains untouched for inventory/export, and the next validation run retries
417421
recovery. Once the source is available, normal fetching replaces it with a

‎src/linkml_reference_validator/etl/extract/html.py‎

Lines changed: 17 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,10 @@ def html_to_text(content: str) -> str:
124124
a browser would render them. Entities are unescaped.
125125
126126
Unlike :class:`HTMLExtractor`, which serves article text, nothing is
127-
narrowed to ``<article>`` or ``<main>`` and no ``<p>``-only shortcut is
128-
taken. Every text node of the sanitized markup appears, contiguous, in
129-
the result, so a quote that matched the markup still matches, and a quote
130-
through a link or bold text now matches too.
127+
narrowed to ``<article>`` or ``<main>``. Every text node of the sanitized
128+
markup appears, contiguous, in the result, so a quote that matched the
129+
markup still matches, and a quote through a link or bold text now matches
130+
too.
131131
132132
Examples:
133133
>>> html_to_text('<p>Produced by <a href="/x">the City of Flint</a>.</p>')
@@ -257,9 +257,10 @@ def _cell_text(cell: Tag) -> str:
257257
class HTMLExtractor(Extractor):
258258
"""Extract readable text from HTML markup, as bytes or as a string.
259259
260-
Prefers an ``<article>`` or main content region; falls back to all paragraph
261-
text, then to the whole document text. Callers holding an already-parsed
262-
region of their own use :meth:`extract_scope` instead.
260+
Prefers an ``<article>`` or main content region, else the whole document.
261+
All of the region's text is kept, a line per block: paragraphs, headings,
262+
list items, table rows and bare ``<div>`` text alike (#121). Callers holding
263+
an already-parsed region of their own use :meth:`extract_scope` instead.
263264
264265
Whitespace around inline markup is preserved, so text spanning italicised
265266
gene symbols survives extraction intact.
@@ -426,38 +427,16 @@ def _extract_scope(self, scope: Tag) -> Optional[str]:
426427
# Dropped here rather than in extract(), because the PMC paths enter
427428
# through this method and a JSON-LD blob or stylesheet landing in
428429
# cached article text would corrupt every snippet checked against it.
429-
# bs4's get_text() also skips Script/Stylesheet strings by default,
430-
# but that is a library default to rely on, not a guarantee this
431-
# extractor makes.
430+
# Required, not defensive: _lines reads a <script>'s text like any
431+
# other string.
432432
for tag in scope.find_all(["script", "style"]):
433433
tag.decompose()
434434

435-
# Before either branch, so both agree: <br> carries no text of its own,
436-
# so bare get_text() would weld the lines it separates into
437-
# "Line oneLine two" - the same welding this extractor exists to avoid.
438-
for line_break in scope.find_all("br"):
439-
line_break.replace_with("\n")
440-
441-
paragraphs = scope.find_all("p")
442-
if paragraphs:
443-
# get_text() with no arguments, deliberately: strip=True would trim
444-
# every markup-delimited run before joining them, welding words to
445-
# their neighbours across inline tags. "(<i>GUSB</i>, <i>GRN</i>,
446-
# and <i>NEU1</i>)" became "(GUSB,GRN, andNEU1)", breaking every
447-
# curated snippet that spans an italicised gene symbol. Trimming
448-
# the finished paragraph instead keeps the source's own spacing.
449-
texts = (p.get_text().strip() for p in paragraphs)
450-
text = "\n\n".join(t for t in texts if t)
451-
if text:
452-
return text
453-
454-
# Same hazard as the paragraph branch, one level down: a blanket
455-
# separator lands between *every* pair of markup-delimited runs, so
456-
# "(<i>GUSB</i>, <i>GRN</i>)" would come out as "(\nGUSB\n,\nGRN\n)".
457-
# Marking block boundaries first means get_text() can then run bare,
458-
# keeping the source's own spacing inside each block.
459-
for block in scope.find_all(BLOCK_LEVEL_TAGS):
460-
block.insert_after("\n")
461-
462-
text = scope.get_text().strip()
435+
# The same block-aware walk html_to_text uses: every text node of the
436+
# scope appears once, each block on a line of its own, and inline
437+
# markup is unwrapped in place so "(<i>GUSB</i>, <i>GRN</i>)" keeps
438+
# the source's own spacing. Lists, tables, headings and bare <div>
439+
# text are kept: a scope's <p> text alone dropped them, and a nested
440+
# or unclosed <p> repeated and welded its children (#121).
441+
text = "\n".join(_lines(scope))
463442
return text if text else None

‎src/linkml_reference_validator/etl/reference_fetcher.py‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,18 @@
106106
#: repository metadata rather than an article. PDF/XML caches need no refresh.
107107
#: Downloaded/raw HTML is structurally checked; pre-extracted text supplied by
108108
#: PMC or a configured text provider is trusted under FullTextLocation's contract.
109-
HTML_FULL_TEXT_CACHE_VERSION = 1
109+
#: Version 2: an article region keeps all of its text, not only its ``<p>``
110+
#: text, so lists, tables, headings and bare ``<div>`` text are no longer
111+
#: dropped, and unclosed ``<p>`` no longer repeats and welds text (#121).
112+
#: Version-1 text lacks them, so a correct quote of a list item fails against it.
113+
HTML_FULL_TEXT_CACHE_VERSION = 2
114+
115+
#: The first ``html_full_text_version`` whose entries passed landing-page
116+
#: rejection. An entry stamped at least this is a checked article body, so when
117+
#: a refresh fails it is served stale like any other type, though it may lack
118+
#: text a later version extracts. Only entries below it, which may be landing
119+
#: pages, are withheld.
120+
HTML_VERIFIED_BODY_VERSION = 1
110121

111122
#: XML extraction changes only XML caches, independent of HTML acceptance.
112123
#: 1: JATS tables are rendered. 2: nested paragraphs are emitted once, list
@@ -1740,6 +1751,7 @@ def _load_from_disk(
17401751
and reference is not None
17411752
and reference.content_type == "full_text_html"
17421753
and self._is_stale_cache_entry(content_text)
1754+
and not self._is_verified_html_body(content_text)
17431755
):
17441756
logger.warning(
17451757
"Refusing stale HTML full text for %s: it may be a repository "
@@ -1866,6 +1878,30 @@ def _is_figure_file_reference(reference_id: str) -> bool:
18661878
and resolve_format(None, reference_id, None) in FIGURE_CONTENT_TYPES
18671879
)
18681880

1881+
@classmethod
1882+
def _is_verified_html_body(cls, content_text: str) -> bool:
1883+
"""Whether an HTML entry's stamp shows it passed landing-page rejection.
1884+
1885+
Args:
1886+
content_text: The cache file's contents, including frontmatter
1887+
1888+
Returns:
1889+
True if ``html_full_text_version`` is at least
1890+
``HTML_VERIFIED_BODY_VERSION``
1891+
1892+
Examples:
1893+
>>> ReferenceFetcher._is_verified_html_body(
1894+
... "---\\nhtml_full_text_version: 1\\n---\\nBody.")
1895+
True
1896+
>>> ReferenceFetcher._is_verified_html_body("---\\ntitle: T\\n---\\nBody.")
1897+
False
1898+
"""
1899+
split = cls._split_frontmatter(content_text)
1900+
if split is None:
1901+
return False
1902+
match = re.search(r"^html_full_text_version:\s*(\d+)\s*$", split[0], re.MULTILINE)
1903+
return match is not None and int(match.group(1)) >= HTML_VERIFIED_BODY_VERSION
1904+
18691905
@classmethod
18701906
def _is_stale_cache_entry(cls, content_text: str) -> bool:
18711907
"""Report whether extraction or format-specific full-text processing needs refreshing.

‎tests/fixtures/PMC_TEST002.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
reference_id: PMC:TEST002
33
extractor_version: 1
4-
html_full_text_version: 1
4+
html_full_text_version: 2
55
title: TP53 mutations in cancer development
66
authors:
77
- Johnson K

‎tests/fixtures/PMID_TEST003.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
reference_id: PMID:TEST003
33
extractor_version: 1
4-
html_full_text_version: 1
4+
html_full_text_version: 2
55
title: Comprehensive analysis of gene Z expression patterns
66
authors:
77
- Garcia L

‎tests/test_html_fulltext_acceptance.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@
99
from bs4 import BeautifulSoup
1010

1111
from linkml_reference_validator.etl.extract.html import HTMLExtractor
12-
from linkml_reference_validator.etl.reference_fetcher import ReferenceFetcher
12+
from linkml_reference_validator.etl.reference_fetcher import (
13+
HTML_FULL_TEXT_CACHE_VERSION,
14+
ReferenceFetcher,
15+
)
1316
from linkml_reference_validator.models import (
1417
FullTextLocation,
1518
ReferenceContent,
@@ -403,7 +406,7 @@ def test_preextracted_html_body_is_a_trusted_provider_contract(tmp_path):
403406
ref, FullTextLocation(text=text, format_hint="html"), "custom"
404407
)
405408
assert ref.content == text
406-
assert ref.metadata["html_full_text_version"] == 1
409+
assert ref.metadata["html_full_text_version"] == HTML_FULL_TEXT_CACHE_VERSION
407410

408411

409412
def test_explicit_body_with_unfamiliar_heading_is_accepted(tmp_path, html_server):

‎tests/test_html_scope_text.py‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
"""HTML article text keeps everything in the scope, not just its ``<p>`` text (issue #121).
2+
3+
``HTMLExtractor`` used to return only ``<p>`` text whenever a scope held any
4+
``<p>``, so lists, tables, headings and bare ``<div>`` text were dropped and a
5+
correct quote of them failed. Nested or unclosed ``<p>`` also repeated and
6+
welded text. Every HTML full-text path (PMC, OpenAlex, downloaded HTML) goes
7+
through this extractor, so these tests pin the shared behaviour.
8+
"""
9+
10+
from linkml_reference_validator.etl.extract.html import HTMLExtractor
11+
from linkml_reference_validator.etl.reference_fetcher import (
12+
EXTRACTOR_CACHE_VERSION,
13+
HTML_FULL_TEXT_CACHE_VERSION,
14+
ReferenceFetcher,
15+
)
16+
from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig
17+
from linkml_reference_validator.validation.supporting_text_validator import SupportingTextValidator
18+
19+
MIXED = (
20+
b"<article><h2>Results</h2><p>We found three things.</p>"
21+
b"<ul><li>POLG variants cause ataxia</li></ul>"
22+
b"<table><tr><td>GENE1</td><td>0.05</td></tr></table>"
23+
b"<div>Unwrapped finding text.</div></article>"
24+
)
25+
26+
27+
def test_text_outside_paragraphs_is_kept():
28+
"""Headings, list items, table cells and bare div text all reach the output."""
29+
text = HTMLExtractor().extract(MIXED) or ""
30+
for expected in (
31+
"Results",
32+
"We found three things.",
33+
"POLG variants cause ataxia",
34+
"GENE1",
35+
"0.05",
36+
"Unwrapped finding text.",
37+
):
38+
assert expected in text
39+
40+
41+
def test_blocks_stay_on_separate_lines():
42+
"""A block never welds onto its neighbour."""
43+
text = HTMLExtractor().extract(MIXED) or ""
44+
assert "things.POLG" not in text
45+
assert "ataxiaGENE1" not in text
46+
47+
48+
def test_unclosed_paragraphs_are_neither_repeated_nor_welded():
49+
"""html.parser nests unclosed ``<p>``; each paragraph still appears once, on its own."""
50+
text = HTMLExtractor().extract(b"<article><p>Para one<p>Para two</article>") or ""
51+
assert text.count("Para two") == 1
52+
assert "Para onePara" not in text
53+
54+
55+
def test_blocks_inside_a_paragraph_are_separated():
56+
"""A ``<div>`` inside a ``<p>`` starts a new line instead of welding."""
57+
text = HTMLExtractor().extract(
58+
b"<article><p>Intro<div>block A</div><div>block B</div></p></article>"
59+
) or ""
60+
assert "Introblock" not in text
61+
assert "block Ablock" not in text
62+
assert all(part in text for part in ("Intro", "block A", "block B"))
63+
64+
65+
def test_inline_markup_keeps_its_spacing():
66+
"""The fix that motivated the old shortcut still holds: italics do not weld."""
67+
text = HTMLExtractor().extract(
68+
b"<article><p>near (<i>GUSB</i>, <i>GRN</i>, and <i>NEU1</i>) here</p></article>"
69+
)
70+
assert text == "near (GUSB, GRN, and NEU1) here"
71+
72+
73+
def test_a_list_item_quote_validates():
74+
"""End to end: a correct quote of a list item is found in the extracted text."""
75+
text = HTMLExtractor().extract(MIXED) or ""
76+
reference = ReferenceContent(reference_id="PMID:1", content=text)
77+
match = SupportingTextValidator(ReferenceValidationConfig()).find_text_in_reference(
78+
"POLG variants cause ataxia", reference
79+
)
80+
assert match.found
81+
82+
83+
def test_html_entries_from_the_paragraph_only_extractor_are_stale():
84+
"""Cached HTML full text from before this fix is re-fetched, not served."""
85+
entry = (
86+
"---\n"
87+
"reference_id: PMID:1\n"
88+
"content_type: full_text_html\n"
89+
f"extractor_version: {EXTRACTOR_CACHE_VERSION}\n"
90+
f"html_full_text_version: {HTML_FULL_TEXT_CACHE_VERSION - 1}\n"
91+
"---\nBody."
92+
)
93+
assert HTML_FULL_TEXT_CACHE_VERSION >= 2
94+
assert ReferenceFetcher._is_stale_cache_entry(entry)
95+
96+
97+
def _fetch_with_source_down(tmp_path, html_stamp: str):
98+
"""Fetch a cached HTML entry while the source yields nothing (the stale fallback)."""
99+
from unittest.mock import patch
100+
101+
(tmp_path / "PMID_30929739.md").write_text(
102+
"---\nreference_id: PMID:30929739\ntitle: A paper\n"
103+
f"extractor_version: {EXTRACTOR_CACHE_VERSION}\n{html_stamp}"
104+
"content_type: full_text_html\n---\n\n## Content\n\nA body sentence.\n",
105+
encoding="utf-8",
106+
)
107+
fetcher = ReferenceFetcher(
108+
ReferenceValidationConfig(
109+
cache_dir=tmp_path, email="me@example.org", fetch_full_text=False
110+
)
111+
)
112+
113+
class _Source:
114+
def fetch(self, identifier, config):
115+
return None
116+
117+
with patch(
118+
"linkml_reference_validator.etl.reference_fetcher"
119+
".ReferenceSourceRegistry.get_source",
120+
return_value=_Source,
121+
):
122+
return fetcher.fetch("PMID:30929739")
123+
124+
125+
def test_verified_html_from_an_older_extractor_is_served_when_refresh_fails(tmp_path):
126+
"""A version-1 entry is a checked article body, only incomplete: serve it stale.
127+
128+
Withholding it would turn this extractor fix into lost evidence for every
129+
HTML entry that cannot be re-fetched, such as a PMC-only article (#95).
130+
"""
131+
reference = _fetch_with_source_down(tmp_path, "html_full_text_version: 1\n")
132+
assert reference is not None
133+
assert "A body sentence." in (reference.content or "")
134+
135+
136+
def test_unverified_html_is_still_withheld_when_refresh_fails(tmp_path):
137+
"""An unstamped entry may be a landing page, so it is still not served."""
138+
assert _fetch_with_source_down(tmp_path, "") is None

‎tests/test_jats_tables.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from linkml_reference_validator.etl import rules
88
from linkml_reference_validator.etl.extract.xml import XMLExtractor
99
from linkml_reference_validator.etl.reference_fetcher import (
10+
HTML_FULL_TEXT_CACHE_VERSION,
1011
XML_EXTRACTION_CACHE_VERSION,
1112
ReferenceFetcher,
1213
)
@@ -200,7 +201,10 @@ def fetch(self, identifier, config):
200201

201202
@pytest.mark.parametrize(
202203
"kind,stamp",
203-
[("full_text_pdf", ""), ("full_text_html", "html_full_text_version: 1\n")],
204+
[
205+
("full_text_pdf", ""),
206+
("full_text_html", f"html_full_text_version: {HTML_FULL_TEXT_CACHE_VERSION}\n"),
207+
],
204208
)
205209
def test_xml_migration_does_not_refresh_other_formats(tmp_path, kind, stamp):
206210
"""Current HTML and PDF caches remain usable without an XML version."""

‎tests/test_no_cache_downgrade.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
import pytest
4141

4242
from linkml_reference_validator.etl.reference_fetcher import (
43+
HTML_FULL_TEXT_CACHE_VERSION,
4344
XML_EXTRACTION_CACHE_VERSION,
4445
ReferenceFetcher,
4546
)
@@ -67,7 +68,7 @@ def _write_cache(cache_dir, reference_id, content_type, body, stamped=False):
6768
if content_type == "full_text_xml":
6869
stamp += f"xml_extraction_version: {XML_EXTRACTION_CACHE_VERSION}\n"
6970
elif content_type == "full_text_html":
70-
stamp += "html_full_text_version: 1\n"
71+
stamp += f"html_full_text_version: {HTML_FULL_TEXT_CACHE_VERSION}\n"
7172
path = cache_dir / f"{reference_id.replace(':', '_')}.md"
7273
path.write_text(
7374
f"---\nreference_id: {reference_id}\n{stamp}"

0 commit comments

Comments
 (0)