Skip to content

Commit eaee275

Browse files
authored
Merge pull request #163 from linkml/ccr-db9d03a0-7pw7k3
Stop extractors welding headings and citation markers onto words
2 parents fcc90e0 + b40efb0 commit eaee275

6 files changed

Lines changed: 512 additions & 5 deletions

File tree

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

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,53 @@ def is_stub_notice(text: str) -> bool:
119119
)
120120

121121

122+
#: Dashes that can join the numbers of a citation range ("1-3", "1–3").
123+
_DASHES = "-\u2010\u2011\u2012\u2013\u2014\u2015\u2212"
124+
125+
126+
def _is_citation_marker(tag: Tag) -> bool:
127+
"""Whether ``tag`` is a bibliographic citation marker.
128+
129+
A JATS ``<xref ref-type="bibr">``, or a ``<sup>`` holding only such xrefs
130+
and the commas and dashes between them. Inline markup is otherwise kept
131+
contiguous (``H<sub>2</sub>O``), but a citation glued to the word before it
132+
(``FOXL2<sup>8</sup>``) reads as another word, and one after a full stop
133+
(``PGE2.<sup>41</sup>``) as a decimal number.
134+
135+
Examples:
136+
>>> soup = BeautifulSoup('<p>A<sup><xref ref-type="bibr">8</xref></sup>'
137+
... '10<sup>6</sup></p>', "xml")
138+
>>> [_is_citation_marker(sup) for sup in soup.find_all("sup")]
139+
[True, False]
140+
"""
141+
if tag.name == "xref":
142+
return tag.get("ref-type") == "bibr"
143+
if tag.name != "sup":
144+
return False
145+
xrefs = tag.find_all("xref")
146+
if not xrefs or any(xref.get("ref-type") != "bibr" for xref in xrefs):
147+
return False
148+
loose = "".join(
149+
str(child) for child in tag.children if type(child) in (NavigableString, CData)
150+
)
151+
return re.fullmatch(rf"[\s,;{re.escape(_DASHES)}]*", loose) is not None
152+
153+
154+
def _welded_to_next_word(tag: Tag) -> bool:
155+
"""Whether the text right after ``tag`` starts with a letter, with no space.
156+
157+
That is what makes a bold lead-in a welded label (``R 2.6</bold>We``)
158+
rather than part of a word (``IL</bold>-6``) or already spaced.
159+
160+
Examples:
161+
>>> soup = BeautifulSoup("<x><p><bold>R 2.6</bold>We</p><p><bold>IL</bold>-6</p></x>", "xml")
162+
>>> [_welded_to_next_word(b) for b in soup.find_all("bold")]
163+
[True, False]
164+
"""
165+
following = tag.next_sibling
166+
return isinstance(following, NavigableString) and str(following)[:1].isalpha()
167+
168+
122169
def _block_text(node: Tag) -> str:
123170
"""Keep inline text contiguous, separating blocks and excluding nested tables.
124171
@@ -137,8 +184,27 @@ def walk(tag: Tag) -> str:
137184
parts.append(str(child))
138185
elif isinstance(child, Tag) and child.name not in {"table", "table-wrap"}:
139186
value = walk(child)
187+
lead_in = (
188+
tag.name == "p"
189+
and child.name == "bold"
190+
and not "".join(parts).strip()
191+
and _welded_to_next_word(child)
192+
)
140193
if child.name in BLOCK_ELEMENTS:
141194
value = " " + value + " "
195+
elif _is_citation_marker(child):
196+
# No space before a dash that follows: "[1</xref>-3]" is
197+
# a range, and " -3" would read as a minus sign.
198+
following = child.next_sibling
199+
dash_next = (
200+
isinstance(following, NavigableString)
201+
and str(following)[:1] in _DASHES
202+
)
203+
value = " " + value + ("" if dash_next else " ")
204+
elif lead_in:
205+
# A paragraph's bold lead-in label ("<bold>R 2.6</bold>We
206+
# recommend") is not part of the sentence after it.
207+
value = value + " "
142208
parts.append(value)
143209
return "".join(parts)
144210

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

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
"""
1313

1414
import logging
15+
import re
1516
import time
1617
from typing import Optional
1718

@@ -33,6 +34,16 @@
3334
logger = logging.getLogger(__name__)
3435

3536

