Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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()`, `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

Expand Down
175 changes: 122 additions & 53 deletions src/litkit/retrieval/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,55 +5,149 @@
"""
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",
"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", "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])")

# 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(
{
**{
ch: repl
for ch, repl in _SQLITE_NORM_REPLACEMENTS
if ch not in ("\u2012", "\u2013", "\u2014")
},
"\u2014": " ",
}
)


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_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.

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(_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]]:
"""Extract normalized query terms paired with an acronym flag.

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, 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)
out: list[tuple[str, bool]] = []
seen: set[str] = set()
for w in _TOKEN_RE.findall(normalized):
if len(w) < 3:
continue
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 = 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(term)
out.append((term, is_acronym))
return out


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:

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 and 3+ chars
- 3-4 character all-uppercase acronyms, plural "s" dropped (unless input
is all-caps prose)
- Contain digits
- Contain underscores or hyphens

Args:
s: Input string (typically a question)

Returns:
List of unique query terms in original order
"""
words = re.findall(r"[A-Za-z0-9_-]{3,}", s)
out = []
seen = set()
for w in words:
lowered = w.lower()
if lowered in _STOPWORDS or lowered in seen:
continue
if (
len(w) >= 5
or (w.isupper() and len(w) >= 3)
or any(ch.isdigit() for ch in w)
or "_" in w
or "-" in w
):
seen.add(lowered)
out.append(lowered)
return out
return [term for term, _ in _extract_query_terms(s)]


def sqlite_norm_expr(field: str = "text") -> str:
Expand All @@ -71,21 +165,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


Expand Down Expand Up @@ -118,19 +199,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 unicodedata.normalize("NFKC", s).lower().translate(_SQLITE_NORM_TRANS)


def avg_chunks_for_papers(
Expand Down
Loading
Loading