Skip to content

Commit bc666f1

Browse files
authored
Merge pull request #150 from linkml/ccr-65a5480d-pb91sk
Match supporting text on whole words, not mid-word
2 parents e17ddf9 + d01b9b7 commit bc666f1

5 files changed

Lines changed: 271 additions & 10 deletions

File tree

‎docs/concepts/how-it-works.md‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ linkml-reference-validator validates that quoted text (supporting text) actually
1313
Before matching, both the supporting text and reference content are normalized:
1414

1515
- **Lowercased**: `"MUC1"` → `"muc1"`
16-
- **Punctuation removed**: `"c-Abl"` → `"c abl"`
16+
- **Punctuation removed**: `"c-Abl"` → `"c abl"` (a point or comma between
17+
digits is kept, so `"10.5"` stays one number)
1718
- **Whitespace collapsed**: Multiple spaces become single space
1819
- **Editorial notes removed**: `"[mucin 1]"` → `""`
1920

@@ -36,6 +37,34 @@ reference_content = "...The MUC1 oncoprotein blocks nuclear..."
3637
# Match: "muc1 oncoprotein" found in normalized reference
3738
```
3839

40+
**Matches start and end on whole words:**
41+
42+
A quote may not begin or end inside a word of the reference. Otherwise a quote
43+
stating the opposite of the paper would pass:
44+
45+
```python
46+
supporting_text = "activates AKT signaling"
47+
reference_content = "...Loss of PTEN inactivates AKT signaling..."
48+
# NOT FOUND: "activates" only occurs inside "inactivates"
49+
50+
supporting_text = "5 mM H2O2"
51+
reference_content = "...treated with 10.5 mM H2O2..."
52+
# NOT FOUND: "5" only occurs inside "10.5"
53+
```
54+
55+
Each part of a quote split with `...` is held to the same rule.
56+
57+
One allowance: when a quote ends in a letter, the reference word it ends on may
58+
carry trailing digits. Full-text extraction welds superscript citations onto the
59+
word before them, so `tumor suppressor<sup>12</sup>` reads as `suppressor12`,
60+
and a quote of `PTEN is a tumor suppressor` must still match. A quote ending in
61+
a digit gets no allowance (`10` never matches `105`). The same allowance means a
62+
quote ending in `AKT` matches `AKT1`, as plain substring matching always did.
63+
64+
Because a point or comma between digits stays part of the number, numbers must
65+
be quoted with the reference's own separators: `days 3, 5 and 7` does not match
66+
`days 3,5 and 7`, and `10 000` does not match `10,000`.
67+
3968
**Empty excerpts are rejected:**
4069

4170
An empty or whitespace-only excerpt is always an error, never a pass. The

‎src/linkml_reference_validator/validation/fuzzy_text_utils.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,8 +396,10 @@ def find_fuzzy_match_in_text(
396396
query_norm = normalize_whitespace(query)
397397
text_norm = normalize_whitespace(text)
398398

399-
# Stage 1: Try exact substring match (fastest - O(n))
400-
if query_norm in text_norm:
399+
# Stage 1: Try exact match (fastest - O(n)). On whole words, as validation
400+
# matches: a hit inside a longer word ("activates" in "inactivates") would
401+
# otherwise come back as a perfect match and be offered as its own fix.
402+
if re.search(rf"(?<!\w){re.escape(query_norm)}(?!\w)", text_norm):
401403
return (True, 100.0, query)
402404

403405
# Stage 2: Quick check - if query is very short, require exact match

‎src/linkml_reference_validator/validation/repairer.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,10 +241,19 @@ def _all_parts_found(
241241
>>> repairer._all_parts_found("[note]", searchable)
242242
False
243243
"""
244-
normalize = normalize_whitespace if literal else SupportingTextValidator.normalize_text
245244
parts = self.validator._split_query(text)
245+
if literal:
246+
# Punctuation is kept here, so spaces do not mark word boundaries;
247+
# the normalized check that follows a literal one enforces them.
248+
return bool(parts) and all(
249+
any(normalize_whitespace(part) in candidate for candidate in searchable)
250+
for part in parts
251+
)
252+
normalize = SupportingTextValidator.normalize_text
253+
contains_words = SupportingTextValidator.contains_words
246254
return bool(parts) and all(
247-
any(normalize(part) in candidate for candidate in searchable) for part in parts
255+
any(contains_words(normalize(part), candidate) for candidate in searchable)
256+
for part in parts
248257
)
249258

250259
def try_ellipsis_insertion(

‎src/linkml_reference_validator/validation/supporting_text_validator.py‎

Lines changed: 75 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -560,7 +560,7 @@ def _substring_match(
560560
for part in query_parts:
561561
normalized_part = self.normalize_text(part)
562562

563-
if not any(normalized_part in text for text in normalized_texts):
563+
if not any(self.contains_words(normalized_part, text) for text in normalized_texts):
564564
# Generate fuzzy suggestion for the failed part, from one text
565565
# at a time: a suggestion spanning two would fail again.
566566
query_for_suggestion = original_query if original_query else part
@@ -570,7 +570,15 @@ def _substring_match(
570570
)
571571

572572
error_message = f"Text part not found as substring: '{part}'"
573-
if len(normalized_texts) > 1 and normalized_part in " ".join(normalized_texts):
573+
if any(normalized_part in text for text in normalized_texts):
574+
error_message = (
575+
f"Text part occurs only inside longer words: '{part}'. "
576+
"A match must start and end on whole words, so a quote "
577+
"of 'activates' does not match 'inactivates'"
578+
)
579+
elif len(normalized_texts) > 1 and self.contains_words(
580+
normalized_part, " ".join(normalized_texts)
581+
):
574582
error_message = (
575583
f"Text part is not within any one figure label: '{part}'. "
576584
"It matches only labels joined in document order, so it "
@@ -593,6 +601,62 @@ def _substring_match(
593601
matched_text=" ... ".join(matched_parts),
594602
)
595603

604+
@staticmethod
605+
def contains_words(part: str, text: str) -> bool:
606+
"""Whether normalized ``part`` occurs in normalized ``text`` as whole words.
607+
608+
A bare substring test lets a quote begin or end inside a word, so
609+
"activates" would match "inactivates" and a quote stating the
610+
opposite of the reference would pass. Both arguments must already be
611+
normalized with :meth:`normalize_text`, which collapses whitespace
612+
to single spaces, so padding each with one space anchors the part
613+
on word boundaries at both ends.
614+
615+
One allowance: when the part ends in a letter, the reference word it
616+
ends on may carry trailing digits. Extraction welds superscript
617+
citations onto the word before them (JATS ``suppressor<sup>12</sup>``,
618+
PMC HTML and PDF text all give ``suppressor12``), and a quote of that
619+
sentence must not fail on its last word. A part ending in a digit gets
620+
no allowance, so ``10`` never matches ``105``.
621+
622+
An empty part (one that was all punctuation) is found, as with a
623+
plain substring test; a quote with no quoted text at all is
624+
rejected before matching.
625+
626+
Args:
627+
part: Normalized query part
628+
text: Normalized text to search
629+
630+
Returns:
631+
True if ``part`` starts and ends on word boundaries within ``text``
632+
633+
Examples:
634+
>>> SupportingTextValidator.contains_words("activates akt", "pten activates akt")
635+
True
636+
>>> SupportingTextValidator.contains_words("activates akt", "pten inactivates akt")
637+
False
638+
>>> SupportingTextValidator.contains_words("pten is not", "pten is nothing")
639+
False
640+
>>> SupportingTextValidator.contains_words("pten", "pten")
641+
True
642+
>>> SupportingTextValidator.contains_words("tumor suppressor", "a tumor suppressor12 in")
643+
True
644+
>>> SupportingTextValidator.contains_words("tumor suppressor", "a tumor suppressor1,2")
645+
True
646+
>>> SupportingTextValidator.contains_words("a dose of 10", "a dose of 105 mg")
647+
False
648+
>>> SupportingTextValidator.contains_words("", "anything")
649+
True
650+
"""
651+
if not part:
652+
return True
653+
if f" {part} " in f" {text} ":
654+
return True
655+
if not part[-1].isalpha():
656+
return False
657+
citation = rf"(?:^| ){re.escape(part)}\d[\d,]*(?: |$)"
658+
return re.search(citation, text) is not None
659+
596660
def generate_suggested_fix(
597661
self,
598662
supporting_text: str,
@@ -661,8 +725,10 @@ def normalize_text(text: str) -> str:
661725
"""Normalize text for comparison.
662726
663727
Folds Latin compatibility ligatures, spells out Greek letters, removes
664-
punctuation and extra whitespace, and lowercases. The same normalization
665-
applies to reference content and queries (including split query parts).
728+
punctuation and extra whitespace, and lowercases. A point or comma
729+
between two digits is kept, so a number such as ``10.5`` stays one
730+
word. The same normalization applies to reference content and queries
731+
(including split query parts).
666732
667733
IJ (IJ/ij) is folded because Unicode defines its compatibility decomposition
668734
as I + J. Distinct letters Æ/æ and Œ/œ are preserved: equating them with
@@ -691,6 +757,8 @@ def normalize_text(text: str) -> str:
691757
'amyloid fibrils'
692758
>>> SupportingTextValidator.normalize_text("ff fi fl ffi ffl ſt st IJ ij")
693759
'ff fi fl ffi ffl st st ij ij'
760+
>>> SupportingTextValidator.normalize_text("10.5 mM, 3,4-dihydroxy, p<0.05.")
761+
'10.5 mm 3,4 dihydroxy p 0.05'
694762
>>> SupportingTextValidator.normalize_text("Æ Œ æ œ H₂O 10⁶ µ")
695763
'æ œ æ œ h₂o 10⁶ µ'
696764
"""
@@ -734,6 +802,8 @@ def normalize_text(text: str) -> str:
734802
text = text.replace(greek, spelled)
735803

736804
text = text.lower()
737-
text = re.sub(r"[^\w\s]", " ", text)
805+
# A point or comma between digits is part of the number: splitting
806+
# "10.5" into "10 5" would let a quote of "5 mM" match "10.5 mM".
807+
text = re.sub(r"(?!(?<=\d)[.,](?=\d))[^\w\s]", " ", text)
738808
text = re.sub(r"\s+", " ", text)
739809
return text.strip()

‎tests/test_word_boundaries.py‎

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
"""A quote must match whole words, not begin or end inside one (issue #124).
2+
3+
Normalized parts used to be tested as bare substrings of the normalized
4+
reference, so "activates" matched inside "inactivates" and a quote stating
5+
the opposite of the reference passed. These tests pin the failing cases and
6+
the matches that must keep working.
7+
"""
8+
9+
import pytest
10+
11+
from linkml_reference_validator.models import ReferenceContent, ReferenceValidationConfig
12+
from linkml_reference_validator.validation.repairer import SupportingTextRepairer
13+
from linkml_reference_validator.validation.supporting_text_validator import SupportingTextValidator
14+
15+
16+
def found(quote: str, content: str) -> bool:
17+
"""Whether ``quote`` validates against ``content``."""
18+
validator = SupportingTextValidator(ReferenceValidationConfig())
19+
reference = ReferenceContent(reference_id="PMID:1", content=content)
20+
return validator.find_text_in_reference(quote, reference).found
21+
22+
23+
@pytest.mark.parametrize(
24+
"quote,content",
25+
[
26+
("activates AKT signaling", "Loss of PTEN inactivates AKT signaling in mice."),
27+
("toxic to hepatocytes", "the compound was nontoxic to hepatocytes"),
28+
("5 mM H2O2 induced apoptosis", "10.5 mM H2O2 induced apoptosis"),
29+
("stable in vivo", "the variant was unstable in vivo"),
30+
("regulated in tumors", "PTEN was downregulated in tumors"),
31+
("PTEN is not", "PTEN is nothing like AKT"),
32+
("the protein binds DNA", "the protein binds DNAse"),
33+
],
34+
)
35+
def test_quote_starting_or_ending_mid_word_fails(quote, content):
36+
"""A quote that begins or ends inside a word of the reference is not found."""
37+
assert not found(quote, content)
38+
39+
40+
@pytest.mark.parametrize(
41+
"quote,content",
42+
[
43+
("activates AKT signaling", "Loss of PTEN activates AKT signaling in mice."),
44+
("PTEN", "PTEN"),
45+
("protein functions", "The protein functions in cells."),
46+
("binds DNA", "it binds DNA."),
47+
("T cell receptor", "the T-cell receptor was"),
48+
("alpha catenin", "α-catenin binds"),
49+
("10.5 mM H2O2", "with 10.5 mM H2O2 induced"),
50+
("loss of PTEN ... AKT signaling", "Loss of PTEN activates AKT signaling."),
51+
],
52+
)
53+
def test_whole_word_quotes_still_match(quote, content):
54+
"""Quotes that start and end on word boundaries, at any position, still match."""
55+
assert found(quote, content)
56+
57+
58+
def test_each_ellipsis_part_is_held_to_word_boundaries():
59+
"""The boundary rule applies to every part of a split quote, not just the whole."""
60+
assert not found("Loss of PTEN ... activates AKT", "Loss of PTEN inactivates AKT signaling.")
61+
62+
63+
def test_figure_labels_are_matched_on_word_boundaries():
64+
"""Each searchable text (an SVG figure label) is held to word boundaries too."""
65+
validator = SupportingTextValidator(ReferenceValidationConfig())
66+
match = validator._substring_match(
67+
["activates AKT"], "", searchable=["PTEN inactivates AKT", "mTOR"]
68+
)
69+
assert not match.found
70+
71+
72+
def test_repair_does_not_confirm_a_mid_word_match():
73+
"""Character normalization is not offered as a fix when it only matches mid-word."""
74+
reference = ReferenceContent(
75+
reference_id="PMID:1", content="Treatment with nonCO₂ gas activates AKT."
76+
)
77+
result = SupportingTextRepairer(ReferenceValidationConfig()).attempt_repair(
78+
"CO2 gas activates AKT", "PMID:1", reference
79+
)
80+
assert not result.is_repaired
81+
82+
83+
@pytest.mark.parametrize(
84+
"quote,content",
85+
[
86+
("PTEN is a tumor suppressor", "PTEN is a tumor suppressor12 in mice."),
87+
("PTEN is a tumor suppressor", "PTEN is a tumor suppressor1,2."),
88+
("PTEN is a tumor suppressor", "PTEN is a tumor suppressor1-3 in mice."),
89+
],
90+
)
91+
def test_citation_digits_welded_to_the_last_word_still_match(quote, content):
92+
"""Extraction welds superscript citations onto a word; a quote ending there still matches.
93+
94+
JATS ``suppressor<sup><xref>12</xref></sup>``, PMC HTML and PDF text all
95+
render the citation as ``suppressor12``, so a quote of the sentence must
96+
not fail on its last word.
97+
"""
98+
assert found(quote, content)
99+
100+
101+
def test_citation_allowance_does_not_extend_a_number():
102+
"""Trailing digits are allowed only after a letter: ``10`` must not grow into ``105``."""
103+
assert not found("a dose of 10", "a dose of 105 mg")
104+
105+
106+
def test_digit_separators_are_part_of_the_number():
107+
"""A point or comma between digits is kept, so differently punctuated numbers differ."""
108+
assert not found("on days 3, 5 and 7", "on days 3,5 and 7")
109+
assert found("on days 3,5 and 7", "measured on days 3,5 and 7")
110+
assert found("p < 0.05", "significant (p<0.05)")
111+
112+
113+
def test_unmapped_glyph_still_splits_the_word():
114+
"""U+FFFD splits a damaged word, so a quote of its second half still matches."""
115+
assert found("ammation of the gut", "in�ammation of the gut")
116+
117+
118+
def test_mid_word_miss_says_why_and_suggests_nothing_that_fails_again():
119+
"""A quote found only inside longer words gets a clear error, not itself as a fix."""
120+
validator = SupportingTextValidator(ReferenceValidationConfig())
121+
quote = "activates AKT signaling"
122+
match = validator.find_text_in_reference(
123+
quote, ReferenceContent(reference_id="PMID:1", content="Loss of PTEN inactivates AKT signaling.")
124+
)
125+
assert not match.found
126+
assert "whole words" in (match.error_message or "")
127+
assert f'"{quote}"' not in (match.suggested_fix or "")
128+
129+
130+
@pytest.mark.parametrize("quote", ["activates AKT signaling", "activates AKT signaling in mice"])
131+
def test_repair_never_returns_the_failing_quote_as_its_fix(quote):
132+
"""Fuzzy repair must not 'fix' a mid-word miss by returning the same quote."""
133+
reference = ReferenceContent(
134+
reference_id="PMID:1",
135+
content="Loss of PTEN inactivates AKT signaling in mice. Other text about things.",
136+
)
137+
result = SupportingTextRepairer(ReferenceValidationConfig()).attempt_repair(
138+
quote, "PMID:1", reference
139+
)
140+
assert not (result.is_repaired and result.repaired_text == quote)
141+
142+
143+
def test_fuzzy_exact_stage_requires_whole_words():
144+
"""The fuzzy matcher's exact shortcut does not accept a mid-word hit."""
145+
from linkml_reference_validator.validation.fuzzy_text_utils import find_fuzzy_match_in_text
146+
147+
found_, score, _ = find_fuzzy_match_in_text("activates AKT", "PTEN inactivates AKT.")
148+
assert score < 100
149+
assert find_fuzzy_match_in_text("activates AKT", "PTEN activates AKT.") == (
150+
True, 100.0, "activates AKT"
151+
)

0 commit comments

Comments
 (0)