File size: 1,436 Bytes
46e547f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""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