From fdf4419d0ee0413976bc35d24b3bcb598fd0db46 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 00:28:00 -0700 Subject: [PATCH 1/3] Retain uppercase acronyms through lexical front-loading Carry uppercase acronym detection from query extraction into find_rare_terms() so Stage-2 lexical front-loading actually searches acronym-only queries (such as HIV and EGFR). Normalize Unicode compatibility forms, hyphen variants, and subscript digits before tokenizing, ignore punctuation-only tokens, update docstrings, and remove unused code in lexical.py. Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/retrieval/helpers.py | 90 ++++++++++++++++++++------------- src/litkit/retrieval/lexical.py | 58 +++++++++------------ tests/test_retrieval.py | 82 ++++++++++++++++++++++++++++-- 4 files changed, 157 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5591089..459ed78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed -- `query_terms()` now preserves 3–4 character all-uppercase acronyms (such as `HIV` and `EGFR`) instead of lowercasing tokens before checking case. (#9) +- `query_terms()` and `find_rare_terms()` now retain 3–4 character all-uppercase acronyms (such as `HIV` and `EGFR`) through Stage-2 lexical front-loading, normalize Unicode variants before tokenizing, and ignore punctuation-only tokens. (#9) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 20ffc5a..9ebbf7b 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -5,12 +5,10 @@ """ from __future__ import annotations -import os import re import unicodedata from pathlib import Path - # Stopwords for query term filtering _STOPWORDS = { "the", "and", "for", "with", "that", "this", "from", "into", "your", @@ -20,42 +18,74 @@ "its", "their", "them", "we", "you", "i", } +_TOKEN_RE = re.compile(r"[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*") +_UNICODE_NORM_TRANS = str.maketrans( + { + "\u00ad": "", # soft hyphen (strip) + "\u2010": "-", # hyphen + "\u2011": "-", # non-breaking hyphen + "\u2012": "-", # figure dash + "\u2013": "-", # en dash + "\u2014": "-", # em dash + "\u2212": "-", # minus sign + **dict(zip("₀₁₂₃₄₅₆₇₈₉", "0123456789", strict=True)), + } +) -def query_terms(s: str) -> list[str]: - """Extract meaningful query terms from a string. - - Extracts alphanumeric tokens, lowercases them, and filters out - short/common words. Keeps tokens that are: - - 5+ characters long - - All uppercase and 3+ chars - - Contain digits - - Contain underscores or hyphens - - Args: - s: Input string (typically a question) - - Returns: - List of unique query terms in original order + +def _normalize_unicode(s: str) -> str: + """Normalize NFKC forms, hyphen/dash variants, and subscript digits.""" + return unicodedata.normalize("NFKC", s).translate(_UNICODE_NORM_TRANS) + + +def _extract_query_terms(s: str) -> list[tuple[str, bool]]: + """Extract normalized query terms paired with an all-uppercase flag. + + Normalizes Unicode compatibility forms, hyphen variants, and subscript + digits before tokenizing ASCII alphanumeric/hyphen/underscore words of at + least 3 characters, checking uppercase status before lowercasing. """ - words = re.findall(r"[A-Za-z0-9_-]{3,}", s) - out = [] - seen = set() - for w in words: + out: list[tuple[str, bool]] = [] + seen: set[str] = set() + for w in _TOKEN_RE.findall(_normalize_unicode(s)): + if len(w) < 3: + continue lowered = w.lower() if lowered in _STOPWORDS or lowered in seen: continue + is_acronym = w.isupper() if ( len(w) >= 5 - or (w.isupper() and len(w) >= 3) + or is_acronym or any(ch.isdigit() for ch in w) or "_" in w or "-" in w ): seen.add(lowered) - out.append(lowered) + out.append((lowered, is_acronym)) return out +def query_terms(s: str) -> list[str]: + """Extract meaningful query terms from a string. + + Normalizes Unicode variants, extracts hyphen/underscore-joined ASCII + alphanumeric tokens of 3+ characters, filters out stopwords, and lowercases + kept terms while preserving order. Keeps tokens that are: + - 5+ characters long + - All uppercase (checked before lowercasing) + - Contain digits + - Contain underscores or hyphens + + Args: + s: Input string (typically a question) + + Returns: + List of unique query terms in original order + """ + return [term for term, _ in _extract_query_terms(s)] + + def sqlite_norm_expr(field: str = "text") -> str: """Build a SQL expression that normalizes unicode variants. @@ -118,19 +148,7 @@ def normalize_for_search_py(s: str) -> str: Returns: Normalized string """ - s = unicodedata.normalize("NFKC", s).lower() - for ch, repl in [ - ("\u00ad", ""), - ("\u2010", "-"), - ("\u2011", "-"), - ("\u2012", "-"), - ("\u2013", "-"), - ("\u2014", "-"), - ("\u2212", "-"), - ]: - s = s.replace(ch, repl) - trans = str.maketrans("₀₁₂₃₄₅₆₇₈₉", "0123456789") - return s.translate(trans) + return _normalize_unicode(s).lower() def avg_chunks_for_papers( diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index 84964d2..ff37d3e 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -4,6 +4,7 @@ Lexical front-loading improves recall for queries containing: - Technical terms with digits (e.g., "H1N1", "SARS-CoV-2", "IL-6") - Hyphenated compound terms (e.g., "angiotensin-converting") +- All-uppercase acronyms (e.g., "HIV", "EGFR") - Very long specific terms (e.g., "methyltransferase") These terms often have exact matches in the corpus that ANN may miss. @@ -17,33 +18,21 @@ from __future__ import annotations import logging -import re import sqlite3 from dataclasses import dataclass, field from typing import TYPE_CHECKING, Protocol from litkit.retrieval.helpers import ( - query_terms, - sqlite_norm_expr, + _extract_query_terms, escape_like, normalize_for_search_py, + sqlite_norm_expr, ) -from litkit.progress import eprint as _eprint if TYPE_CHECKING: from sqlite3 import Connection -# Stopwords for query term filtering (shared with helpers.py) -_STOPWORDS = { - "the", "and", "for", "with", "that", "this", "from", "into", "your", - "about", "does", "what", "when", "where", "which", "who", "whom", - "whose", "why", "how", "are", "is", "was", "were", "be", "been", - "being", "of", "on", "in", "to", "a", "an", "as", "by", "at", "it", - "its", "their", "them", "we", "you", "i", -} - - @dataclass class LexicalConfig: """Configuration for lexical front-loading behavior. @@ -60,7 +49,7 @@ class LexicalConfig: allow_global: Force global scope (ignore candidate filter) min_term_length: Threshold for long-term fallback max_terms: Cap # of rare terms to use - require_rare_terms: If False, allow long-only matches + require_rare_terms: Retained for config compatibility (long-term fallback always runs) """ enabled: bool = True cap: int | None = None @@ -114,40 +103,39 @@ def search( def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: """Extract rare/technical terms that benefit from exact match. - + This is a pure function - no DB dependencies, easy to test. - + Prioritizes: 1. Terms with digits (H1N1, IL-6, CD4) 2. Terms with LIKE-sensitive chars (hyphens, underscores, %, \\) - 3. Very long terms (config.min_term_length+) as fallback - + 3. All-uppercase acronyms of 3+ chars (HIV, EGFR) + 4. Very long terms (config.min_term_length+) as fallback + Args: question: The user's question config: LexicalConfig with min_term_length and max_terms - + Returns: List of rare terms, capped at config.max_terms """ - # Use shared query_terms for base extraction - terms = query_terms(question) - - # Find "rare" terms: digits or LIKE-sensitive chars + # Use shared extraction so acronym flags are preserved before lowercasing + terms = _extract_query_terms(question) + + # Find "rare" terms: digits, LIKE-sensitive chars, or all-uppercase acronyms rare = [ - t for t in terms - if any(ch.isdigit() for ch in t) + t + for t, is_acronym in terms + if is_acronym + or any(ch.isdigit() for ch in t) or any(ch in "-_%\\" for ch in t) ] - - # Fallback: long terms if no rare terms and not requiring rare + + # Fallback: long terms when no rare terms matched if not rare: - if config.require_rare_terms: - # Still try long terms as fallback - rare = [t for t in terms if len(t) >= config.min_term_length] - else: - rare = [t for t in terms if len(t) >= config.min_term_length] - - return rare[:config.max_terms] + rare = [t for t, _ in terms if len(t) >= config.min_term_length] + + return rare[: config.max_terms] class SqliteLexicalBackend: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 9de26f5..8b5c46e 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -3,11 +3,15 @@ import sqlite3 +import faiss +import numpy as np import pytest -from litkit.db import connect_db, init_db, load_temp_candidates +from litkit.db import chunk_ids_to_paper_ids, connect_db, init_db, load_temp_candidates from litkit.frontload.cap import cap_chunks_per_paper +from litkit.index import flat_ip_index from litkit.index.search import pick_nprobe +from litkit.retrieval import search_chunks_constrained from litkit.retrieval.helpers import ( escape_like, normalize_for_search_py, @@ -40,9 +44,30 @@ def test_query_terms_keeps_short_hyphen_and_underscore_terms(): def test_query_terms_keeps_uppercase_acronyms(): assert query_terms("Does HIV bind CD4 via EGFR?") == ["hiv", "cd4", "egfr"] # Uppercase stopwords are still filtered; title/lowercase short words are dropped; - # uppercase acronyms are lowercased and deduplicated. + # uppercase acronyms are lowercased and deduplicated regardless of order. assert query_terms("HOW DOES HIV AND EGFR act in the body?") == ["hiv", "egfr"] assert query_terms("Can hiv and HIV bind RNA or rna?") == ["hiv", "rna"] + assert query_terms("HIV and hiv; METHYLTRANSFERASE and methyltransferase") == [ + "hiv", + "methyltransferase", + ] + + +def test_query_terms_handles_edge_cases_and_unicode(): + assert query_terms("") == [] + assert query_terms(" ") == [] + assert query_terms("HOW DOES THE") == [] + # Mixed-case 3-4 letter terms are not treated as all-uppercase acronyms. + assert query_terms("Does mRNA or IgG bind Hiv?") == [] + # Punctuation-only sequences are ignored; trailing hyphens before non-ASCII are dropped. + assert query_terms("--- ___ TNF-α") == ["tnf"] + # Unicode hyphens, subscripts, and NFKC forms normalize before tokenization. + assert query_terms("Is IL\u20116 and CO\u2082 raised in \ufb01brosis?") == [ + "il-6", + "co2", + "raised", + "fibrosis", + ] def test_find_rare_terms_prefers_digits_and_hyphens(): @@ -53,8 +78,15 @@ def test_find_rare_terms_prefers_digits_and_hyphens(): ] +def test_find_rare_terms_keeps_uppercase_acronyms(): + cfg = LexicalConfig() + assert find_rare_terms("Does HIV bind CD4 via EGFR?", cfg) == ["hiv", "cd4", "egfr"] + assert find_rare_terms("How does HIV infect cells?", cfg) == ["hiv"] + assert find_rare_terms("HOW DOES HIV AND EGFR act in the body?", cfg) == ["hiv", "egfr"] + + def test_find_rare_terms_falls_back_to_long_terms_and_caps(): - # No digits or hyphens: terms of min_term_length (9) or more are used. + # No digits, hyphens, or acronyms: terms of min_term_length (9) or more are used. assert find_rare_terms("explain methyltransferase pathways", LexicalConfig()) == [ "methyltransferase" ] @@ -182,6 +214,50 @@ def test_lexical_search_respects_limit_and_disable(lexical_db): assert backend.search([], None, LexicalConfig()).chunk_ids == [] +def test_stage2_lexical_frontloads_uppercase_acronyms(tmp_path): + """Acronym-only queries must trigger lexical front-loading in Stage 2.""" + db_path = tmp_path / "stage2.sqlite3" + conn = init_db(db_path) + conn.execute( + "INSERT INTO papers(id, doc_id, pmid, pmcid, title) VALUES (?, ?, ?, ?, ?)", + (1, "d1", "1", "PMC1", "Retrovirus interactions"), + ) + conn.executemany( + "INSERT INTO chunks(id, paper_id, ord, text) VALUES (?, ?, ?, ?)", + [ + (10, 1, 0, "unrelated background text"), + (11, 1, 1, "HIV binds EGFR on target cells"), + ], + ) + conn.commit() + conn.close() + + index_path = tmp_path / "chunks.index" + index = faiss.IndexIDMap2(flat_ip_index(4)) + # Chunk 10 aligns with the query vector; chunk 11 is orthogonal so ANN puts 10 first. + vecs = np.array([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]], dtype=np.float32) + index.add_with_ids(vecs, np.array([10, 11], dtype=np.int64)) + faiss.write_index(index, str(index_path)) + + class _QueryEmbedder: + def encode(self, texts): + return np.array([[1.0, 0.0, 0.0, 0.0]], dtype=np.float32) + + chunk_ids, _ = search_chunks_constrained( + "Does HIV bind EGFR?", + candidate_papers=[1], + k=1, + chunk_index_path=index_path, + db_path=db_path, + embedder=_QueryEmbedder(), + connect_db=connect_db, + load_temp_candidates=load_temp_candidates, + chunk_ids_to_paper_ids=chunk_ids_to_paper_ids, + min_chunks_per_paper=1.0, + ) + assert chunk_ids == [11] + + # ------------------------------------------------------------------- merging From fc4204c877077dfed5353bab98268767ba4938c4 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 01:31:15 -0700 Subject: [PATCH 2/3] Address PR #36 review: word-boundary acronyms, tiering, and dash/NFKC handling Match 3-4 character alphabetic terms on ASCII word boundaries in SQLite, prioritize digit/hyphen terms and long-term fallback ahead of acronyms, cap acronyms at 3-4 characters while skipping all-caps prose, keep NFKC out of tokenization until #20, map em dashes and spaced en dashes to spaces, share the SQLite normalization replacement table, and expand tests. Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/retrieval/helpers.py | 110 ++++++++++++++++------------ src/litkit/retrieval/lexical.py | 107 ++++++++++++++++++--------- tests/test_retrieval.py | 123 +++++++++++++++++++++++++++++--- 4 files changed, 254 insertions(+), 88 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 459ed78..4cb6415 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed -- `query_terms()` and `find_rare_terms()` now retain 3–4 character all-uppercase acronyms (such as `HIV` and `EGFR`) through Stage-2 lexical front-loading, normalize Unicode variants before tokenizing, and ignore punctuation-only tokens. (#9) +- `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV` and `EGFR`) with word-boundary matching, prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. (#9) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 9ebbf7b..730ddb0 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -15,52 +15,84 @@ "about", "does", "what", "when", "where", "which", "who", "whom", "whose", "why", "how", "are", "is", "was", "were", "be", "been", "being", "of", "on", "in", "to", "a", "an", "as", "by", "at", "it", - "its", "their", "them", "we", "you", "i", + "its", "their", "them", "we", "you", "i", "can", "did", "not", "may", + "has", "had", "but", "all", "one", "use", "will", } +_ACRONYM_MAX_LEN = 4 +_ALPHA_WORD_RE = re.compile(r"[A-Za-z]+") _TOKEN_RE = re.compile(r"[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*") -_UNICODE_NORM_TRANS = str.maketrans( +_EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[A-Za-z0-9])[\u2012\u2013](?=[A-Za-z0-9])") + +# Single source of truth shared by sqlite_norm_expr() and normalize_for_search_py(). +_SQLITE_NORM_REPLACEMENTS: tuple[tuple[str, str], ...] = ( + ("\u00ad", ""), # soft hyphen (strip) + ("\u2010", "-"), # hyphen + ("\u2011", "-"), # non-breaking hyphen + ("\u2012", "-"), # figure dash + ("\u2013", "-"), # en dash + ("\u2014", "-"), # em dash + ("\u2212", "-"), # minus sign + *zip("₀₁₂₃₄₅₆₇₈₉", "0123456789", strict=True), +) +_SQLITE_NORM_TRANS = str.maketrans(dict(_SQLITE_NORM_REPLACEMENTS)) + +# Tokenization mapping derived from _SQLITE_NORM_REPLACEMENTS (no NFKC until #20): +# em dashes separate words instead of joining them, and en/figure dashes are handled +# contextually so "Michaelis–Menten" joins while "cells – specifically" splits. +_TOKENIZE_TRANS = str.maketrans( { - "\u00ad": "", # soft hyphen (strip) - "\u2010": "-", # hyphen - "\u2011": "-", # non-breaking hyphen - "\u2012": "-", # figure dash - "\u2013": "-", # en dash - "\u2014": "-", # em dash - "\u2212": "-", # minus sign - **dict(zip("₀₁₂₃₄₅₆₇₈₉", "0123456789", strict=True)), + **{ + ch: repl + for ch, repl in _SQLITE_NORM_REPLACEMENTS + if ch not in ("\u2012", "\u2013", "\u2014") + }, + "\u2014": " ", } ) -def _normalize_unicode(s: str) -> str: - """Normalize NFKC forms, hyphen/dash variants, and subscript digits.""" - return unicodedata.normalize("NFKC", s).translate(_UNICODE_NORM_TRANS) +def _normalize_for_tokenize(s: str) -> str: + """Normalize SQLite-compatible dashes/subscripts without fusing prose.""" + out = s.translate(_TOKENIZE_TRANS) + out = _EN_FIGURE_DASH_BETWEEN_ALNUM_RE.sub("-", out) + return out.replace("\u2012", " ").replace("\u2013", " ") + + +def _is_all_caps_prose(s: str) -> bool: + """Detect all-caps sentences/headings where uppercase does not mark acronyms.""" + if any(ch.isascii() and ch.islower() for ch in s): + return False + words = [w for w in _ALPHA_WORD_RE.findall(s) if len(w) >= 2] + if not words: + return False + return any( + (w.lower() in _STOPWORDS and w.lower() != "and") or len(w) > _ACRONYM_MAX_LEN + for w in words + ) def _extract_query_terms(s: str) -> list[tuple[str, bool]]: - """Extract normalized query terms paired with an all-uppercase flag. + """Extract normalized query terms paired with an acronym flag. - Normalizes Unicode compatibility forms, hyphen variants, and subscript - digits before tokenizing ASCII alphanumeric/hyphen/underscore words of at - least 3 characters, checking uppercase status before lowercasing. + Applies SQLite-compatible dash and subscript normalization (without NFKC) + before tokenizing ASCII alphanumeric/hyphen/underscore words of at least 3 + characters, checking uppercase status before lowercasing. All-uppercase + 3-4 character tokens are flagged as acronyms unless the input is all-caps + prose. """ + normalized = _normalize_for_tokenize(s) + allow_acronyms = not _is_all_caps_prose(normalized) out: list[tuple[str, bool]] = [] seen: set[str] = set() - for w in _TOKEN_RE.findall(_normalize_unicode(s)): + for w in _TOKEN_RE.findall(normalized): if len(w) < 3: continue lowered = w.lower() if lowered in _STOPWORDS or lowered in seen: continue - is_acronym = w.isupper() - if ( - len(w) >= 5 - or is_acronym - or any(ch.isdigit() for ch in w) - or "_" in w - or "-" in w - ): + is_acronym = allow_acronyms and w.isupper() and len(w) <= _ACRONYM_MAX_LEN + if len(w) >= 5 or is_acronym or any(ch.isdigit() for ch in w) or "_" in w or "-" in w: seen.add(lowered) out.append((lowered, is_acronym)) return out @@ -69,11 +101,12 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: def query_terms(s: str) -> list[str]: """Extract meaningful query terms from a string. - Normalizes Unicode variants, extracts hyphen/underscore-joined ASCII - alphanumeric tokens of 3+ characters, filters out stopwords, and lowercases - kept terms while preserving order. Keeps tokens that are: + Normalizes SQLite-compatible dashes and subscript digits, extracts + hyphen/underscore-joined ASCII alphanumeric tokens of 3+ characters, + filters out stopwords, and lowercases kept terms while preserving order. + Keeps tokens that are: - 5+ characters long - - All uppercase (checked before lowercasing) + - 3-4 character all-uppercase acronyms (unless input is all-caps prose) - Contain digits - Contain underscores or hyphens @@ -101,21 +134,8 @@ def sqlite_norm_expr(field: str = "text") -> str: SQL expression string """ f = f"lower({field})" - # Hyphen/minus variants: U+2010..U+2014, U+2212, plus soft hyphen - for ch, repl in [ - ("\u00ad", ""), # soft hyphen (strip) - ("\u2010", "-"), # hyphen - ("\u2011", "-"), # non-breaking hyphen - ("\u2012", "-"), # figure dash - ("\u2013", "-"), # en dash - ("\u2014", "-"), # em dash - ("\u2212", "-"), # minus sign - ]: + for ch, repl in _SQLITE_NORM_REPLACEMENTS: f = f"replace({f}, '{ch}', '{repl}')" - # Subscript digits → ASCII - subs = "₀₁₂₃₄₅₆₇₈₉" - for d_sub, d in zip(subs, "0123456789", strict=False): - f = f"replace({f}, '{d_sub}', '{d}')" return f @@ -148,7 +168,7 @@ def normalize_for_search_py(s: str) -> str: Returns: Normalized string """ - return _normalize_unicode(s).lower() + return unicodedata.normalize("NFKC", s).lower().translate(_SQLITE_NORM_TRANS) def avg_chunks_for_papers( diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index ff37d3e..bd1bf33 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -18,11 +18,14 @@ from __future__ import annotations import logging +import re import sqlite3 from dataclasses import dataclass, field +from functools import lru_cache from typing import TYPE_CHECKING, Protocol from litkit.retrieval.helpers import ( + _ACRONYM_MAX_LEN, _extract_query_terms, escape_like, normalize_for_search_py, @@ -33,6 +36,23 @@ from sqlite3 import Connection +@lru_cache(maxsize=256) +def _word_boundary_re(term: str) -> re.Pattern[str]: + # Require ASCII alphanumeric boundaries (matching _TOKEN_RE) so short + # acronyms match 'RNA-seq', '(HIV)', and 'TNFα' without matching 'journal'. + return re.compile(rf"(? int: + if not text or not term: + return 0 + return 1 if _word_boundary_re(term).search(text) else 0 + + +def _needs_word_boundary(norm_term: str) -> bool: + return norm_term.isascii() and norm_term.isalpha() and len(norm_term) <= _ACRONYM_MAX_LEN + + @dataclass class LexicalConfig: """Configuration for lexical front-loading behavior. @@ -49,7 +69,7 @@ class LexicalConfig: allow_global: Force global scope (ignore candidate filter) min_term_length: Threshold for long-term fallback max_terms: Cap # of rare terms to use - require_rare_terms: Retained for config compatibility (long-term fallback always runs) + require_rare_terms: Ignored; the long-term fallback runs whenever no digit or hyphen/underscore terms are found """ enabled: bool = True cap: int | None = None @@ -107,10 +127,10 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: This is a pure function - no DB dependencies, easy to test. Prioritizes: - 1. Terms with digits (H1N1, IL-6, CD4) - 2. Terms with LIKE-sensitive chars (hyphens, underscores, %, \\) - 3. All-uppercase acronyms of 3+ chars (HIV, EGFR) - 4. Very long terms (config.min_term_length+) as fallback + 1. Terms with digits (H1N1, IL-6, CD4) or hyphens/underscores (P-gp, a_b) + 2. Long terms (config.min_term_length+) as fallback when tier 1 is empty + 3. 3-4 character all-uppercase acronyms (HIV, EGFR), ordered after higher + tiers so they never crowd out digit/hyphen terms or disable fallback Args: question: The user's question @@ -122,18 +142,20 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: # Use shared extraction so acronym flags are preserved before lowercasing terms = _extract_query_terms(question) - # Find "rare" terms: digits, LIKE-sensitive chars, or all-uppercase acronyms - rare = [ - t - for t, is_acronym in terms - if is_acronym - or any(ch.isdigit() for ch in t) - or any(ch in "-_%\\" for ch in t) - ] + # Priority 1: digits or hyphens/underscores + primary = [t for t, _ in terms if any(ch.isdigit() for ch in t) or any(ch in "-_" for ch in t)] + primary_set = set(primary) - # Fallback: long terms when no rare terms matched - if not rare: - rare = [t for t, _ in terms if len(t) >= config.min_term_length] + # Priority 3: 3-4 char all-uppercase acronyms not already in priority 1 + acronyms = [t for t, is_acronym in terms if is_acronym and t not in primary_set] + + if primary: + rare = primary + acronyms + else: + # Priority 2 fallback: long terms still run even when acronyms are present + long_terms = [t for t, _ in terms if len(t) >= config.min_term_length] + long_set = set(long_terms) + rare = long_terms + [t for t in acronyms if t not in long_set] return rare[: config.max_terms] @@ -161,6 +183,7 @@ def __init__( self.db_conn = db_conn self.load_temp_candidates = load_temp_candidates self._warn_once = False + self.db_conn.create_function("litkit_word_match", 2, _word_match, deterministic=True) def search( self, @@ -182,22 +205,40 @@ def search( scope = "global" if candidate_papers is None else "candidates" - # Build LIKE clause with normalization - norm = sqlite_norm_expr("text") - like_parts = [f"{norm} LIKE ? ESCAPE '\\'"] * len(terms) + # Build LIKE clause with normalization; short alphabetic terms (such as + # 3-4 char acronyms) also require word boundaries so 'rna' does not + # match 'journal' or 'internal'. + norm = sqlite_norm_expr("c.text") + like_parts: list[str] = [] + params: list[object] = [] + for t in terms: + nt = normalize_for_search_py(t) + like_param = f"%{escape_like(nt)}%" + if _needs_word_boundary(nt): + like_parts.append( + f"({norm} LIKE ? ESCAPE '\\' AND litkit_word_match({norm}, ?))" + ) + params.extend([like_param, nt]) + else: + like_parts.append(f"{norm} LIKE ? ESCAPE '\\'") + params.append(like_param) like_clause = " OR ".join(like_parts) - params = [ - f"%{escape_like(normalize_for_search_py(t))}%" - for t in terms - ] - + # Title hint for sorting (prefer chunks from papers with matching title) title_hint = normalize_for_search_py(terms[0] if terms else "") - title_like_param = f"%{escape_like(title_hint)}%" if title_hint else "%" - + title_norm = sqlite_norm_expr("p.title") + if title_hint and _needs_word_boundary(title_hint): + title_expr = ( + f"({title_norm} LIKE ? ESCAPE '\\' AND litkit_word_match({title_norm}, ?))" + ) + title_params: list[object] = [f"%{escape_like(title_hint)}%", title_hint] + else: + title_expr = f"{title_norm} LIKE ? ESCAPE '\\'" + title_params = [f"%{escape_like(title_hint)}%" if title_hint else "%"] + cur = self.db_conn.cursor() chunk_ids: list[int] = [] - + try: if scope == "global": cur.execute( @@ -205,15 +246,15 @@ def search( SELECT c.id FROM chunks c JOIN papers p ON p.id = c.paper_id - WHERE ({like_clause.replace('text', 'c.text')}) + WHERE ({like_clause}) ORDER BY (c.ord = -1) DESC, - ({sqlite_norm_expr('p.title')} LIKE ? ESCAPE '\\') DESC, + ({title_expr}) DESC, (p.pmid IS NOT NULL) DESC, (p.pmcid IS NOT NULL) DESC, c.id ASC LIMIT ? """, - params + [title_like_param, config.limit], + params + title_params + [config.limit], ) else: # Scope to candidate papers @@ -223,16 +264,16 @@ def search( SELECT c.id FROM chunks c JOIN papers p ON p.id = c.paper_id - WHERE ({like_clause.replace('text', 'c.text')}) + WHERE ({like_clause}) AND c.paper_id IN (SELECT id FROM cand_papers) ORDER BY (c.ord = -1) DESC, - ({sqlite_norm_expr('p.title')} LIKE ? ESCAPE '\\') DESC, + ({title_expr}) DESC, (p.pmid IS NOT NULL) DESC, (p.pmcid IS NOT NULL) DESC, c.id ASC LIMIT ? """, - params + [title_like_param, config.limit], + params + title_params + [config.limit], ) chunk_ids = [row[0] for row in cur.fetchall()] diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index 8b5c46e..c6e4a45 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -59,15 +59,33 @@ def test_query_terms_handles_edge_cases_and_unicode(): assert query_terms("HOW DOES THE") == [] # Mixed-case 3-4 letter terms are not treated as all-uppercase acronyms. assert query_terms("Does mRNA or IgG bind Hiv?") == [] + # All-caps prose does not turn ordinary 3-4 letter words into acronyms. + assert query_terms("HOW DOES HIV AND EGFR ACT IN THE BODY?") == [] + assert query_terms("WHAT IS THE ROLE OF RNA IN CELL SIGNALING?") == ["signaling"] # Punctuation-only sequences are ignored; trailing hyphens before non-ASCII are dropped. assert query_terms("--- ___ TNF-α") == ["tnf"] - # Unicode hyphens, subscripts, and NFKC forms normalize before tokenization. - assert query_terms("Is IL\u20116 and CO\u2082 raised in \ufb01brosis?") == [ + # Em dashes and spaced en dashes separate words; non-spaced en dashes join compounds. + assert query_terms("What causes fibrosis\u2014specifically methyltransferase?") == [ + "causes", + "fibrosis", + "specifically", + "methyltransferase", + ] + assert query_terms("HIV\u2014a retrovirus") == ["hiv", "retrovirus"] + assert query_terms("Michaelis\u2013Menten and cells \u2013 specifically") == [ + "michaelis-menten", + "cells", + "specifically", + ] + # SQLite-supported hyphens and subscripts normalize; superscripts (no NFKC in SQL) do not. + assert query_terms("Is IL\u20116 and IC\u2085\u2080 of CO\u2082 raised?") == [ "il-6", + "ic50", "co2", "raised", - "fibrosis", ] + assert query_terms("concentration 10\u207b\u00b3 M") == ["concentration"] + assert query_terms("Ca\u00b2\u207a signaling") == ["signaling"] def test_find_rare_terms_prefers_digits_and_hyphens(): @@ -80,9 +98,42 @@ def test_find_rare_terms_prefers_digits_and_hyphens(): def test_find_rare_terms_keeps_uppercase_acronyms(): cfg = LexicalConfig() - assert find_rare_terms("Does HIV bind CD4 via EGFR?", cfg) == ["hiv", "cd4", "egfr"] + # Tier 1 (digits/hyphens) precedes tier 2 (3-4 char acronyms) before max_terms. + assert find_rare_terms("Does HIV bind CD4 via EGFR?", cfg) == ["cd4", "hiv", "egfr"] assert find_rare_terms("How does HIV infect cells?", cfg) == ["hiv"] assert find_rare_terms("HOW DOES HIV AND EGFR act in the body?", cfg) == ["hiv", "egfr"] + # Acronyms do not push digit/hyphen terms past max_terms. + assert find_rare_terms( + "Do TNF, IFN, VEGF, EGFR, KRAS, BRAF, PTEN, MYC and IL-6 interact?", cfg + ) == ["il-6", "tnf", "ifn", "vegf", "egfr", "kras", "braf", "pten"] + # Acronyms do not suppress the long-term fallback when no tier-1 terms exist. + assert find_rare_terms("How does HIV integrase use methyltransferase activity?", cfg) == [ + "integrase", + "methyltransferase", + "hiv", + ] + assert find_rare_terms("Does ACE inhibition reduce fibrosis?", cfg) == ["inhibition", "ace"] + # All-caps prose and headings do not turn ordinary 3-4 letter words into acronyms. + assert find_rare_terms("HOW DOES HIV AND EGFR ACT IN THE BODY?", cfg) == [] + assert find_rare_terms("WHAT IS THE ROLE OF RNA IN CELL SIGNALING?", cfg) == ["signaling"] + assert find_rare_terms("WHAT IS THE ROLE OF TNF\u03b1 IN CELL SIGNALING?", cfg) == ["signaling"] + assert find_rare_terms("CAN HIV BIND EGFR?", cfg) == [] + assert find_rare_terms("B CELL LYMPHOMA", cfg) == [] + assert find_rare_terms("Roles of PROTEIN KINASE in CANCER", cfg) == [] + assert find_rare_terms("CANCER and cancer", cfg) == [] + assert find_rare_terms("cancer and CANCER", cfg) == [] + # Mixed-case queries starting with "A "/"I " or with 5+ char acronyms still keep acronyms. + assert find_rare_terms("A DNA/RNA assay", cfg) == ["dna", "rna"] + assert find_rare_terms("A JAK/STAT pathway", cfg) == ["jak", "stat"] + assert find_rare_terms("I study HIV and RNA", cfg) == ["hiv", "rna"] + assert find_rare_terms("CRISPR ELISA HIV assay", cfg) == ["hiv"] + # Em dashes and superscripts do not create bogus rare terms that kill fallback. + assert find_rare_terms( + "What causes fibrosis\u2014specifically methyltransferase dysregulation?", cfg + ) == ["specifically", "methyltransferase", "dysregulation"] + assert find_rare_terms("HIV\u2014a retrovirus", cfg) == ["retrovirus", "hiv"] + assert find_rare_terms("concentration 10\u207b\u00b3 M", cfg) == ["concentration"] + assert find_rare_terms("Ca\u00b2\u207a signaling", cfg) == ["signaling"] def test_find_rare_terms_falls_back_to_long_terms_and_caps(): @@ -214,8 +265,41 @@ def test_lexical_search_respects_limit_and_disable(lexical_db): assert backend.search([], None, LexicalConfig()).chunk_ids == [] +def test_lexical_search_word_boundaries_for_short_acronyms(tmp_path): + """Short alphabetic terms must match on word boundaries, not inside other words.""" + conn = init_db(tmp_path / "acronyms.sqlite3") + conn.executemany( + "INSERT INTO papers(id, doc_id, pmid, pmcid, title) VALUES (?, ?, ?, ?, ?)", + [ + (1, "d1", "1", "PMC1", "Journal of Internal Medicine"), + (2, "d2", "2", "PMC2", "RNA splicing mechanisms"), + ], + ) + conn.executemany( + "INSERT INTO chunks(id, paper_id, ord, text) VALUES (?, ?, ?, ?)", + [ + (10, 1, -1, "Published in this journal as an internal alternative control."), + (11, 1, 0, "Carcinoma and cardiac carbon studies on archived surface data."), + (12, 2, 0, "RNA-seq confirms RNA splicing in CAR T cells."), + (13, 2, 1, "ACE inhibition blocks (HIV) and HIV-1 entry."), + (14, 2, 2, "TNF\u03b1 and IFN\u03b3 regulate signaling."), + ], + ) + conn.commit() + try: + backend = SqliteLexicalBackend(conn, load_temp_candidates) + assert backend.search(["rna"], None, LexicalConfig()).chunk_ids == [12] + assert backend.search(["car"], None, LexicalConfig()).chunk_ids == [12] + assert backend.search(["hiv"], None, LexicalConfig()).chunk_ids == [13] + assert backend.search(["ace"], None, LexicalConfig()).chunk_ids == [13] + assert backend.search(["tnf"], None, LexicalConfig()).chunk_ids == [14] + assert backend.search(["ifn"], None, LexicalConfig()).chunk_ids == [14] + finally: + conn.close() + + def test_stage2_lexical_frontloads_uppercase_acronyms(tmp_path): - """Acronym-only queries must trigger lexical front-loading in Stage 2.""" + """Acronym queries front-load true word matches, not substring false positives.""" db_path = tmp_path / "stage2.sqlite3" conn = init_db(db_path) conn.execute( @@ -227,6 +311,7 @@ def test_stage2_lexical_frontloads_uppercase_acronyms(tmp_path): [ (10, 1, 0, "unrelated background text"), (11, 1, 1, "HIV binds EGFR on target cells"), + (12, 1, 2, "published in an internal journal with archived records"), ], ) conn.commit() @@ -234,18 +319,38 @@ def test_stage2_lexical_frontloads_uppercase_acronyms(tmp_path): index_path = tmp_path / "chunks.index" index = faiss.IndexIDMap2(flat_ip_index(4)) - # Chunk 10 aligns with the query vector; chunk 11 is orthogonal so ANN puts 10 first. - vecs = np.array([[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0]], dtype=np.float32) - index.add_with_ids(vecs, np.array([10, 11], dtype=np.int64)) + # Chunk 10 aligns with the query vector; chunks 11 and 12 are orthogonal so ANN puts 10 first. + vecs = np.array( + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], + dtype=np.float32, + ) + index.add_with_ids(vecs, np.array([10, 11, 12], dtype=np.int64)) faiss.write_index(index, str(index_path)) class _QueryEmbedder: def encode(self, texts): return np.array([[1.0, 0.0, 0.0, 0.0]], dtype=np.float32) + # Positive case: HIV/EGFR chunk (11) is front-loaded ahead of ANN winner (10); + # "archived" in chunk 12 does not match "hiv". chunk_ids, _ = search_chunks_constrained( "Does HIV bind EGFR?", candidate_papers=[1], + k=2, + chunk_index_path=index_path, + db_path=db_path, + embedder=_QueryEmbedder(), + connect_db=connect_db, + load_temp_candidates=load_temp_candidates, + chunk_ids_to_paper_ids=chunk_ids_to_paper_ids, + min_chunks_per_paper=1.0, + ) + assert chunk_ids == [11, 10] + + # Negative case: "journal"/"internal" in chunk 12 must not be front-loaded for "RNA". + rna_ids, _ = search_chunks_constrained( + "How does RNA work?", + candidate_papers=[1], k=1, chunk_index_path=index_path, db_path=db_path, @@ -255,7 +360,7 @@ def encode(self, texts): chunk_ids_to_paper_ids=chunk_ids_to_paper_ids, min_chunks_per_paper=1.0, ) - assert chunk_ids == [11] + assert rna_ids == [10] # ------------------------------------------------------------------- merging From f1c53b430c69391518f3e528a6c116e93e289d02 Mon Sep 17 00:00:00 2001 From: Bill Hlavacek Date: Tue, 1 Dec 2026 01:51:57 -0700 Subject: [PATCH 3/3] Keep acronyms in keyword queries and plural/numbered forms Address the second review round on #36: - Decide all-caps prose from stopwords or long, vowel-rich words, so keyword queries such as "EGFR NSCLC" and "HIV CRISPR" keep their acronyms while "B CELL LYMPHOMA" is still treated as prose. - Accept plural, inhibitor, and numbered suffixes on word-boundary matches (RNAs, RNAi, ACEi, TLR4, JAK2/STAT3), and search plural acronyms in questions by their stem (TLRs -> tlr). - Remove "all" from the stopwords so ALL (acute lymphoblastic leukemia) is searched. - Pass the raw column to litkit_word_match so SQLite evaluates the normalization chain once per row instead of twice. - Document the mixed-case emphasis-caps limitation in tests and update the CHANGELOG entry. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Bill Hlavacek --- CHANGELOG.md | 2 +- src/litkit/retrieval/helpers.py | 67 ++++++++++++++++++++++++--------- src/litkit/retrieval/lexical.py | 36 ++++++++++++------ tests/test_retrieval.py | 51 +++++++++++++++++++++---- 4 files changed, 119 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cb6415..5db106e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ internal versions are summarized under 0.3.33. ## [Unreleased] ### Fixed -- `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV` and `EGFR`) with word-boundary matching, prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. (#9) +- `query_terms()`, `find_rare_terms()`, and Stage-2 lexical front-loading now retain 3–4 character all-uppercase acronyms (such as `HIV`, `EGFR`, and `ALL`, plus plurals like `TLRs`) with word-boundary matching that still accepts plural, numbered, and inhibitor forms (`RNAs`, `TLR4`, `ACEi`), prioritize digit/hyphen and long-term matches ahead of acronyms, and normalize SQLite-compatible dashes and subscripts before tokenizing. All-caps prose such as `WHAT IS THE ROLE OF RNA` does not turn ordinary words into acronyms, while all-caps keyword queries such as `EGFR NSCLC` keep theirs. (#9) ## [0.3.36] - 2026-11-30 diff --git a/src/litkit/retrieval/helpers.py b/src/litkit/retrieval/helpers.py index 730ddb0..32abc74 100644 --- a/src/litkit/retrieval/helpers.py +++ b/src/litkit/retrieval/helpers.py @@ -16,11 +16,20 @@ "whose", "why", "how", "are", "is", "was", "were", "be", "been", "being", "of", "on", "in", "to", "a", "an", "as", "by", "at", "it", "its", "their", "them", "we", "you", "i", "can", "did", "not", "may", - "has", "had", "but", "all", "one", "use", "will", + "has", "had", "but", "one", "use", "will", } +# "all" is deliberately absent: as "ALL" it is acute lymphoblastic leukemia. _ACRONYM_MAX_LEN = 4 _ALPHA_WORD_RE = re.compile(r"[A-Za-z]+") +# Lowercase plural "s" on an all-caps token ("TLRs", "RCTs", "CD4s"). +_CAPS_PLURAL_S_RE = re.compile(r"(?<=[A-Z0-9])s\b") +# In all-caps text, a word this long with 2+ vowels reads as ordinary prose +# (LYMPHOMA, SIGNALING, CANCER), while long acronyms are usually vowel-poor +# (CRISPR, NSCLC, VEGFR). Five-letter words are ambiguous (COVID vs TUMOR), so +# they are not evidence either way. +_PROSE_WORD_MIN_LEN = 6 +_VOWELS = frozenset("AEIOU") _TOKEN_RE = re.compile(r"[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*") _EN_FIGURE_DASH_BETWEEN_ALNUM_RE = re.compile(r"(?<=[A-Za-z0-9])[\u2012\u2013](?=[A-Za-z0-9])") @@ -59,17 +68,37 @@ def _normalize_for_tokenize(s: str) -> str: return out.replace("\u2012", " ").replace("\u2013", " ") +def _is_prose_word(word: str) -> bool: + """Whether an all-caps word reads as ordinary prose rather than an acronym.""" + lowered = word.lower() + if lowered in _STOPWORDS and lowered != "and": + return True + return len(word) >= _PROSE_WORD_MIN_LEN and sum(ch in _VOWELS for ch in word.upper()) >= 2 + + def _is_all_caps_prose(s: str) -> bool: - """Detect all-caps sentences/headings where uppercase does not mark acronyms.""" - if any(ch.isascii() and ch.islower() for ch in s): - return False - words = [w for w in _ALPHA_WORD_RE.findall(s) if len(w) >= 2] - if not words: + """Detect all-caps sentences/headings where uppercase does not mark acronyms. + + True only when the text has no lowercase ASCII letters (ignoring the plural + "s" of tokens like "TLRs") and contains a stopword or a long, vowel-rich word: + "WHAT IS THE ROLE OF RNA" and "B CELL LYMPHOMA" are prose, while keyword + queries such as "EGFR NSCLC" or "HIV CRISPR" keep their acronyms. + """ + if any(ch.isascii() and ch.islower() for ch in _CAPS_PLURAL_S_RE.sub("", s)): return False - return any( - (w.lower() in _STOPWORDS and w.lower() != "and") or len(w) > _ACRONYM_MAX_LEN - for w in words - ) + return any(_is_prose_word(w) for w in _ALPHA_WORD_RE.findall(s) if len(w) >= 2) + + +def _acronym_stem(token: str) -> str | None: + """Return the 3-4 character all-caps acronym in a token, or None. + + A lowercase plural "s" is dropped ("TLRs" -> "TLR") so the term also matches + the singular and numbered forms in the corpus. + """ + stem = token[:-1] if len(token) > 3 and token.endswith("s") else token + if 3 <= len(stem) <= _ACRONYM_MAX_LEN and stem.isupper(): + return stem + return None def _extract_query_terms(s: str) -> list[tuple[str, bool]]: @@ -78,8 +107,8 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: Applies SQLite-compatible dash and subscript normalization (without NFKC) before tokenizing ASCII alphanumeric/hyphen/underscore words of at least 3 characters, checking uppercase status before lowercasing. All-uppercase - 3-4 character tokens are flagged as acronyms unless the input is all-caps - prose. + 3-4 character tokens, and their lowercase-"s" plurals, are flagged as + acronyms unless the input is all-caps prose. """ normalized = _normalize_for_tokenize(s) allow_acronyms = not _is_all_caps_prose(normalized) @@ -88,13 +117,14 @@ def _extract_query_terms(s: str) -> list[tuple[str, bool]]: for w in _TOKEN_RE.findall(normalized): if len(w) < 3: continue - lowered = w.lower() - if lowered in _STOPWORDS or lowered in seen: + stem = _acronym_stem(w) if allow_acronyms else None + term = (stem or w).lower() + if term in _STOPWORDS or term in seen: continue - is_acronym = allow_acronyms and w.isupper() and len(w) <= _ACRONYM_MAX_LEN + is_acronym = stem is not None if len(w) >= 5 or is_acronym or any(ch.isdigit() for ch in w) or "_" in w or "-" in w: - seen.add(lowered) - out.append((lowered, is_acronym)) + seen.add(term) + out.append((term, is_acronym)) return out @@ -106,7 +136,8 @@ def query_terms(s: str) -> list[str]: filters out stopwords, and lowercases kept terms while preserving order. Keeps tokens that are: - 5+ characters long - - 3-4 character all-uppercase acronyms (unless input is all-caps prose) + - 3-4 character all-uppercase acronyms, plural "s" dropped (unless input + is all-caps prose) - Contain digits - Contain underscores or hyphens diff --git a/src/litkit/retrieval/lexical.py b/src/litkit/retrieval/lexical.py index bd1bf33..f2a1343 100644 --- a/src/litkit/retrieval/lexical.py +++ b/src/litkit/retrieval/lexical.py @@ -38,15 +38,29 @@ @lru_cache(maxsize=256) def _word_boundary_re(term: str) -> re.Pattern[str]: - # Require ASCII alphanumeric boundaries (matching _TOKEN_RE) so short - # acronyms match 'RNA-seq', '(HIV)', and 'TNFα' without matching 'journal'. - return re.compile(rf"(? int: - if not text or not term: + # ASCII alphanumeric boundaries (matching _TOKEN_RE), so 'rna' matches + # 'RNA-seq', '(RNA)' and 'TNFα' but not 'journal' or 'internal'. An + # optional plural "s", inhibitor "i", or number (plus one letter) suffix keeps + # forms such as 'RNAs', 'RNAi', 'ACEi', 'TLR4', 'JAK2/STAT3' and 'STAT5a'. + # IGNORECASE with ASCII mirrors SQLite's ASCII-only lower(). + return re.compile( + rf"(? int: + """SQLite function: 1 if ``term`` occurs in ``text`` on word boundaries, else 0. + + Takes the raw column so SQLite evaluates the sqlite_norm_expr() chain only + once per row (for the LIKE prefilter). Of that chain, only soft-hyphen + removal can change which characters are adjacent to a term, so it is the + only replacement repeated here; Unicode dashes and subscript digits act as + boundaries either way. + """ + if not isinstance(text, str) or not isinstance(term, str) or not text or not term: return 0 - return 1 if _word_boundary_re(term).search(text) else 0 + return 1 if _word_boundary_re(term).search(text.replace("\u00ad", "")) else 0 def _needs_word_boundary(norm_term: str) -> bool: @@ -129,7 +143,7 @@ def find_rare_terms(question: str, config: LexicalConfig) -> list[str]: Prioritizes: 1. Terms with digits (H1N1, IL-6, CD4) or hyphens/underscores (P-gp, a_b) 2. Long terms (config.min_term_length+) as fallback when tier 1 is empty - 3. 3-4 character all-uppercase acronyms (HIV, EGFR), ordered after higher + 3. 3-4 character all-uppercase acronyms (HIV, EGFR; TLRs -> tlr), ordered after higher tiers so they never crowd out digit/hyphen terms or disable fallback Args: @@ -216,7 +230,7 @@ def search( like_param = f"%{escape_like(nt)}%" if _needs_word_boundary(nt): like_parts.append( - f"({norm} LIKE ? ESCAPE '\\' AND litkit_word_match({norm}, ?))" + f"({norm} LIKE ? ESCAPE '\\' AND litkit_word_match(c.text, ?))" ) params.extend([like_param, nt]) else: @@ -229,7 +243,7 @@ def search( title_norm = sqlite_norm_expr("p.title") if title_hint and _needs_word_boundary(title_hint): title_expr = ( - f"({title_norm} LIKE ? ESCAPE '\\' AND litkit_word_match({title_norm}, ?))" + f"({title_norm} LIKE ? ESCAPE '\\' AND litkit_word_match(p.title, ?))" ) title_params: list[object] = [f"%{escape_like(title_hint)}%", title_hint] else: diff --git a/tests/test_retrieval.py b/tests/test_retrieval.py index c6e4a45..0c43de6 100644 --- a/tests/test_retrieval.py +++ b/tests/test_retrieval.py @@ -51,6 +51,11 @@ def test_query_terms_keeps_uppercase_acronyms(): "hiv", "methyltransferase", ] + # ALL (acute lymphoblastic leukemia) is an acronym, not a stopword. + assert query_terms("ALL") == ["all"] + # Plural acronyms keep their 3-4 letter stem, so they also match singular forms. + assert query_terms("Do TLRs, RCTs and GPCRs agree?") == ["tlr", "rct", "gpcr", "agree"] + assert query_terms("HIV and HIVs") == ["hiv"] def test_query_terms_handles_edge_cases_and_unicode(): @@ -119,6 +124,13 @@ def test_find_rare_terms_keeps_uppercase_acronyms(): assert find_rare_terms("WHAT IS THE ROLE OF TNF\u03b1 IN CELL SIGNALING?", cfg) == ["signaling"] assert find_rare_terms("CAN HIV BIND EGFR?", cfg) == [] assert find_rare_terms("B CELL LYMPHOMA", cfg) == [] + # All-caps keyword queries keep their acronyms: long acronyms are vowel-poor + # (NSCLC, VEGFR, CRISPR), so unlike LYMPHOMA they do not mark the text as prose. + assert find_rare_terms("EGFR NSCLC", cfg) == ["egfr"] + assert find_rare_terms("VEGFR HCC", cfg) == ["hcc"] + assert find_rare_terms("HIV CRISPR", cfg) == ["hiv"] + # A plural acronym's lowercase "s" does not make all-caps prose look mixed-case. + assert find_rare_terms("WHAT IS THE ROLE OF TLRs IN SEPSIS?", cfg) == [] assert find_rare_terms("Roles of PROTEIN KINASE in CANCER", cfg) == [] assert find_rare_terms("CANCER and cancer", cfg) == [] assert find_rare_terms("cancer and CANCER", cfg) == [] @@ -127,6 +139,18 @@ def test_find_rare_terms_keeps_uppercase_acronyms(): assert find_rare_terms("A JAK/STAT pathway", cfg) == ["jak", "stat"] assert find_rare_terms("I study HIV and RNA", cfg) == ["hiv", "rna"] assert find_rare_terms("CRISPR ELISA HIV assay", cfg) == ["hiv"] + # ALL (acute lymphoblastic leukemia) is searched like any other acronym. + assert find_rare_terms("What is the prognosis of pediatric ALL?", cfg) == [ + "prognosis", + "pediatric", + "all", + ] + assert find_rare_terms("ALL vs AML outcomes", cfg) == ["all", "aml"] + # Plural acronyms in the question are searched by their stem. + assert find_rare_terms("Do TLRs sense RNA viruses?", cfg) == ["tlr", "rna"] + # Known limitation: a 3-4 letter word written in caps for emphasis in a mixed-case + # question cannot be told apart from an acronym, so it is searched (word-bounded). + assert find_rare_terms("What is the ROLE of HIV?", cfg) == ["role", "hiv"] # Em dashes and superscripts do not create bogus rare terms that kill fallback. assert find_rare_terms( "What causes fibrosis\u2014specifically methyltransferase dysregulation?", cfg @@ -279,21 +303,34 @@ def test_lexical_search_word_boundaries_for_short_acronyms(tmp_path): "INSERT INTO chunks(id, paper_id, ord, text) VALUES (?, ?, ?, ?)", [ (10, 1, -1, "Published in this journal as an internal alternative control."), - (11, 1, 0, "Carcinoma and cardiac carbon studies on archived surface data."), + (11, 1, 0, "Carcinoma and cardiac carbon statistics on archived surface data."), (12, 2, 0, "RNA-seq confirms RNA splicing in CAR T cells."), (13, 2, 1, "ACE inhibition blocks (HIV) and HIV-1 entry."), (14, 2, 2, "TNF\u03b1 and IFN\u03b3 regulate signaling."), + # Plural, numbered, and inhibitor forms of an acronym still match. + (15, 2, 3, "JAK2/STAT3 and TLR4 signaling drive CARs."), + (16, 2, 4, "Long noncoding RNAs, RNAi, HIV1 isolates and ACEi therapy."), + # A soft hyphen inside the acronym is ignored, as in sqlite_norm_expr(); + # a lowercase prefix ("mRNA") is a different word. + (17, 2, 5, "mRNA vaccines elicit anti\u2011H\u00adIV responses."), ], ) conn.commit() try: backend = SqliteLexicalBackend(conn, load_temp_candidates) - assert backend.search(["rna"], None, LexicalConfig()).chunk_ids == [12] - assert backend.search(["car"], None, LexicalConfig()).chunk_ids == [12] - assert backend.search(["hiv"], None, LexicalConfig()).chunk_ids == [13] - assert backend.search(["ace"], None, LexicalConfig()).chunk_ids == [13] - assert backend.search(["tnf"], None, LexicalConfig()).chunk_ids == [14] - assert backend.search(["ifn"], None, LexicalConfig()).chunk_ids == [14] + + def ids(term): + return backend.search([term], None, LexicalConfig()).chunk_ids + + assert ids("rna") == [12, 16] + assert ids("car") == [12, 15] + assert ids("hiv") == [13, 16, 17] + assert ids("ace") == [13, 16] + assert ids("tnf") == [14] + assert ids("ifn") == [14] + assert ids("jak") == [15] + assert ids("stat") == [15] + assert ids("tlr") == [15] finally: conn.close()