1010import re
1111from 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
1522from linkml_reference_validator .etl .extract .base import Extractor , ExtractorRegistry
1623from linkml_reference_validator .etl .rules import ARTICLE_BODY_SELECTORS
4350KEPT_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+
4686def 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 & 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
81257class HTMLExtractor (Extractor ):
82258 """Extract readable text from HTML markup, as bytes or as a string.
0 commit comments