Skip to content

Commit 35fac0f

Browse files
authored
Merge pull request #103 from linkml/url-cache-readable-text
Cache url: HTML pages as readable text, so quotes through links and bold text match
2 parents 510d524 + 39c4d42 commit 35fac0f

8 files changed

Lines changed: 478 additions & 45 deletions

File tree

‎docs/how-to/validate-urls.md‎

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ When a reference field contains a URL, the validator:
1616

1717
1. Fetches the web page content
1818
2. Extracts the page title (see [Titles](#titles))
19-
3. Sanitizes HTML and caches the content for future validations
19+
3. Converts HTML to readable text and caches it for future validations
2020
4. Validates your supporting text against the page content
2121

2222
## URL Format
@@ -80,20 +80,29 @@ When the validator encounters a URL reference, it:
8080
The fetcher stores:
8181

8282
- **Title**: See [Titles](#titles)
83-
- **Content**: Sanitized HTML for HTML pages; plain text and XML as received;
83+
- **Content**: Readable text for HTML pages; plain text and XML as received;
8484
extracted text for PDFs
8585
- **Content type**: `url` for pages, `full_text_pdf` for PDFs with text
8686

87-
HTML is sanitized before it is cached, because caches are often committed to
88-
public repositories and page scripts routinely carry signed asset URLs and API
89-
keys. `<script>`, `<style>`, `<noscript>` and `<template>` elements and HTML
90-
comments are removed. So are `<meta>`, `<link>` and `<base>`, which hold nothing
91-
but attributes. Every other tag attribute is removed except `rowspan`,
92-
`colspan` and `scope`, which carry table structure. Body markup and text are
93-
kept. There is no HTML-to-text conversion, so tag names can still surface
94-
during normalization. If validation fails because tags interrupt the text,
95-
consider extracting plain text and validating against a local `file:`
96-
reference instead.
87+
HTML is converted to readable text before it is cached. A quote copied from
88+
the page then matches even when it runs through a link, bold or italic text,
89+
and a cached page can be read, and diffed, line by line:
90+
91+
- Inline tags (`<a>`, `<b>`, `<em>`, `<span>`, ...) are removed and their
92+
text is kept in place.
93+
- Block-level tags (`<p>`, `<li>`, `<h1>`-`<h6>`, `<div>`, `<br>`, ...) start
94+
a new line.
95+
- A table row is one line, its cells separated by ` | `. Normalization drops
96+
the `|`, so a quote copied from a rendered row with its cells separated by
97+
spaces still matches.
98+
- `<pre>` keeps its whitespace. Elsewhere whitespace collapses to one space.
99+
- Entities such as `&amp;` are unescaped.
100+
101+
The whole page is kept, including navigation, sidebars and footers; it is not
102+
narrowed to the article body. Because caches are often committed to public
103+
repositories and page scripts routinely carry signed asset URLs and API keys,
104+
`<script>`, `<style>`, `<noscript>` and `<template>` elements and HTML comments
105+
are removed with their text, and no tag attribute reaches the cache.
97106

98107
#### Titles
99108

@@ -176,11 +185,11 @@ URL validation is designed for static web pages. It may not work well with:
176185

177186
### Raw Content
178187

179-
The validator stores sanitized page markup, not extracted text. For HTML pages:
188+
The validator stores the page's text, not its markup. For HTML pages:
180189

181-
- HTML tags are preserved in the cache, without attributes other than
182-
`rowspan`, `colspan` and `scope`
183-
- The text normalization during validation handles most cases
190+
- Text that only appears in an attribute, such as an image's `alt` text, is
191+
not kept
192+
- Text inside `<noscript>` or `<template>` is not kept
184193
- Complex HTML layouts may require careful text extraction
185194

186195
### No Rendering

‎docs/troubleshooting.md‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -902,11 +902,14 @@ rather than as `unavailable`, so it falls outside this stamp and is not
902902
re-tested. Clear such entries by hand if you were running that setting before
903903
this version.
904904

905-
`url:` entries carry their own stamp, `url_source_version: 1`. Version 1 is
905+
`url:` entries carry their own stamp, `url_source_version`. Version 1 is
906906
two URLSource changes: HTML is sanitized before caching, so page scripts,
907907
comments and attributes stop reaching the cache (issue #92), and a PDF's title
908908
is recovered from a publisher landing page or its embedded metadata rather than
909-
set to its URL (issue #93). A `url:` entry with a missing or older stamp is
909+
set to its URL (issue #93). Version 2 caches an HTML page as readable text
910+
rather than markup, so a quote that runs through a link or bold text matches
911+
(issue #102). Every quote that matched the version 1 markup still matches the
912+
text, provided the page itself has not changed. A `url:` entry with a missing or older stamp is
910913
re-fetched once on the next validation fetch. If the page cannot be reached,
911914
the old entry is still served and is not rewritten, so a later run retries.
912915
Other sources are unaffected. With `trust_cached_entries` set, old entries are
@@ -920,6 +923,18 @@ stop matching once the entry is re-fetched. If the same text appears elsewhere
920923
on the page, nothing changes. If it does not, cite a source that carries it,
921924
such as the `PMID:` or `DOI:` of the article.
922925

926+
**The version 2 refresh rewrites every cached HTML page.** Each `url:` HTML
927+
entry changes from one line of markup to many lines of text, so expect a large
928+
diff in a committed cache. The refresh fetches each page again, so a page that
929+
has changed or gone since it was cached can stop supporting a quote; an
930+
unreachable page keeps its old entry, as above. To keep that diff reviewable,
931+
refresh in a commit of its own: right after upgrading, run your usual
932+
validation on an otherwise unchanged checkout and commit only the rewritten
933+
cache files, before any curation changes. Entries are refreshed only as a
934+
validation uses them (see
935+
[Cached references re-fetched after upgrading](#cached-references-re-fetched-after-upgrading)),
936+
so a page no validation cites keeps its old entry until one does.
937+
923938
**A cache-wide refresh adds one line to every enriched entry.** Both index
924939
providers now set `access_type` where they previously left it unset, so a
925940
refreshed public entry gains a `full_text_access_type: open` line. It means the

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

Lines changed: 185 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,14 @@
1010
import re
1111
from typing import Optional, Union
1212

13-
from bs4 import BeautifulSoup, Comment, Tag # type: ignore
13+
from bs4 import ( # type: ignore
14+
BeautifulSoup,
15+
CData,
16+
Comment,
17+
NavigableString,
18+
Tag,
19+
)
20+
from bs4.element import PreformattedString # type: ignore
1421

1522
from linkml_reference_validator.etl.extract.base import Extractor, ExtractorRegistry
1623
from linkml_reference_validator.etl.rules import ARTICLE_BODY_SELECTORS
@@ -43,12 +50,46 @@
4350
KEPT_ATTRIBUTES = frozenset({"rowspan", "colspan", "scope"})
4451

4552

53+
#: Tags that start a new line in :func:`html_to_text`: the extractor's block
54+
#: tags, plus the document-level and form containers a whole page also has.
55+
#: ``td`` and ``th`` stay in it although a row's cells are joined on one line
56+
#: by :func:`_row_cells`: that path is taken only inside a ``<tr>``, so a cell
57+
#: met anywhere else still gets a line of its own.
58+
TEXT_BREAK_TAGS = frozenset(BLOCK_LEVEL_TAGS) | {
59+
"body", "caption", "center", "details", "dialog", "fieldset", "form",
60+
"head", "html", "legend", "menu", "option", "summary", "tbody", "textarea",
61+
"tfoot", "thead", "title",
62+
}
63+
64+
#: Between the cells of a table row. Normalization drops punctuation, so a
65+
#: quote copied from a rendered row, with the cells separated by spaces, still
66+
#: matches. Empty cells are left out, so a row's columns need not line up with
67+
#: the row above; this is text for matching and reading, not a table.
68+
CELL_SEPARATOR = " | "
69+
70+
71+
#: Marks, on the walk's stack, the end of a block-level element.
72+
_BLOCK_END = object()
73+
74+
75+
def _without_non_content(content: str) -> BeautifulSoup:
76+
"""Parse a page, dropping ``NON_CONTENT_TAGS`` and comments."""
77+
soup = BeautifulSoup(content, "html.parser")
78+
for tag in soup.find_all(NON_CONTENT_TAGS):
79+
if not tag.decomposed: # already gone with an enclosing non-content tag
80+
tag.decompose()
81+
for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):
82+
comment.extract()
83+
return soup
84+
85+
4686
def sanitize_html(content: str) -> str:
4787
"""Strip an HTML page to its body markup and text, for caching.
4888
4989
Drops ``NON_CONTENT_TAGS`` and comments, and every attribute not in
50-
``KEPT_ATTRIBUTES``. Markup is kept, unlike :class:`HTMLExtractor`, which
51-
flattens to plain text; this is for ``url:`` pages stored as HTML.
90+
``KEPT_ATTRIBUTES``. Markup is kept, unlike :class:`HTMLExtractor` and
91+
:func:`html_to_text`, which flatten to plain text. ``url:`` pages are
92+
cached through :func:`html_to_text` since #102.
5293
5394
Examples:
5495
>>> sanitize_html('<p class="x" onclick="f()">Hi<script>k=1</script><!-- c --></p>')
@@ -60,12 +101,7 @@ def sanitize_html(content: str) -> str:
60101
>>> sanitize_html("<pre><b>x</b> <b>y</b></pre>")
61102
'<pre><b>x</b> <b>y</b></pre>'
62103
"""
63-
soup = BeautifulSoup(content, "html.parser")
64-
for tag in soup.find_all(NON_CONTENT_TAGS):
65-
if not tag.decomposed: # already gone with an enclosing non-content tag
66-
tag.decompose()
67-
for comment in soup.find_all(string=lambda text: isinstance(text, Comment)):
68-
comment.extract()
104+
soup = _without_non_content(content)
69105
for tag in soup.find_all(True):
70106
tag.attrs = {k: v for k, v in tag.attrs.items() if k in KEPT_ATTRIBUTES}
71107
# Removed elements leave runs of indentation behind. Collapse each
@@ -77,6 +113,146 @@ def sanitize_html(content: str) -> str:
77113
text.replace_with("\n" if "\n" in text else " ")
78114
return str(soup)
79115

116+
117+
def html_to_text(content: str) -> str:
118+
r"""Flatten a whole HTML page to readable text, for caching ``url:`` pages.
119+
120+
Drops what :func:`sanitize_html` drops, then unwraps every inline tag in
121+
place and starts a new line at each block-level tag and ``<br>``. A table
122+
row becomes one line, its cells joined by ``CELL_SEPARATOR``. ``<pre>``
123+
keeps its whitespace; elsewhere whitespace runs collapse to one space, as
124+
a browser would render them. Entities are unescaped.
125+
126+
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.
131+
132+
Examples:
133+
>>> html_to_text('<p>Produced by <a href="/x">the City of Flint</a>.</p>')
134+
'Produced by the City of Flint.'
135+
>>> html_to_text("<p>The <b>Flint water crisis</b> was</p><ul><li>one</li><li>two</li></ul>")
136+
'The Flint water crisis was\none\ntwo'
137+
>>> html_to_text("<p>Line one<br>Line two</p>")
138+
'Line one\nLine two'
139+
>>> html_to_text("<table><tr><th>Gene</th><th>Finding</th></tr><tr><td>POLG</td><td>A &amp; B</td></tr></table>")
140+
'Gene | Finding\nPOLG | A & B'
141+
>>> html_to_text("<pre>x y\n z</pre>")
142+
'x y\n z'
143+
>>> html_to_text("<p>near (<i>GUSB</i>, <i>GRN</i>)\n here</p><script>k=1</script>")
144+
'near (GUSB, GRN) here'
145+
"""
146+
return "\n".join(_lines(_without_non_content(content)))
147+
148+
149+
def _lines(node: Tag) -> list[str]:
150+
"""The lines of ``node``'s text, the last one included.
151+
152+
Lines outside ``<pre>`` are never blank and carry no leading or trailing
153+
whitespace. A ``<pre>`` block's lines are kept as written, blank ones and
154+
indentation included, since its whitespace is part of its text.
155+
156+
Walks the tree with a stack of its own rather than by recursion, so a page
157+
nested deeper than Python's recursion limit is flattened like any other.
158+
Only a table nested in a table cell recurses, through :func:`_row_cells`.
159+
"""
160+
lines: list[str] = []
161+
line: list[str] = []
162+
# Children are pushed in reverse so they pop in document order. A block's
163+
# closing break is pushed beneath its children, to end its last line.
164+
stack: list[object] = list(reversed(list(node.children)))
165+
while stack:
166+
child = stack.pop()
167+
if child is _BLOCK_END:
168+
_end_line(lines, line)
169+
elif isinstance(child, PreformattedString) and not isinstance(child, CData):
170+
continue # a doctype, declaration or processing instruction: not text
171+
elif isinstance(child, NavigableString):
172+
line.append(re.sub(r"\s+", " ", str(child)))
173+
elif not isinstance(child, Tag):
174+
continue
175+
elif child.name == "br":
176+
_end_line(lines, line)
177+
elif child.name == "pre":
178+
_end_line(lines, line)
179+
lines.extend(_pre_text(child).strip("\n").splitlines())
180+
elif child.name == "tr":
181+
_end_line(lines, line)
182+
row = CELL_SEPARATOR.join(cell for cell in _row_cells(child) if cell)
183+
if row:
184+
lines.append(row)
185+
elif child.name in TEXT_BREAK_TAGS:
186+
_end_line(lines, line)
187+
stack.append(_BLOCK_END)
188+
stack.extend(reversed(list(child.children)))
189+
else:
190+
stack.extend(reversed(list(child.children)))
191+
_end_line(lines, line)
192+
return lines
193+
194+
195+
def _end_line(lines: list[str], line: list[str]) -> None:
196+
"""Move the line being built onto ``lines``, unless it holds only whitespace."""
197+
text = re.sub(r" +", " ", "".join(line)).strip()
198+
if text:
199+
lines.append(text)
200+
line.clear()
201+
202+
203+
def _pre_text(pre: Tag) -> str:
204+
r"""A ``<pre>`` block's text, whitespace kept and each ``<br>`` a line break.
205+
206+
``get_text()`` would ignore ``<br>`` and weld the words either side.
207+
208+
Examples:
209+
>>> _pre_text(BeautifulSoup("<pre>a<br>b <i>c</i></pre>", "html.parser").pre)
210+
'a\nb c'
211+
"""
212+
return "".join(
213+
"\n" if isinstance(node, Tag) else str(node)
214+
for node in pre.descendants
215+
if (isinstance(node, Tag) and node.name == "br")
216+
or type(node) is NavigableString
217+
or isinstance(node, CData)
218+
)
219+
220+
221+
def _row_cells(row: Tag) -> list[str]:
222+
"""The text of each cell in a table row, and of anything else it holds.
223+
224+
A cell may sit inside a wrapper, as in the ``<tr><form><td>`` of older
225+
layouts, and a row may hold stray text. Neither is dropped: the sanitized
226+
markup kept that text, so a quote may already match it.
227+
228+
Examples:
229+
>>> row = BeautifulSoup("<tr>x<form><td>a</td><td>b</td></form></tr>", "html.parser")
230+
>>> _row_cells(row.tr)
231+
['x', 'a', 'b']
232+
"""
233+
cells: list[str] = []
234+
for child in row.children:
235+
if isinstance(child, Tag) and child.name in ("td", "th"):
236+
cells.append(_cell_text(child))
237+
elif isinstance(child, Tag) and child.find(["td", "th"]) is not None:
238+
cells.extend(_row_cells(child))
239+
elif isinstance(child, Tag):
240+
cells.append(_cell_text(child))
241+
elif type(child) is NavigableString or isinstance(child, CData):
242+
cells.append(" ".join(child.split()))
243+
return cells
244+
245+
246+
def _cell_text(cell: Tag) -> str:
247+
"""One table cell's text on one line, whatever blocks it holds.
248+
249+
Examples:
250+
>>> _cell_text(BeautifulSoup("<td><p>a</p><p>b <i>c</i></p></td>", "html.parser").td)
251+
'a b c'
252+
"""
253+
return " ".join(_lines(cell))
254+
255+
80256
@ExtractorRegistry.register
81257
class HTMLExtractor(Extractor):
82258
"""Extract readable text from HTML markup, as bytes or as a string.

‎src/linkml_reference_validator/etl/reference_fetcher.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,10 @@
132132
#: URL (#93). Neither fix rewrites an entry already written, and both kinds of
133133
#: entry carry a current ``extractor_version``, so without this they would be
134134
#: served as they are forever. Stamped from ``reference.metadata``, like the
135-
#: HTML stamp, and only on a fresh URLSource fetch.
136-
URL_SOURCE_CACHE_VERSION = 1
135+
#: HTML stamp, and only on a fresh URLSource fetch. Version 2: HTML is cached as
136+
#: readable text rather than markup, so a quote through a link or bold text
137+
#: matches (#102).
138+
URL_SOURCE_CACHE_VERSION = 2
137139

138140
_FORMAT_TO_CONTENT_TYPE = {
139141
"pdf": "full_text_pdf",

‎src/linkml_reference_validator/etl/sources/url.py‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig
2121
from linkml_reference_validator.etl.sources.base import ReferenceSource, ReferenceSourceRegistry
2222
from linkml_reference_validator.etl.acquire import ContentAcquirer, sniff_format
23-
from linkml_reference_validator.etl.extract.html import sanitize_html
23+
from linkml_reference_validator.etl.extract.html import html_to_text
2424
from linkml_reference_validator.etl.extract.pdf import PDFExtractor
2525
from linkml_reference_validator.etl.rules import LANDING_PAGE_RULES
2626

@@ -37,10 +37,10 @@
3737
class URLSource(ReferenceSource):
3838
"""Fetch reference content from web URLs.
3939
40-
Fetches HTML and plain text content. HTML keeps its markup but is
41-
sanitized (see :func:`sanitize_html`) so page scripts and attributes do not
42-
reach the cache. Plain text and XML are stored as fetched. Content is cached
43-
to disk like other sources.
40+
Fetches HTML and plain text content. HTML is flattened to readable text
41+
(see :func:`html_to_text`), so page scripts and attributes do not reach the
42+
cache and a quote can run through a link or bold text. Plain text and XML
43+
are stored as fetched. Content is cached to disk like other sources.
4444
4545
Examples:
4646
>>> source = URLSource()
@@ -109,10 +109,10 @@ def fetch(
109109
)
110110

111111
content = self._decode(data, content_type_header)
112-
# Before sanitizing: citation_title lives in a <meta> attribute.
112+
# Before flattening: citation_title lives in a <meta> attribute.
113113
title = self._extract_title(content, url)
114114
if "html" in content_type_header or self._looks_like_html(data):
115-
content = sanitize_html(content)
115+
content = html_to_text(content)
116116

117117
return ReferenceContent(
118118
reference_id=f"url:{url}",

0 commit comments

Comments
 (0)