37+
#: JATS elements that end a run of text in a Crossref abstract. Their local
38+
#: names, so ``jats:p`` and a bare ``p`` both count.
39+
_JATS_ABSTRACT_BLOCKS = frozenset(
40+
{
41+
"title", "p", "sec", "list", "list-item", "label", "caption", "def-item",
42+
"disp-quote", "div", "br",
43+
}
44+
)
45+
46+
3647
@ReferenceSourceRegistry.register
3748
class DOISource(ReferenceSource):
3849
"""Fetch references from Crossref using DOI, with DataCite fallback.
@@ -515,6 +526,15 @@ def _extract_crossref_year(self, message: dict) -> str:
515526
def _clean_abstract(self, abstract: str) -> str:
516527
"""Clean JATS/XML markup from abstract text.
517528
529+
Block elements (titles, paragraphs, sections, list items, and HTML
530+
``div`` and ``br``) become paragraphs separated by a blank line.
531+
Crossref nests a structured abstract's sections as ``<jats:title>`` and
532+
``<jats:p>`` with no text between them, so stripping the tags alone
533+
welded each heading onto the next sentence ("AbstractDisease
534+
overviewAcute myeloid..."), and a quote beginning at that sentence
535+
failed whole-word matching. Whitespace inside a paragraph is
536+
collapsed; inline markup stays contiguous.
537+
518538
Args:
519539
abstract: Abstract text potentially containing JATS markup
520540
@@ -525,8 +545,18 @@ def _clean_abstract(self, abstract: str) -> str:
525545
>>> source = DOISource()
526546
>>> source._clean_abstract("<jats:p>Test abstract.</jats:p>")
527547
'Test abstract.'
548+
>>> source._clean_abstract(
549+
... "<jats:title>Abstract</jats:title><jats:sec><jats:title>Aim"
550+
... "</jats:title><jats:p>To test <jats:italic>it</jats:italic>.</jats:p>"
551+
... "</jats:sec>")
552+
'Abstract\\n\\nAim\\n\\nTo test it.'
528553
"""
529554
if not abstract:
530555
return ""
531556
soup = BeautifulSoup(abstract, "html.parser")
532-
return soup.get_text().strip()
557+
for tag in soup.find_all(True):
558+
if tag.name.rpartition(":")[2] in _JATS_ABSTRACT_BLOCKS:
559+
tag.insert_before("\n\n")
560+
tag.insert_after("\n\n")
561+
paragraphs = (" ".join(chunk.split()) for chunk in re.split(r"\n\s*\n", soup.get_text()))
562+
return "\n\n".join(paragraph for paragraph in paragraphs if paragraph)

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

Lines changed: 94 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,54 @@
3737
logger = logging.getLogger(__name__)
3838

3939

40+
#: Section headings of structured abstracts. PubMed sometimes stores them
41+
#: welded onto the next sentence with no markup at all ("IntroductionThe black
42+
#: widow spider..."), which no tag can mark.
43+
_ABSTRACT_HEADINGS = (
44+
"Abstract|Background|Introduction|Objectives?|Aims?|Purpose|Importance|"
45+
"Context|Design|Setting|Participants|Patients|Methods|Materials and Methods|"
46+
"Interventions?|Measurements|Main Outcome Measures|Results|Findings|"
47+
"Observations|Case Report|Case Presentation|Discussion|Interpretation|"
48+
"Conclusions?|Conclusions and Relevance|Significance|Limitations"
49+
)
50+
_WELDED_HEADING = re.compile(
51+
rf"(?:^|(?<=[.!?])|(?<=: ))[ \t]*({_ABSTRACT_HEADINGS})(?=[A-Z])"
52+
)
53+
54+
55+
def _set_off_welded_headings(text: str) -> str:
56+
"""Split a heading welded onto its sentence into a ``"Heading: "`` label.
57+
58+
Only a listed heading, at the start of the text or right after a sentence
59+
ends, and directly followed by a capital letter, so "The Results were"
60+
and "Methodsical" are left alone. A heading right after ": " also counts,
61+
which splits chained headings ("AbstractBackgroundIt" becomes "Abstract:
62+
Background: It") and a welded heading after any earlier label ("Aim:
63+
MethodsWe"). Title-case headings only, on purpose: all-caps welds
64+
("RESULTSThe") and welds after a bracket ("exposures)Conclusions") are
65+
left as they are.
66+
67+
Examples:
68+
>>> _set_off_welded_headings("IntroductionThe spider. ResultsA total.")
69+
'Introduction: The spider.\\n\\nResults: A total.'
70+
>>> _set_off_welded_headings("The Results were striking.")
71+
'The Results were striking.'
72+
"""
73+
74+
def label(match: re.Match[str]) -> str:
75+
after_label = text[: match.start()].endswith(": ")
76+
lead = "" if match.start() == 0 or after_label else "\n\n"
77+
return lead + match.group(1) + ": "
78+
79+
# Repeat for chained headings: "AbstractBackgroundIt began." only exposes
80+
# "Background" once "Abstract" has been split off.
81+
while True:
82+
updated = _WELDED_HEADING.sub(label, text)
83+
if updated == text:
84+
return text
85+
text = updated
86+
87+
4088
@ReferenceSourceRegistry.register
4189
class PMIDSource(ReferenceSource):
4290
"""Fetch references from PubMed using PMID.
@@ -236,7 +284,9 @@ def _render_abstract_sections(element: Any) -> Optional[str]:
236284
"""
237285
sections = []
238286
for node in element.find_all("AbstractText"):
239-
text = node.get_text().strip()
287+
# Edits the parsed node in place; nothing reads it again.
288+
PMIDSource._set_off_inline_headings(node)
289+
text = _set_off_welded_headings(node.get_text().strip())
240290
if not text:
241291
continue
242292
label = node.get("Label")
@@ -245,6 +295,49 @@ def _render_abstract_sections(element: Any) -> Optional[str]:
245295
joined = "\n\n".join(sections)
246296
return joined if joined else None
247297

298+
@staticmethod
299+
def _set_off_inline_headings(node: Any) -> None:
300+
"""Turn inline bold section headings into ``"Heading: "`` labels, in place.
301+
302+
Some publishers supply a structured abstract as one ``AbstractText``
303+
whose headings are inline ``<b>``, with no space after them
304+
(``<b>Background</b>Neuroblastoma can arise...``), so ``get_text()``
305+
welds each heading onto the next word and a quote beginning at that
306+
word fails whole-word matching. A ``<b>`` or ``<strong>`` counts as a
307+
heading only at the start of the text or right after a sentence ends,
308+
and only when the text after it starts with a letter; bold inside a
309+
sentence, or not welded to the next word, is left as it is.
310+
311+
Args:
312+
node: An ``AbstractText`` element, modified in place
313+
314+
Examples:
315+
>>> from bs4 import BeautifulSoup
316+
>>> xml = ("<AbstractText><b>Background</b>It began."
317+
... "<b>Results</b>It worked.</AbstractText>")
318+
>>> node = BeautifulSoup(xml, "xml").find("AbstractText")
319+
>>> PMIDSource._set_off_inline_headings(node)
320+
>>> node.get_text()
321+
'Background: It began.\\n\\nResults: It worked.'
322+
"""
323+
for bold in node.find_all(["b", "strong"]):
324+
before = "".join(
325+
str(sibling.get_text() if hasattr(sibling, "get_text") else sibling)
326+
for sibling in reversed(list(bold.previous_siblings))
327+
).rstrip()
328+
if before and not before.endswith((".", "!", "?")):
329+
continue
330+
# Only a real weld: the next text starts with a letter, no space.
331+
# "<b>IL</b>-6" and "<b>Importantly</b>," are not headings.
332+
following = bold.next_sibling
333+
if not (isinstance(following, str) and following[:1].isalpha()):
334+
continue
335+
heading = bold.get_text().strip()
336+
if not heading:
337+
continue
338+
label = heading if heading.endswith(":") else f"{heading}:"
339+
bold.replace_with(f"{chr(10) * 2 if before else ''}{label} ")
340+
248341
def _parse_abstract(self, soup: BeautifulSoup) -> Optional[str]:
249342
"""Parse the abstract from a PubMed article XML document.
250343

‎src/linkml_reference_validator/validation/supporting_text_validator.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,10 @@ def is_blank_text(value: object) -> bool:
6262
return isinstance(value, str) and not value.strip()
6363

6464

65+
#: Digits a citation marker welded onto a word can carry: decimal digits and
66+
#: the superscript digits that text printing the marker itself uses (``ears¹``).
67+
_CITATION_DIGITS = r"\d¹²³⁴⁵⁶⁷⁸⁹⁰"
68+
6569
#: Characters typesetters print for a minus sign: "-", the Unicode hyphens
6670
#: U+2010 and U+2011, the figure dash U+2012, the en dash, "−" (U+2212) and the
6771
#: small and fullwidth hyphen-minus. The em dash is left out: it is a
@@ -627,8 +631,9 @@ def contains_words(part: str, text: str) -> bool:
627631
One allowance: when the part ends in a letter, the reference word it
628632
ends on may carry trailing digits. Extraction welds superscript
629633
citations onto the word before them (JATS ``suppressor<sup>12</sup>``,
630-
PMC HTML and PDF text all give ``suppressor12``), and a quote of that
631-
sentence must not fail on its last word. A part ending in a digit gets
634+
PMC HTML and PDF text all give ``suppressor12``, and text that prints
635+
the citation itself as superscript gives ``ears¹``), and a quote of
636+
that sentence must not fail on its last word. A part ending in a digit gets
632637
no allowance, so ``10`` never matches ``105``.
633638
634639
An empty part (one that was all punctuation) is found, as with a
@@ -657,6 +662,8 @@ def contains_words(part: str, text: str) -> bool:
657662
True
658663
>>> SupportingTextValidator.contains_words("a dose of 10", "a dose of 105 mg")
659664
False
665+
>>> SupportingTextValidator.contains_words("small ears", "small ears¹ ³ both")
666+
True
660667
>>> SupportingTextValidator.contains_words("", "anything")
661668
True
662669
"""
@@ -666,7 +673,7 @@ def contains_words(part: str, text: str) -> bool:
666673
return True
667674
if not part[-1].isalpha():
668675
return False
669-
citation = rf"(?:^| ){re.escape(part)}\d[\d,]*(?: |$)"
676+
citation = rf"(?:^| ){re.escape(part)}[{_CITATION_DIGITS}][{_CITATION_DIGITS},]*(?: |$)"
670677
return re.search(citation, text) is not None
671678

672679
def generate_suggested_fix(

0 commit comments

Comments
 (0)