Download scripts/rag_retriever.py from codingforfun/aiccounting-demo: direct link, hf CLI and curl.
- Browser
- Download file 8.5 kB
-
https://huggingface.co/spaces/codingforfun/aiccounting-demo/resolve/main/scripts/rag_retriever.py
- Command line
-
hf download hf://spaces/codingforfun/aiccounting-demo/scripts/rag_retriever.py
-
curl -L -o rag_retriever.py https://huggingface.co/spaces/codingforfun/aiccounting-demo/resolve/main/scripts/rag_retriever.py
8.5 kB
| #!/usr/bin/env python3 | |
| """Hybrid retriever over data/retrieval/ (built by rag_index.py), with optional Jev reranking. | |
| r = Retriever() # BM25 + Qwen3-Embedding-0.6B | |
| hits = r.search("Berapa tarif PPh badan?", k=5) # BM25 + dense, fused with RRF, per unit | |
| hits = asyncio.run(r.rerank_jev(q, r.search(q, k=20), k=5)) # + Jev relevance judgment on the top 20 | |
| Each hit: {unit_id, sumber, title, score, passages: [best passage texts], ranks: {...}} | |
| Jev step (reranking) = a yes/no relevance judgment per (question, pasal) pair -> Noul probability. | |
| CLI: .venv/bin/python scripts/rag_retriever.py "pertanyaan ..." [--jev] | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import json | |
| import sys | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from rag_index import EMBEDDERS, OUT, tokenize # noqa: E402 | |
| RRF_K = 60 | |
| JEV_MODEL = "jev-latest" | |
| JEV_Q = ("Does the regulation text in `teks_pasal` itself state the legal rule, rate, threshold, procedure, " | |
| "deadline or definition needed to answer `pertanyaan`? Answer yes only if this text contains what is " | |
| "needed to answer; answer no if it is merely on the same general topic, only cross-references " | |
| "another article, or covers a different situation.") | |
| JEV_TEXT_CHARS = 5000 | |
| class Retriever: | |
| def __init__(self, dense: str | None = "qwen3-embedding-0.6b", bm25: bool = True): | |
| self.ps = [json.loads(l) for l in open(OUT / "passages.jsonl")] | |
| self.unit_ps: dict[str, list[int]] = defaultdict(list) | |
| for i, p in enumerate(self.ps): | |
| self.unit_ps[p["unit_id"]].append(i) | |
| self.bm25 = self.dense = None | |
| if bm25: | |
| import bm25s | |
| import Stemmer | |
| self.bm25 = bm25s.BM25.load(OUT / "bm25") | |
| self.vocab = json.load(open(OUT / "bm25" / "vocab_custom.json")) | |
| self.stem = Stemmer.Stemmer("indonesian") | |
| if dense: | |
| import torch | |
| from sentence_transformers import SentenceTransformer | |
| cfg = EMBEDDERS[dense] | |
| self.qfmt = cfg["query"] | |
| self.emb = np.load(OUT / f"emb_{dense}.npy").astype(np.float32) | |
| dev = "mps" if torch.backends.mps.is_available() else "cpu" | |
| self.dense = SentenceTransformer(cfg["repo"], device=dev, config_kwargs=cfg["config_kwargs"] or None, | |
| model_kwargs={"torch_dtype": torch.float32}) | |
| # ---- first stage ------------------------------------------------------------------------------------- | |
| def _bm25_scores(self, q: str) -> np.ndarray: | |
| ids = [self.vocab[t] for t in tokenize(q, self.stem) if t in self.vocab] | |
| return self.bm25.get_scores(ids) if ids else np.zeros(len(self.ps)) | |
| def _dense_scores(self, qs: list[str]) -> np.ndarray: | |
| e = self.dense.encode([self.qfmt(q) for q in qs], normalize_embeddings=True, convert_to_numpy=True) | |
| return e.astype(np.float32) @ self.emb.T | |
| def _unit_rank(self, pscores: np.ndarray, depth: int = 200) -> list[tuple[str, float, int]]: | |
| """Passage scores -> units ranked by their best passage. Returns (unit_id, score, best_passage_idx).""" | |
| best: dict[str, tuple[float, int]] = {} | |
| for i in np.argsort(-pscores)[: depth * 4]: | |
| u = self.ps[i]["unit_id"] | |
| if u not in best: | |
| best[u] = (float(pscores[i]), int(i)) | |
| if len(best) >= depth: | |
| break | |
| return [(u, s, i) for u, (s, i) in best.items()] | |
| def search(self, q: str, k: int = 10, mode: str = "hybrid", _dense_row: np.ndarray | None = None) -> list[dict]: | |
| lists = {} | |
| if mode in ("hybrid", "bm25") and self.bm25 is not None: | |
| lists["bm25"] = self._unit_rank(self._bm25_scores(q)) | |
| if mode in ("hybrid", "dense") and self.dense is not None: | |
| row = _dense_row if _dense_row is not None else self._dense_scores([q])[0] | |
| lists["dense"] = self._unit_rank(row) | |
| fused: dict[str, dict] = {} | |
| for name, ranked in lists.items(): | |
| for r, (u, s, i) in enumerate(ranked): | |
| h = fused.setdefault(u, {"unit_id": u, "score": 0.0, "ranks": {}, "best": set()}) | |
| h["score"] += 1.0 / (RRF_K + r + 1) | |
| h["ranks"][name] = r + 1 | |
| h["best"].add(i) | |
| hits = sorted(fused.values(), key=lambda h: -h["score"])[:k] | |
| for h in hits: | |
| pi = sorted(h.pop("best")) | |
| h["title"] = self.ps[pi[0]]["title"] | |
| h["sumber"] = h["title"].split(" — ")[0] | |
| h["passages"] = [self.ps[i]["text"] for i in pi] | |
| return hits | |
| def candidates(self, q: str, k_bm25: int = 20, k_dense: int = 10, _dense_row=None) -> list[dict]: | |
| """Candidate pool for reranking: BM25 top-k plus dense top-k not already in it (BM25 order first). | |
| On the val set BM25 alone covers more gold pasal than RRF fusion; dense is kept as a safety net for | |
| questions phrased differently from the regulation text.""" | |
| pool = self.search(q, k_bm25, "bm25") | |
| if self.dense is not None and k_dense: | |
| seen = {h["unit_id"] for h in pool} | |
| pool += [h for h in self.search(q, k_dense, "dense", _dense_row=_dense_row) if h["unit_id"] not in seen] | |
| return pool | |
| def candidates_many(self, qs: list[str], k_bm25: int = 20, k_dense: int = 10) -> list[list[dict]]: | |
| rows = self._dense_scores(qs) if self.dense is not None else [None] * len(qs) | |
| return [self.candidates(q, k_bm25, k_dense, _dense_row=rows[i]) for i, q in enumerate(qs)] | |
| def search_many(self, qs: list[str], k: int = 10, mode: str = "hybrid") -> list[list[dict]]: | |
| rows = self._dense_scores(qs) if (self.dense is not None and mode != "bm25") else [None] * len(qs) | |
| return [self.search(q, k, mode, _dense_row=rows[i]) for i, q in enumerate(qs)] | |
| # ---- Jev rerank ------------------------------------------------------------------------------------- | |
| def unit_text(self, unit_id: str, prefer: list[str] | None = None) -> str: | |
| """Text shown to the reranker: the matched passages first, then the rest of the unit, capped.""" | |
| texts = list(prefer or []) | |
| for i in self.unit_ps[unit_id]: | |
| if self.ps[i]["text"] not in texts: | |
| texts.append(self.ps[i]["text"]) | |
| return "\n…\n".join(texts)[:JEV_TEXT_CHARS] | |
| async def rerank_jev(self, q: str, hits: list[dict], k: int = 5, client=None, sem=None) -> list[dict]: | |
| from typesafe_sdk import AsyncTypeSafeClient, Noul | |
| own = client is None | |
| if own: | |
| client = await AsyncTypeSafeClient(model=JEV_MODEL).__aenter__() | |
| sem = sem or asyncio.Semaphore(12) | |
| async def one(h): | |
| async with sem: | |
| r = await client.system_one( | |
| state={"pertanyaan": q, "sumber": h["title"], "teks_pasal": self.unit_text(h["unit_id"], h["passages"])}, | |
| questions={"relevan": Noul(instructions=JEV_Q)}) | |
| return r.answers["relevan"].noul | |
| try: | |
| probs = await asyncio.gather(*[one(h) for h in hits]) | |
| finally: | |
| if own: | |
| await client.__aexit__(None, None, None) | |
| for r, (h, p) in enumerate(zip(hits, probs)): | |
| h["jev"] = round(float(p), 4) | |
| h["ranks"]["first_stage"] = r + 1 | |
| # Jev probability decides; first-stage order breaks near-ties | |
| return sorted(hits, key=lambda h: (-round(h["jev"], 2), h["ranks"]["first_stage"]))[:k] | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("q") | |
| ap.add_argument("-k", type=int, default=5) | |
| ap.add_argument("--jev", action="store_true", help="rerank the top 20 with Jev") | |
| ap.add_argument("--dense", default="qwen3-embedding-0.6b") | |
| a = ap.parse_args() | |
| r = Retriever(dense=a.dense) | |
| hits = r.search(a.q, k=20 if a.jev else a.k) # val: hybrid top-20 + Jev beats the BM25∪dense pool | |
| if a.jev: | |
| hits = asyncio.run(r.rerank_jev(a.q, hits, k=a.k)) | |
| for n, h in enumerate(hits, 1): | |
| extra = f" jev={h['jev']:.2f}" if "jev" in h else "" | |
| print(f"{n}. {h['sumber']} ranks={h['ranks']}{extra}\n {h['passages'][0][:220].replace(chr(10), ' ')}…") | |
| if __name__ == "__main__": | |
| main() | |