85 lines
3.3 KiB
Python
85 lines
3.3 KiB
Python
"""Question-to-article ranking: BM25 + cosine, reciprocal rank fusion.
|
|
|
|
The candidate pool is small (all results from this call's searches), so BM25
|
|
needs no external index or dependency. Snippets guide fetching, never answers.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
from collections import Counter
|
|
from dataclasses import dataclass
|
|
|
|
from .queries import WORD_RE
|
|
from .store import stem
|
|
from .wiki import WikiSearchResult
|
|
|
|
|
|
def merge_search_results(per_query: list[list[WikiSearchResult]]) -> list[WikiSearchResult]:
|
|
"""Deduplicate by title, retaining distinct query-specific snippets."""
|
|
snippets: dict[str, list[str]] = {}
|
|
for results in per_query:
|
|
for hit in results:
|
|
parts = snippets.setdefault(hit.title, [])
|
|
if hit.snippet and hit.snippet not in parts:
|
|
parts.append(hit.snippet)
|
|
return [WikiSearchResult(title, "\n".join(parts))
|
|
for title, parts in snippets.items()]
|
|
|
|
|
|
def bm25_scores(question: str, documents: list[str]) -> list[float]:
|
|
"""Okapi BM25 (k1=1.5, b=0.75), with positive Robertson IDF.
|
|
|
|
Query terms come from the full question, never the composed searches.
|
|
Tokenization and stemming are shared with the existing lexical retrieval.
|
|
"""
|
|
counts = [Counter(stem(t) for t in WORD_RE.findall(doc.casefold()))
|
|
for doc in documents]
|
|
lengths = [sum(c.values()) for c in counts]
|
|
avg_length = sum(lengths) / len(lengths) if lengths else 0
|
|
if not avg_length:
|
|
return [0.0] * len(documents)
|
|
terms = sorted({stem(t) for t in WORD_RE.findall(question.casefold())})
|
|
df = Counter(t for c in counts for t in c)
|
|
idf = {t: math.log1p((len(counts) - df[t] + 0.5) / (df[t] + 0.5))
|
|
for t in terms}
|
|
return [sum(idf[t] * (c[t] * 2.5) /
|
|
(c[t] + 1.5 * (0.25 + 0.75 * length / avg_length))
|
|
for t in terms if c[t])
|
|
for c, length in zip(counts, lengths)]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RankedArticle:
|
|
article: WikiSearchResult
|
|
bm25: float
|
|
semantic: float | None
|
|
score: float
|
|
|
|
|
|
def rank_articles(question: str, articles: list[WikiSearchResult],
|
|
similarities: list[float] | None = None) -> list[RankedArticle]:
|
|
"""Equal-weight RRF (k=60), or BM25 alone when semantics are unavailable.
|
|
|
|
Equal scores share a rank, so lexical misses or tied cosine scores do not
|
|
introduce an arbitrary preference. Final ties preserve search encounter order.
|
|
"""
|
|
lexical = bm25_scores(question, [a.text for a in articles])
|
|
if similarities is not None:
|
|
if len(similarities) != len(articles) or not all(
|
|
math.isfinite(s) for s in similarities):
|
|
raise ValueError("one finite semantic similarity is required per article")
|
|
|
|
def reciprocal_rank(scores: list[float], value: float) -> float:
|
|
rank = 1 + sum(s > value for s in scores)
|
|
return 1.0 / (60 + rank)
|
|
|
|
ranked = []
|
|
for i, article in enumerate(articles):
|
|
semantic = similarities[i] if similarities is not None else None
|
|
score = lexical[i]
|
|
if similarities is not None:
|
|
score = reciprocal_rank(lexical, lexical[i])
|
|
score += reciprocal_rank(similarities, similarities[i])
|
|
ranked.append(RankedArticle(article, lexical[i], semantic, score))
|
|
return sorted(ranked, key=lambda a: a.score, reverse=True)
|