wikipedia fetch Ranking combining BM25 lexical relevance and embedding cosine similarity through reciprocal rank fusion
This commit is contained in:
+33
-4
@@ -14,6 +14,7 @@ from __future__ import annotations
|
||||
import re
|
||||
import time
|
||||
from dataclasses import dataclass, field
|
||||
from html.parser import HTMLParser
|
||||
|
||||
import requests
|
||||
|
||||
@@ -22,6 +23,26 @@ UA = "floop-bot/0.1 (research; contact: emili@oniricapps.com)"
|
||||
LANG = "en"
|
||||
|
||||
|
||||
class _SnippetText(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.parts: list[str] = []
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
self.parts.append(data)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WikiSearchResult:
|
||||
"""Search metadata, not evidence: snippets still need a fetched source."""
|
||||
title: str
|
||||
snippet: str = ""
|
||||
|
||||
@property
|
||||
def text(self) -> str:
|
||||
return f"{self.title}\n{self.snippet}".strip()
|
||||
|
||||
|
||||
@dataclass
|
||||
class WikiTable:
|
||||
"""One parsed wikitext table: header row + all data rows, untruncated."""
|
||||
@@ -331,10 +352,18 @@ class WikipediaClient:
|
||||
raise WikiError(f"wikipedia api failed after {self.max_retries + 1} attempts: {last_err}")
|
||||
|
||||
# ---- api surface --------------------------------------------------------
|
||||
def search(self, query: str, limit: int = 5) -> list[str]:
|
||||
"""Official search: list=search. Returns candidate article titles."""
|
||||
data = self._get(action="query", list="search", srsearch=query, srlimit=limit)
|
||||
return [h["title"] for h in data.get("query", {}).get("search", [])]
|
||||
def search(self, query: str, limit: int = 5) -> list[WikiSearchResult]:
|
||||
"""Return titles and plain-text search snippets, without fetching pages."""
|
||||
data = self._get(action="query", list="search", srsearch=query,
|
||||
srlimit=limit, srprop="snippet", srnamespace=0)
|
||||
results = []
|
||||
for hit in data.get("query", {}).get("search", []):
|
||||
parser = _SnippetText()
|
||||
parser.feed(hit.get("snippet", ""))
|
||||
parser.close()
|
||||
snippet = " ".join("".join(parser.parts).split())
|
||||
results.append(WikiSearchResult(title=hit["title"], snippet=snippet))
|
||||
return results
|
||||
|
||||
def summary(self, title: str) -> str:
|
||||
data = self._get(action="query", titles=title, prop="extracts",
|
||||
|
||||
Reference in New Issue
Block a user