Skip to content

Commit 3acefa1

Browse files
authored
Merge pull request #152 from linkml/ccr-65a5480d-pb91sk
Keep all HTML article text, and match µ with μ
2 parents 2324933 + c6421d8 commit 3acefa1

13 files changed

Lines changed: 392 additions & 67 deletions

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

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -405,14 +405,18 @@ 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-
entry: its text may be repository metadata rather than article evidence. The
415+
If refreshing an entry stamped `html_full_text_version: 1` or later fails,
416+
validation falls back to it with a warning, as for other content types: it is a
417+
checked article body, though it may lack list and table text. If refreshing an
418+
entry with no stamp fails, validation does **not** fall back to that entry: its
419+
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
418422
verified article or the available metadata/abstract. Other content types retain

‎docs/how-to/repair-validation-errors.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,10 @@ The distinct letters `Æ/æ` and `Œ/œ` remain distinct from `AE/ae` and `OE/oe
2626
Equating these letters would accept spelling changes beyond typographic repair.
2727
Validation uses an explicit ligature table instead of broad Unicode NFKC
2828
normalization so this change does not equate scientific notation such as `H₂O`
29-
with `H2O`, `10⁶` with `106`, or the micro sign `µ` with Greek `μ`.
29+
with `H2O` or `10⁶` with `106`. The micro sign `µ` and Greek `μ` *are* treated
30+
as the same letter, since sources use them interchangeably (`5 µM` matches
31+
`5 μM`), as are the variant Greek forms `ϕ ϵ ϑ ϐ ϖ ϰ ϱ` and the ordinary
32+
letters they stand for.
3033

3134
### Unmapped PDF glyphs do not match
3235

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

Lines changed: 37 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,22 @@
4646
#: are stripped they would remain only as empty tags.
4747
NON_CONTENT_TAGS = ("script", "style", "noscript", "template", "meta", "link", "base")
4848

49+
#: Bibliography containers inside an article region. A cited paper's title is
50+
#: not evidence for the citing article, so their text is never extracted:
51+
#: PLOS ``ol.references``, PMC ``section.ref-list``, Springer
52+
#: ``ol.c-article-references``, Wiley ``section.article-section__references``,
53+
#: and the DPUB-ARIA ``doc-bibliography`` role. Whole class tokens on block
54+
#: containers only: a substring match would also delete an inline citation
55+
#: marker or a wrapper such as ``body-with-references`` around the whole
56+
#: body. A layout not listed here keeps its bibliography text; extend the list
57+
#: as publishers are seen, never with a substring.
58+
BIBLIOGRAPHY_SELECTOR = (
59+
":is(section, div, ol, ul, aside)"
60+
":is(.ref-list, .references, .c-article-references,"
61+
" .article-section__references, .bibliography), "
62+
'[role="doc-bibliography"]'
63+
)
64+
4965
#: The only attributes that carry meaning for a quoted excerpt: table structure.
5066
KEPT_ATTRIBUTES = frozenset({"rowspan", "colspan", "scope"})
5167

@@ -124,10 +140,10 @@ def html_to_text(content: str) -> str:
124140
a browser would render them. Entities are unescaped.
125141
126142
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.
143+
narrowed to ``<article>`` or ``<main>``. Every text node of the sanitized
144+
markup appears, contiguous, in the result, so a quote that matched the
145+
markup still matches, and a quote through a link or bold text now matches
146+
too.
131147
132148
Examples:
133149
>>> html_to_text('<p>Produced by <a href="/x">the City of Flint</a>.</p>')
@@ -257,9 +273,10 @@ def _cell_text(cell: Tag) -> str:
257273
class HTMLExtractor(Extractor):
258274
"""Extract readable text from HTML markup, as bytes or as a string.
259275
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.
276+
Prefers an ``<article>`` or main content region, else the whole document.
277+
All of the region's text is kept, a line per block: paragraphs, headings,
278+
list items, table rows and bare ``<div>`` text alike (#121). Callers holding
279+
an already-parsed region of their own use :meth:`extract_scope` instead.
263280
264281
Whitespace around inline markup is preserved, so text spanning italicised
265282
gene symbols survives extraction intact.
@@ -426,38 +443,18 @@ def _extract_scope(self, scope: Tag) -> Optional[str]:
426443
# Dropped here rather than in extract(), because the PMC paths enter
427444
# through this method and a JSON-LD blob or stylesheet landing in
428445
# 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.
432-
for tag in scope.find_all(["script", "style"]):
433-
tag.decompose()
446+
# Required, not defensive: _lines reads a <script>'s or <noscript>'s
447+
# text like any other string. A bibliography goes too: before #121 its
448+
# entries were dropped only by accident, as non-<p> text.
449+
for tag in [*scope.find_all(NON_CONTENT_TAGS), *scope.select(BIBLIOGRAPHY_SELECTOR)]:
450+
if not tag.decomposed: # already gone with an enclosing tag
451+
tag.decompose()
434452

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()
453+
# The same block-aware walk html_to_text uses: every text node of the
454+
# scope appears once, each block on a line of its own, and inline
455+
# markup is unwrapped in place so "(<i>GUSB</i>, <i>GRN</i>)" keeps
456+
# the source's own spacing. Lists, tables, headings and bare <div>
457+
# text are kept: a scope's <p> text alone dropped them, and a nested
458+
# or unclosed <p> repeated and welded its children (#121).
459+
text = "\n".join(_lines(scope))
463460
return text if text else None

‎src/linkml_reference_validator/etl/reference_fetcher.py‎

Lines changed: 45 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,38 @@ 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+
Such an entry is served when a refresh fails, whatever made it stale
1886+
(an HTML, extractor or URL version bump): the refusal exists only for
1887+
the landing-page risk, which this stamp rules out. The stamp is read
1888+
with a regex, as ``_is_stale_cache_entry`` reads ``extractor_version``,
1889+
so damaged frontmatter elsewhere in the header cannot make this raise.
1890+
1891+
Args:
1892+
content_text: The cache file's contents, including frontmatter
1893+
1894+
Returns:
1895+
True if ``html_full_text_version`` is at least
1896+
``HTML_VERIFIED_BODY_VERSION``
1897+
1898+
Examples:
1899+
>>> ReferenceFetcher._is_verified_html_body(
1900+
... "---\\nhtml_full_text_version: 1\\n---\\nBody.")
1901+
True
1902+
>>> ReferenceFetcher._is_verified_html_body("---\\ntitle: T\\n---\\nBody.")
1903+
False
1904+
"""
1905+
split = cls._split_frontmatter(content_text)
1906+
if split is None:
1907+
return False
1908+
match = re.search(
1909+
r"^html_full_text_version:\s*(\d+)\s*(?:#.*)?$", split[0], re.MULTILINE
1910+
)
1911+
return match is not None and int(match.group(1)) >= HTML_VERIFIED_BODY_VERSION
1912+
18691913
@classmethod
18701914
def _is_stale_cache_entry(cls, content_text: str) -> bool:
18711915
"""Report whether extraction or format-specific full-text processing needs refreshing.

‎src/linkml_reference_validator/validation/supporting_text_validator.py‎

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,10 @@ def normalize_text(text: str) -> str:
738738
as I + J. Distinct letters Æ/æ and Œ/œ are preserved: equating them with
739739
AE/OE would broaden validation beyond typographic repair. An explicit
740740
table avoids broad NFKC normalization, which also changes scientific
741-
notation such as superscripts, subscripts, and the micro sign.
741+
notation such as superscripts and subscripts (``10⁶`` would read as
742+
``106``). The micro sign ``µ`` and the variant Greek forms (``ϕ ϵ ϑ ϐ
743+
ϖ ϰ ϱ``) are spelled out like the ordinary letters they stand for, since
744+
sources use them interchangeably: ``5 µM`` matches ``5 μM``.
742745
743746
Args:
744747
text: Text to normalize
@@ -767,8 +770,10 @@ def normalize_text(text: str) -> str:
767770
'p lt 0.05 5 pm 2 by neg2.5 fold'
768771
>>> SupportingTextValidator.normalize_text("IL-6, Ca2+-dependent, A -> B")
769772
'il 6 ca2 dependent a b'
770-
>>> SupportingTextValidator.normalize_text("Æ Œ æ œ H₂O 10⁶ µ")
771-
'æ œ æ œ h₂o 10⁶ µ'
773+
>>> SupportingTextValidator.normalize_text("Æ Œ æ œ H₂O 10⁶")
774+
'æ œ æ œ h₂o 10⁶'
775+
>>> SupportingTextValidator.normalize_text("5 µM") == SupportingTextValidator.normalize_text("5 μM")
776+
True
772777
"""
773778
# Only compatibility ligatures; do not apply general Unicode NFKC.
774779
ligature_map = {
@@ -777,29 +782,29 @@ def normalize_text(text: str) -> str:
777782
}
778783
text = text.translate({ord(ligature): expanded for ligature, expanded in ligature_map.items()})
779784

780-
# Greek letter mappings (both uppercase and lowercase)
785+
# Greek letter mappings: both cases, the micro sign and variant forms
781786
greek_map = {
782787
'α': 'alpha', 'Α': 'alpha',
783-
'β': 'beta', 'Β': 'beta',
788+
'β': 'beta', 'Β': 'beta', 'ϐ': 'beta',
784789
'γ': 'gamma', 'Γ': 'gamma',
785790
'δ': 'delta', 'Δ': 'delta',
786-
'ε': 'epsilon', 'Ε': 'epsilon',
791+
'ε': 'epsilon', 'Ε': 'epsilon', 'ϵ': 'epsilon',
787792
'ζ': 'zeta', 'Ζ': 'zeta',
788793
'η': 'eta', 'Η': 'eta',
789-
'θ': 'theta', 'Θ': 'theta',
794+
'θ': 'theta', 'Θ': 'theta', 'ϑ': 'theta',
790795
'ι': 'iota', 'Ι': 'iota',
791-
'κ': 'kappa', 'Κ': 'kappa',
796+
'κ': 'kappa', 'Κ': 'kappa', 'ϰ': 'kappa',
792797
'λ': 'lambda', 'Λ': 'lambda',
793-
'μ': 'mu', 'Μ': 'mu',
798+
'μ': 'mu', 'Μ': 'mu', 'µ': 'mu',
794799
'ν': 'nu', 'Ν': 'nu',
795800
'ξ': 'xi', 'Ξ': 'xi',
796801
'ο': 'omicron', 'Ο': 'omicron',
797-
'π': 'pi', 'Π': 'pi',
798-
'ρ': 'rho', 'Ρ': 'rho',
802+
'π': 'pi', 'Π': 'pi', 'ϖ': 'pi',
803+
'ρ': 'rho', 'Ρ': 'rho', 'ϱ': 'rho',
799804
'σ': 'sigma', 'ς': 'sigma', 'Σ': 'sigma',
800805
'τ': 'tau', 'Τ': 'tau',
801806
'υ': 'upsilon', 'Υ': 'upsilon',
802-
'φ': 'phi', 'Φ': 'phi',
807+
'φ': 'phi', 'Φ': 'phi', 'ϕ': 'phi',
803808
'χ': 'chi', 'Χ': 'chi',
804809
'ψ': 'psi', 'Ψ': 'psi',
805810
'ω': 'omega', 'Ω': 'omega',

‎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_greek_variants.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""The micro sign and variant Greek letters normalize like the ordinary letters (issue #126).
2+
3+
PDFs, publishers and curators use the micro sign ``µ`` (U+00B5) and Greek
4+
``μ`` (U+03BC) interchangeably, and the variant forms ``ϕ ϵ ϑ ϐ ϖ`` for the
5+
ordinary letters, so a correct quote must match either spelling.
6+
"""
7+
8+
import pytest
9+
10+
from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig
11+
from linkml_reference_validator.validation.supporting_text_validator import SupportingTextValidator
12+
13+
14+
def found(quote: str, content: str) -> bool:
15+
"""Whether ``quote`` validates against ``content``."""
16+
validator = SupportingTextValidator(ReferenceValidationConfig())
17+
reference = ReferenceContent(reference_id="PMID:1", content=content)
18+
return validator.find_text_in_reference(quote, reference).found
19+
20+
21+
@pytest.mark.parametrize(
22+
"quote,content",
23+
[
24+
("an IC50 of 5 µM", "an IC50 of 5 μM was observed"),
25+
("an IC50 of 5 μM", "an IC50 of 5 µM was observed"),
26+
],
27+
)
28+
def test_micro_sign_and_greek_mu_are_equivalent(quote, content):
29+
"""``5 µM`` and ``5 μM`` match each other in both directions."""
30+
assert found(quote, content)
31+
32+
33+
@pytest.mark.parametrize(
34+
"variant,ordinary",
35+
[
36+
("µ", "μ"), # micro sign, mu
37+
("ϕ", "φ"), # phi symbol, phi
38+
("ϵ", "ε"), # lunate epsilon, epsilon
39+
("ϑ", "θ"), # theta symbol, theta
40+
("ϐ", "β"), # beta symbol, beta
41+
("ϖ", "π"), # pi symbol, pi
42+
("ϰ", "κ"), # kappa symbol, kappa
43+
("ϱ", "ρ"), # rho symbol, rho
44+
],
45+
)
46+
def test_variant_forms_normalize_like_the_ordinary_letter(variant, ordinary):
47+
"""Each variant form is spelled out as the letter it stands for."""
48+
normalize = SupportingTextValidator.normalize_text
49+
assert normalize(f"{variant}-value") == normalize(f"{ordinary}-value")
50+
51+
52+
def test_greek_mu_still_differs_from_the_latin_letter_u():
53+
"""Folding stops at the Greek letters; a Latin ``u`` is not ``mu``."""
54+
assert not found("5 uM", "an IC50 of 5 µM was observed")

‎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):

0 commit comments

Comments
 (0)