EllaNAM's picture
Add editable evaluation notebooks and their Python source
46e547f verified
Raw History Blame Contribute Delete
1.44 kB
"""Plain Wikipedia title and bounded BM25 query expansion."""
from __future__ import annotations
import re
from typing import Iterable
from .lexical_tokens import content_terms, input_terms
_DISAMBIGUATION_RE = re.compile(r"^(.+?)\s*\(([^()]+)\)$")
def structure_title(title: str | None) -> str:
normalized = " ".join((title or "").split())
match = _DISAMBIGUATION_RE.match(normalized)
return " ".join(match.groups()) if match else normalized
def build_lexical_text(
*,
title: str,
resolved_text: str,
pseudo_queries: Iterable[str] = (),
) -> str:
"""Keep all title and body tokens, then add at most 25% new lexical terms."""
base = "\n".join(part for part in (structure_title(title), resolved_text.strip()) if part)
terms = input_terms(base)
budget = min(24, len(terms) // 4)
if budget == 0:
return base
anchors = set(content_terms(terms))
seen = set(terms)
expansion = []
for question in pseudo_queries:
question_terms = content_terms(input_terms(question))
if not anchors.intersection(question_terms):
continue
for term in question_terms:
if term not in seen:
expansion.append(term)
seen.add(term)
if len(expansion) == budget:
return base + "\n" + " ".join(expansion)
return base + "\n" + " ".join(expansion) if expansion else base