Delete retrieval.py
Browse files- retrieval.py +0 -274
retrieval.py
DELETED
|
@@ -1,274 +0,0 @@
|
|
| 1 |
-
"""Arabic text normalisation and source retrieval over the Quran and Hadith corpora.
|
| 2 |
-
|
| 3 |
-
The retriever is the single shared index used by both verification and correction. It was extracted from the
|
| 4 |
-
IslamicEval 2025 research notebook (``research/IslamicEval_Unified.ipynb``) and keeps its retrieval logic:
|
| 5 |
-
|
| 6 |
-
* Quran: word-vote retrieval of single ayahs (coverage / precision F1) plus IDF-weighted seeds for
|
| 7 |
-
multi-ayah window search.
|
| 8 |
-
* Hadith: IDF word-vote recall followed by a character 4-gram cosine re-rank.
|
| 9 |
-
"""
|
| 10 |
-
from __future__ import annotations
|
| 11 |
-
|
| 12 |
-
import gzip
|
| 13 |
-
import json
|
| 14 |
-
import logging
|
| 15 |
-
import math
|
| 16 |
-
import os
|
| 17 |
-
import re
|
| 18 |
-
import unicodedata
|
| 19 |
-
from collections import Counter, defaultdict
|
| 20 |
-
from pathlib import Path
|
| 21 |
-
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
|
| 22 |
-
|
| 23 |
-
logger = logging.getLogger(__name__)
|
| 24 |
-
|
| 25 |
-
BASE_DIR = Path(__file__).resolve().parent
|
| 26 |
-
DEFAULT_QURAN_PATH = BASE_DIR / "data" / "quran.json"
|
| 27 |
-
DEFAULT_HADITH_PATH = BASE_DIR / "data" / "hadith.json"
|
| 28 |
-
|
| 29 |
-
# --------------------------------------------------------------------------------------------------------------
|
| 30 |
-
# Arabic normalisation
|
| 31 |
-
# --------------------------------------------------------------------------------------------------------------
|
| 32 |
-
_DIACRITICS = re.compile(
|
| 33 |
-
r"[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0640]"
|
| 34 |
-
)
|
| 35 |
-
_PUNCTUATION = re.compile(r"[،؛؟!،.,:;'\"()\[\]{}<>«»\-_/\\|@#$%^&*+=~`]")
|
| 36 |
-
_MULTI_SPACE = re.compile(r"\s+")
|
| 37 |
-
_ALEF_VARIANTS = re.compile(r"[أإآٱ]")
|
| 38 |
-
_MATCH_DIACRITICS = re.compile(r"[\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E8\u06EA-\u06ED\u0640]")
|
| 39 |
-
|
| 40 |
-
STOPWORDS = frozenset(
|
| 41 |
-
"""من في على ان أن إن الى إلى عن مع ما لا لم لن قد و ثم أو او هو هي هم انت أنتم كان كانت يكون تكون قال قالت
|
| 42 |
-
هذا هذه ذلك تلك الذي التي الذين اللاتي اللائي كل بعض غير عند بين حتى إذا اذا لو لكن بل يا أيها ايها""".split()
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
def normalize_strict(text: Optional[str]) -> str:
|
| 47 |
-
"""Remove diacritics, unify alef variants and strip punctuation (keeps ta marbuta / alef maqsura)."""
|
| 48 |
-
if not text:
|
| 49 |
-
return ""
|
| 50 |
-
text = unicodedata.normalize("NFC", text)
|
| 51 |
-
text = _DIACRITICS.sub("", text)
|
| 52 |
-
text = _ALEF_VARIANTS.sub("ا", text)
|
| 53 |
-
text = _PUNCTUATION.sub(" ", text)
|
| 54 |
-
return _MULTI_SPACE.sub(" ", text).strip()
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
def normalize_lenient(text: Optional[str]) -> str:
|
| 58 |
-
"""Strict normalisation plus ta-marbuta/ha and alef-maqsura/ya folding (used for Hadith, whose spelling varies)."""
|
| 59 |
-
return normalize_strict(text).replace("ة", "ه").replace("ى", "ي")
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
def normalize_for_matching(text: Optional[str]) -> str:
|
| 63 |
-
"""Aggressive normalisation used for window matching: keeps only Arabic letters and single spaces."""
|
| 64 |
-
if not text:
|
| 65 |
-
return ""
|
| 66 |
-
text = _MATCH_DIACRITICS.sub("", text)
|
| 67 |
-
for src, dst in (("أ", "ا"), ("إ", "ا"), ("آ", "ا"), ("ٱ", "ا"), ("ؤ", "و"), ("ئ", "ي"), ("ة", "ه"), ("ى", "ي")):
|
| 68 |
-
text = text.replace(src, dst)
|
| 69 |
-
text = re.sub(r"[^\u0600-\u06FF\s]", " ", text)
|
| 70 |
-
return re.sub(r"\s+", " ", text).strip()
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
def tokenize(text: str) -> List[str]:
|
| 74 |
-
return [token for token in text.split() if token]
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def content_words(tokens: Iterable[str]) -> List[str]:
|
| 78 |
-
"""Drop stop-words and single-letter tokens."""
|
| 79 |
-
return [t for t in tokens if t not in STOPWORDS and len(t) > 1]
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
def _char_ngrams(text: str, n: int = 4) -> set:
|
| 83 |
-
return {text[i : i + n] for i in range(len(text) - n + 1)}
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
# --------------------------------------------------------------------------------------------------------------
|
| 87 |
-
# Retriever
|
| 88 |
-
# --------------------------------------------------------------------------------------------------------------
|
| 89 |
-
class CorpusError(RuntimeError):
|
| 90 |
-
"""Raised when a corpus file is missing or malformed."""
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
class SourceRetriever:
|
| 94 |
-
"""In-memory index over ``quran.json`` and ``hadith.json`` (builds in a few seconds)."""
|
| 95 |
-
|
| 96 |
-
def __init__(
|
| 97 |
-
self,
|
| 98 |
-
quran_path: os.PathLike = DEFAULT_QURAN_PATH,
|
| 99 |
-
hadith_path: os.PathLike = DEFAULT_HADITH_PATH,
|
| 100 |
-
) -> None:
|
| 101 |
-
quran_path, hadith_path = Path(quran_path), Path(hadith_path)
|
| 102 |
-
gzipped = hadith_path.with_name(hadith_path.name + ".gz")
|
| 103 |
-
if not hadith_path.is_file() and gzipped.is_file(): # compressed copy used by the in-browser deployment
|
| 104 |
-
hadith_path = gzipped
|
| 105 |
-
for path in (quran_path, hadith_path):
|
| 106 |
-
if not path.is_file():
|
| 107 |
-
raise CorpusError(f"Corpus file not found: {path}")
|
| 108 |
-
|
| 109 |
-
self.__dict__.update(self._build(quran_path, hadith_path))
|
| 110 |
-
|
| 111 |
-
n_ayahs, n_hadith = len(self.quran), len(self.hadith)
|
| 112 |
-
self.quran_idf = {w: math.log((n_ayahs + 1) / (len(d) + 1)) + 1 for w, d in self.q_content_index.items()}
|
| 113 |
-
self.hadith_idf = {w: math.log((n_hadith + 1) / (len(d) + 1)) + 1 for w, d in self.h_content_index.items()}
|
| 114 |
-
logger.info("Retriever ready: %d ayahs, %d hadith records", n_ayahs, n_hadith)
|
| 115 |
-
|
| 116 |
-
# ---- construction ---------------------------------------------------------------------------------------
|
| 117 |
-
@staticmethod
|
| 118 |
-
def _read_json(path: Path) -> list:
|
| 119 |
-
try:
|
| 120 |
-
opener = gzip.open if path.suffix == ".gz" else open
|
| 121 |
-
with opener(path, "rt", encoding="utf-8") as handle:
|
| 122 |
-
data = json.load(handle)
|
| 123 |
-
except (OSError, json.JSONDecodeError) as exc:
|
| 124 |
-
raise CorpusError(f"Cannot read corpus file {path}: {exc}") from exc
|
| 125 |
-
if not isinstance(data, list):
|
| 126 |
-
raise CorpusError(f"Unexpected corpus format in {path}: expected a JSON list")
|
| 127 |
-
return data
|
| 128 |
-
|
| 129 |
-
def _build(self, quran_path: Path, hadith_path: Path) -> dict:
|
| 130 |
-
quran: List[dict] = []
|
| 131 |
-
q_norm_match: List[str] = []
|
| 132 |
-
q_all_index: Dict[str, List[int]] = defaultdict(list)
|
| 133 |
-
q_content_index: Dict[str, List[int]] = defaultdict(list)
|
| 134 |
-
q_word_count: List[int] = []
|
| 135 |
-
by_surah: Dict[int, Dict[int, int]] = defaultdict(dict)
|
| 136 |
-
|
| 137 |
-
for entry in self._read_json(quran_path):
|
| 138 |
-
text = (entry.get("ayah_text") or "").strip()
|
| 139 |
-
if not text:
|
| 140 |
-
continue
|
| 141 |
-
idx = len(quran)
|
| 142 |
-
quran.append(
|
| 143 |
-
{
|
| 144 |
-
"surah_id": entry.get("surah_id"),
|
| 145 |
-
"surah_name": entry.get("surah_name", ""),
|
| 146 |
-
"ayah_id": entry.get("ayah_id"),
|
| 147 |
-
"text": text,
|
| 148 |
-
}
|
| 149 |
-
)
|
| 150 |
-
by_surah[entry.get("surah_id")][entry.get("ayah_id")] = idx
|
| 151 |
-
q_norm_match.append(normalize_for_matching(text))
|
| 152 |
-
tokens = tokenize(normalize_strict(text))
|
| 153 |
-
q_word_count.append(len(tokens))
|
| 154 |
-
for word in set(tokens):
|
| 155 |
-
q_all_index[word].append(idx)
|
| 156 |
-
for word in set(content_words(q_norm_match[-1].split())):
|
| 157 |
-
q_content_index[word].append(idx)
|
| 158 |
-
|
| 159 |
-
hadith: List[dict] = []
|
| 160 |
-
h_content_index: Dict[str, List[int]] = defaultdict(list)
|
| 161 |
-
for entry in self._read_json(hadith_path):
|
| 162 |
-
if not entry:
|
| 163 |
-
continue
|
| 164 |
-
matn = (entry.get("Matn") or "").strip() or None
|
| 165 |
-
full = (entry.get("hadithTxt") or "").strip() or None
|
| 166 |
-
if not (matn or full):
|
| 167 |
-
continue
|
| 168 |
-
record = {
|
| 169 |
-
"hadithID": entry.get("hadithID"),
|
| 170 |
-
"book": entry.get("BookID"),
|
| 171 |
-
"title": entry.get("title"),
|
| 172 |
-
"matn": matn,
|
| 173 |
-
"full": full,
|
| 174 |
-
"norm_matn": normalize_for_matching(matn) if matn else None,
|
| 175 |
-
"norm_full": normalize_for_matching(full) if full else None,
|
| 176 |
-
}
|
| 177 |
-
idx = len(hadith)
|
| 178 |
-
hadith.append(record)
|
| 179 |
-
words = set()
|
| 180 |
-
for key in ("norm_matn", "norm_full"):
|
| 181 |
-
if record[key]:
|
| 182 |
-
words |= set(content_words(record[key].split()))
|
| 183 |
-
for word in words:
|
| 184 |
-
h_content_index[word].append(idx)
|
| 185 |
-
|
| 186 |
-
return {
|
| 187 |
-
"quran": quran,
|
| 188 |
-
"quran_by_surah": dict(by_surah),
|
| 189 |
-
"q_norm_match": q_norm_match,
|
| 190 |
-
"q_all_index": dict(q_all_index),
|
| 191 |
-
"q_content_index": dict(q_content_index),
|
| 192 |
-
"q_word_count": q_word_count,
|
| 193 |
-
"hadith": hadith,
|
| 194 |
-
"h_content_index": dict(h_content_index),
|
| 195 |
-
}
|
| 196 |
-
|
| 197 |
-
# ---- Quran ----------------------------------------------------------------------------------------------
|
| 198 |
-
def search_quran_ayahs(self, query: str, top_k: int = 25, extra_seeds: int = 10) -> List[dict]:
|
| 199 |
-
"""Single-ayah candidates ranked by the F1 of query coverage and ayah precision.
|
| 200 |
-
|
| 201 |
-
The F1 ranking favours short ayahs, so a fragment of a long ayah can be missed; the top IDF-voted ayahs
|
| 202 |
-
(rare-word matches) are appended as extra candidates to recover those partial quotations."""
|
| 203 |
-
query_words = tokenize(normalize_strict(query))
|
| 204 |
-
if not query_words:
|
| 205 |
-
return []
|
| 206 |
-
votes: Dict[int, int] = defaultdict(int)
|
| 207 |
-
for word in query_words:
|
| 208 |
-
for idx in self.q_all_index.get(word, ()):
|
| 209 |
-
votes[idx] += 1
|
| 210 |
-
scored: List[Tuple[int, float]] = []
|
| 211 |
-
for idx, vote in votes.items():
|
| 212 |
-
coverage = vote / len(query_words)
|
| 213 |
-
precision = vote / self.q_word_count[idx] if self.q_word_count[idx] else 0.0
|
| 214 |
-
f1 = 2 * coverage * precision / (coverage + precision) if coverage + precision > 0 else 0.0
|
| 215 |
-
scored.append((idx, f1))
|
| 216 |
-
scored.sort(key=lambda item: item[1], reverse=True)
|
| 217 |
-
ranked = [idx for idx, _ in scored[:top_k]]
|
| 218 |
-
scores = dict(scored)
|
| 219 |
-
seeds = self.quran_seed_ayahs(content_words(normalize_for_matching(query).split()), extra_seeds)
|
| 220 |
-
ranked += [idx for idx in seeds if idx not in set(ranked)]
|
| 221 |
-
results = []
|
| 222 |
-
for idx in ranked:
|
| 223 |
-
candidate = dict(self.quran[idx])
|
| 224 |
-
candidate.update(type="Quran", retrieval_score=scores.get(idx, 0.0))
|
| 225 |
-
results.append(candidate)
|
| 226 |
-
return results
|
| 227 |
-
|
| 228 |
-
def quran_seed_ayahs(self, query_words: Sequence[str], top_k: int = 25) -> List[int]:
|
| 229 |
-
"""IDF-voted ayah indices used to seed the multi-ayah window search."""
|
| 230 |
-
return [idx for idx, _ in self.vote(self.q_content_index, self.quran_idf, query_words, top_k)]
|
| 231 |
-
|
| 232 |
-
# ---- Hadith ---------------------------------------------------------------------------------------------
|
| 233 |
-
def search_hadith(self, query: str, top_k: int = 15, pool: int = 40) -> List[dict]:
|
| 234 |
-
"""IDF word-vote recall, then re-rank by character 4-gram cosine similarity."""
|
| 235 |
-
words = content_words(normalize_for_matching(query).split())
|
| 236 |
-
if not words:
|
| 237 |
-
return []
|
| 238 |
-
query_grams = _char_ngrams(normalize_lenient(query))
|
| 239 |
-
results = []
|
| 240 |
-
for idx, _ in self.vote(self.h_content_index, self.hadith_idf, words, pool):
|
| 241 |
-
record = self.hadith[idx]
|
| 242 |
-
text = record["matn"] or record["full"]
|
| 243 |
-
doc_grams = _char_ngrams(normalize_lenient(text))
|
| 244 |
-
cosine = (
|
| 245 |
-
len(query_grams & doc_grams) / ((len(query_grams) * len(doc_grams)) ** 0.5)
|
| 246 |
-
if query_grams and doc_grams
|
| 247 |
-
else 0.0
|
| 248 |
-
)
|
| 249 |
-
results.append(
|
| 250 |
-
{
|
| 251 |
-
"type": "Hadith",
|
| 252 |
-
"idx": idx,
|
| 253 |
-
"hadithID": record["hadithID"],
|
| 254 |
-
"book": record["book"],
|
| 255 |
-
"title": record["title"],
|
| 256 |
-
"text": text,
|
| 257 |
-
"has_matn": bool(record["matn"]),
|
| 258 |
-
"retrieval_score": cosine,
|
| 259 |
-
}
|
| 260 |
-
)
|
| 261 |
-
results.sort(key=lambda c: c["retrieval_score"], reverse=True)
|
| 262 |
-
return results[:top_k]
|
| 263 |
-
|
| 264 |
-
# ---- shared ---------------------------------------------------------------------------------------------
|
| 265 |
-
@staticmethod
|
| 266 |
-
def vote(index: Dict[str, List[int]], idf: Dict[str, float], words: Iterable[str], top_k: int) -> List[Tuple[int, float]]:
|
| 267 |
-
scores: Counter = Counter()
|
| 268 |
-
for word in set(words):
|
| 269 |
-
weight = idf.get(word, 0.0)
|
| 270 |
-
if weight <= 0:
|
| 271 |
-
continue
|
| 272 |
-
for doc in index.get(word, ()):
|
| 273 |
-
scores[doc] += weight
|
| 274 |
-
return scores.most_common(top_k)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|