Demo RAG: BM25 + Qwen3-Embedding -> Jev rerank -> Gemma 4 31B, dengan kode akses
Browse filesFiles changed (13)
- README.md+14-7
- app.pyAdded+130
- data/retrieval/bm25/data.csc.index.npyAdded+3
- data/retrieval/bm25/indices.csc.index.npyAdded+3
- data/retrieval/bm25/indptr.csc.index.npyAdded+3
- data/retrieval/bm25/params.index.jsonAdded+12
- data/retrieval/bm25/vocab.index.jsonAdded
- data/retrieval/bm25/vocab_custom.jsonAdded
- data/retrieval/emb_qwen3-embedding-0.6b.npyAdded+3
- data/retrieval/passages.jsonlAdded
- requirements.txtAdded+9
- scripts/rag_index.pyAdded+454
- scripts/rag_retriever.pyAdded+170
123452345678789101113121314151617181920---title: Aiccounting Demoemoji: 📚colorFrom: yellowcolorTo: redtitle: aiccounting demoemoji: 🧾colorFrom: bluecolorTo: graysdk: gradiosdk_version: 6.31.0python_version: '3.13'sdk_version: 6.20.0app_file: app.pypinned: false---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# aiccounting — demo RAG peraturan pajak Indonesia
Pertanyaan → BM25 + Qwen3-Embedding-0.6B → rerank **Jev** → 4 pasal teratas → **Gemma 4 31B** (Inference Providers)menjawab hanya dari kutipan itu. Indeks: 32 peraturan dari JDIH BPK (lihat `Erasys/aiccounting-laporan`).
Demo internal, bukan nasihat pajak.
Secrets: `HF_TOKEN` (fine-grained token, izin *Make calls to Inference Providers*), `TYPESAFE_API_KEY`, `DEMO_ACCESS_CODE`.Space ini publik; tanpa kode akses yang benar tidak ada model atau Jev yang dipanggil.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""aiccounting — demo RAG peraturan pajak & akuntansi Indonesia.
Pipeline (sama dengan eval di repo aiccounting): pertanyaan -> BM25 + Qwen3-Embedding-0.6B (lokal, CPU) top-20 -> rerank Jev (TypeSafe API) -> 4 pasal teratas -> Gemma 4 31B (HF Inference Providers) menjawab hanya dari kutipan itu.
Secrets yang dibutuhkan Space: HF_TOKEN (fine-grained, izin "Make calls to Inference Providers"),TYPESAFE_API_KEY (Jev), DEMO_ACCESS_CODE (kode akses; tanpa ini tidak ada pertanyaan yang diproses)."""from __future__ import annotations
import asyncioimport hmacimport osimport sysfrom pathlib import Path
import gradio as grfrom huggingface_hub import InferenceClient
sys.path.insert(0, str(Path(__file__).resolve().parent / "scripts"))from rag_retriever import Retriever # noqa: E402
MODEL = "google/gemma-4-31B-it"K = 4CAP = 4000LOW_RELEVANCE = 0.5# prompt v1 — the one kept after tuning on the dev set (see report notebook, section 8d)SYSTEM = ("Anda adalah asisten akuntansi dan perpajakan Indonesia. Jawab berdasarkan peraturan perundang-" "undangan yang berlaku, sebutkan dasar hukumnya (pasal dan peraturan), tunjukkan perhitungan " "langkah demi langkah bila ada angka, dan nyatakan kesimpulan dengan jelas. Anda menerima kutipan " "peraturan hasil penelusuran; sebagian mungkin tidak relevan. Jawab hanya berdasarkan kutipan yang " "relevan dan sebutkan pasal yang Anda gunakan. Jika kutipan tidak memuat dasar untuk menjawab, " "katakan demikian.")
RET = Retriever(dense="qwen3-embedding-0.6b")LLM = InferenceClient(provider="auto", api_key=os.environ.get("HF_TOKEN"))
def ctx_text(h: dict) -> str: texts = list(h["passages"]) for i in RET.unit_ps[h["unit_id"]]: if RET.ps[i]["text"] not in texts: texts.append(RET.ps[i]["text"]) s = "\n…\n".join(texts) return s if len(s) <= CAP else s[:CAP] + " …"
def retrieve(q: str) -> list[dict]: hits = RET.search(q, 20, "hybrid") return asyncio.run(RET.rerank_jev(q, hits, k=K))
def excerpts_md(top: list[dict]) -> str: out = [] for i, h in enumerate(top, 1): body = ctx_text(h).replace("\n", " \n") out.append(f"**[{i}] {h['sumber']}** · relevansi Jev {h['jev']:.2f}\n\n{body}") return "\n\n---\n\n".join(out)
ACCESS_CODE = os.environ.get("DEMO_ACCESS_CODE", "")
def answer(q: str, code: str): # the Space is public: nothing that costs money runs without the access code if not ACCESS_CODE: yield "Demo belum dikonfigurasi (secret DEMO_ACCESS_CODE belum diisi).", "" return if not hmac.compare_digest((code or "").strip(), ACCESS_CODE): yield "Kode akses salah.", "" return q = (q or "").strip() if not q: yield "Tulis pertanyaan dulu.", "" return yield "_Mencari pasal yang relevan…_", "" try: top = retrieve(q) except Exception as e: # noqa: BLE001 yield f"Gagal menelusuri peraturan: `{type(e).__name__}`. Cek secret TYPESAFE_API_KEY.", "" return ex = excerpts_md(top) warn = "" if not top or top[0]["jev"] < LOW_RELEVANCE: warn = ("> ⚠️ Tidak ada pasal yang dinilai benar-benar relevan. Jawaban di bawah kemungkinan tidak berdasar — " "coba tulis ulang pertanyaan dengan istilah peraturan (mis. \"PPh Pasal 26\", \"Wajib Pajak luar " "negeri\").\n\n") ctx = "\n\n".join(f"[{i}] {h['title']}\n{ctx_text(h)}" for i, h in enumerate(top, 1)) msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": f"Kutipan peraturan:\n\n{ctx}\n\nPertanyaan: {q}"}] text = warn yield text + "_Menyusun jawaban…_", ex try: for chunk in LLM.chat_completion(model=MODEL, messages=msgs, max_tokens=2048, temperature=0, stream=True): delta = chunk.choices[0].delta.content if chunk.choices else None if delta: text += delta yield text, ex except Exception as e: # noqa: BLE001 yield text + f"\n\nGagal memanggil model: `{type(e).__name__}`. Cek secret HF_TOKEN.", ex return yield text, ex
EXAMPLES = [ "Berapa tarif PPh Pasal 26 atas imbalan jasa kepada Wajib Pajak luar negeri?", "Omzet usaha saya 3 miliar setahun. Apakah saya boleh memakai PPh final 0,5%?", "Batas akhir pelaporan SPT Masa jatuh pada hari Sabtu. Boleh lapor hari Senin?", "Mesin pabrik terbakar dan dapat penggantian asuransi tahun depan. Kapan kerugiannya dibebankan?",]
with gr.Blocks(title="aiccounting · demo RAG") as demo: gr.Markdown( "## aiccounting — tanya peraturan pajak Indonesia\n" "Jawaban disusun **hanya dari pasal hasil penelusuran** atas 32 peraturan (UU KUP, PPh, PPN, HPP, PP 55/2022, " "PMK 81/2024, dll.). Lihat kutipannya di bawah jawaban. **Demo internal, bukan nasihat pajak.** " "PSAK/SAK belum termasuk.") code = gr.Textbox(label="Kode akses", type="password", max_lines=1) q = gr.Textbox(label="Pertanyaan", lines=3, placeholder="mis. PT kami membayar jasa konsultan luar negeri…") btn = gr.Button("Tanya", variant="primary") gr.Examples(EXAMPLES, inputs=q) ans = gr.Markdown(label="Jawaban") with gr.Accordion("Kutipan peraturan yang dipakai", open=False): exs = gr.Markdown() btn.click(answer, inputs=[q, code], outputs=[ans, exs]) q.submit(answer, inputs=[q, code], outputs=[ans, exs])
if __name__ == "__main__": demo.queue(default_concurrency_limit=4).launch()123version https://git-lfs.github.com/spec/v1oid sha256:18bf39f20bac10e7c01219d3af28aa65def4a96e7b73226223b670877edd699csize 1904628123version https://git-lfs.github.com/spec/v1oid sha256:afcf241a564160832c1d7d115eb291362e16787ccae45c2360f7c070430f94c9size 1904628123version https://git-lfs.github.com/spec/v1oid sha256:7419405912fc1cc80f1ed27f335a173a3621b7d449cdd0c9f2de062d4e7ef83dsize 109168123456789101112{ "k1": 1.5, "b": 0.75, "delta": 0.5, "method": "lucene", "idf_method": "lucene", "dtype": "float32", "int_dtype": "int32", "num_docs": 7677, "version": "0.3.16", "backend": "numpy"}123version https://git-lfs.github.com/spec/v1oid sha256:9bca5980d8493a8916f728822047b9e555dff3950f9ddfe124c672b26f95b162size 15722624123456789--extra-index-url https://download.pytorch.org/whl/cputorch==2.15.0sentence-transformers==6.2.0transformers==5.22.1bm25s==0.3.16PyStemmer==3.1.0numpy==2.5.4huggingface_hub==2.4.0typesafe-sdk==0.7.5123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454#!/usr/bin/env python3"""Build the retrieval index over current Indonesian regulations.
Unit = one pasal in its latest version (batang tubuh + its penjelasan), or a loose chunk (lampiran, penjelasan umum, pasal whose heading was lost to OCR). unit_id uses the same scheme as data/latih/units.jsonl, so the eval set's meta.unit_id is the ground truth.Passage = a window of ~1,200 chars of a unit, prefixed with its title. Search scores passages; results are returned per unit (max over its passages).
Only current law is indexed: not trivial, not deleted, latest version, regulation not repealed. Non-tax pasal(e.g. sectoral chapters of UU Cipta Kerja) are kept on purpose: they are realistic distractors.
Outputs (data/retrieval/): passages.jsonl, bm25/ (bm25s index), emb_<model>.npyUsage: .venv/bin/python scripts/rag_index.py # passages + BM25 + all embedding models .venv/bin/python scripts/rag_index.py --only bm25No API calls; embeddings run locally (MPS/CPU)."""from __future__ import annotations
import argparseimport jsonimport refrom collections import defaultdictfrom pathlib import Path
ROOT = Path(__file__).resolve().parent.parentCORPUS = ROOT / "data" / "regulasi" / "corpus.jsonl"MANIFEST = ROOT / "data" / "regulasi" / "manifest.json"OUT = ROOT / "data" / "retrieval"WIN, OVERLAP = 1200, 200
# embedding models: name -> how to encode documents and queriesEMBEDDERS = { "embeddinggemma-2": { "repo": "google/embeddinggemma-2", "config_kwargs": {"vision_config": None, "audio_config": None}, # text-only: 270M of 740M params "doc": lambda title, text: f"title: {title} | text: {text}", "query": lambda q: f"task: question answering | query: {q}", }, "qwen3-embedding-0.6b": { "repo": "Qwen/Qwen3-Embedding-0.6B", "config_kwargs": {}, "doc": lambda title, text: f"{title}\n{text}", "query": lambda q: ("Instruct: Given a question about Indonesian tax, accounting or company law, " f"retrieve the regulation article that answers it\nQuery:{q}"), },}
STOP = set("""yang dan di ke dari dalam untuk dengan atau pada ini itu adalah sebagai oleh tersebut akan dapat bagijuga serta apakah bagaimana berapa kami saya kita ada sudah telah harus jika bila apabila maka karena kepadapara suatu sebuah se tiap setiap hal tentang atas antara lain apa siapa kapan mana mengapa kenapa perlu bisaboleh mohon tolong jelaskan sebutkan the""".split())
def current(c: dict) -> bool: return (not c["trivial"] and not c["dihapus"] and c["versi_terbaru"] is not False and c.get("target_status") != "Dicabut" and c["section"] != "pembukaan" and c["kind"] not in ("instruksi_perubahan", "pembungkus_perubahan"))
def build_units() -> list[dict]: """Same grouping as prepare_units.py, but over all current law (not only app-relevant chunks).""" titles = {m["slug"]: m.get("judul") for m in json.load(open(MANIFEST))} if MANIFEST.exists() else {} cs = [json.loads(l) for l in open(CORPUS)] body: dict[tuple, list[dict]] = defaultdict(list) penj: dict[tuple, list[dict]] = defaultdict(list) loose = [] for c in cs: if c["kind"] in ("pasal", "pasal_perubahan") and c["target_pasal"]: key = (c["target_slug"], c["target_pasal"]) if c["section"] == "batang_tubuh": body[key].append(c) elif c["section"] == "penjelasan_pasal": penj[key].append(c) elif current(c): loose.append(c)
units = [] for key, parts in body.items(): parts = [p for p in parts if p["versi_terbaru"]] if not parts or not any(current(p) for p in parts): continue src = parts[-1]["reg_slug"] parts = sorted([p for p in parts if p["reg_slug"] == src], key=lambda p: (p["page_start"], p["part"])) pj = [p for p in penj.get(key, []) if p["versi_terbaru"] and not p["trivial"]] units.append({ "unit_id": f"{key[0]}|{key[1]}", "sumber": parts[0]["header"].split(" [bagian")[0], "judul": titles.get(key[0]) or parts[0]["reg_judul"], "dari_dokumen": src, "target_slug": key[0], "pasal": key[1], "section": "batang_tubuh", "relevan": any(p.get("relevan_aplikasi") for p in parts), "topik": sorted({t for p in parts for t in p["topik"]}), "teks": "\n".join(p["text"] for p in parts), "penjelasan": "\n".join(p["text"] for p in pj) or None, }) for c in loose: units.append({ "unit_id": c["id"], "sumber": c["header"], "judul": titles.get(c["target_slug"]) or c["reg_judul"], "dari_dokumen": c["reg_slug"], "target_slug": c["target_slug"], "pasal": c.get("target_pasal"), "section": c["section"], "relevan": bool(c.get("relevan_aplikasi")), "topik": c["topik"], "teks": c["text"], "penjelasan": None, }) return units
# --- splitting units that swallowed later pasal (heading missed by the chunker because of OCR) -----------------# "Pasal112", "PasaIl06", "Pasa1268", "Pasal T2", "Pasal 17E}" ... on a line of their ownLOOSE_H = re.compile(r"^[\"“”'(]{0,2}P\s?[aA4]\s?[sS5]\s?[aA4]\s?[lI1iLt]{1,2}\s*([0-9OoIlLiTSZ!][0-9OoIlLiTSZ! ]{0,4}" r"(?:\s?[A-I])?)[\s.}\]\"”'!]{0,4}$")# the chunker sometimes glued a heading to the next line: "Pasa1463 Wajib Pajak …" (number glued to "Pasal")GLUED_H = re.compile(r"^P[aA4][sS5][aA4][lI1]{1,2}(\d[\dOoIl]{0,3}[A-I]?)\s+([A-Z(\"“].*)$")OCR_DIGIT = str.maketrans({"O": "0", "o": "0", "I": "1", "l": "1", "L": "1", "i": "1", "!": "1", "T": "7", "S": "5", "Z": "2"})INSTR_REF = re.compile(r"(?:Ketentuan\s+Pasal|disisipkan\s+\d*\s*\(?\w*\)?\s*pasal,?\s*yakni\s+Pasal|Pasal)\s+(\d{1,4}[A-Z]?)" r"\b[^.\n]{0,60}(?:diubah|disisipkan|berbunyi)", re.I)SPLIT_SECTIONS = ("batang_tubuh",)
def _parse_no(tok: str) -> tuple[int, str] | None: """OCR'd pasal number -> (number, letter suffix). Trailing A–I is a suffix; anything else must map to digits.""" tok = tok.replace(" ", "") m = re.fullmatch(r"(.+?)([A-I]?)", tok) digits = m.group(1).translate(OCR_DIGIT) if not digits.isdigit() or len(digits) > 3: return None return int(digits), m.group(2)
def _key(no: str | None) -> tuple[int, str] | None: m = re.fullmatch(r"(\d{1,4})([A-Z]{0,2})", no or "") return (int(m.group(1)), m.group(2)) if m else None
def split_missed_headings(text: str, start: tuple[int, str] | None) -> list[tuple[str | None, str]]: """Split `text` at heading lines the chunker missed. Returns [(pasal_no or None for the head, segment)].
A line becomes a heading only if (1) it looks like an OCR'd "Pasal N" on its own line, (2) the previous non-empty line ends a sentence/instruction (. : ) etc.) — so "…dimaksud dalam\\nPasal 25;" stays text — and (3) N follows the previous pasal: same number with a later suffix, or a number up to 15 higher. An amendment instruction just before it ("Ketentuan Pasal 17B diubah …") overrides the OCR'd number when the digits agree.""" lines = text.split("\n") segs: list[tuple[str | None, list[str]]] = [(None, [])] prev, last_txt = start, "" for i, ln in enumerate(lines): s = ln.strip() m = LOOSE_H.match(s) if s else None rest = None if not m and s: m = GLUED_H.match(s) rest = m.group(2) if m else None if m and (rest is not None or not last_txt or last_txt[-1] in ".:)\"”;" or last_txt.endswith("berikut")): cand = _parse_no(m.group(1)) ctx = "\n".join(lines[max(0, i - 6):i]) ref = [_key(r) for r in INSTR_REF.findall(ctx)] ref = [r for r in ref if r and cand and r[0] == cand[0]] if ref: cand = ref[-1] elif cand and cand[1] == "E" and re.search(r"E\s*\}", s): cand = (cand[0], "B") # "Pasal 17E}" is OCR for "Pasal 17B" ok = cand and (prev is None or (cand[0] == prev[0] and cand[1] > prev[1]) or prev[0] < cand[0] <= prev[0] + 15) if ok: segs.append((f"{cand[0]}{cand[1]}", [rest] if rest else [])) prev, last_txt = cand, (rest or "").strip() continue segs[-1][1].append(ln) if s: last_txt = s return [(no, "\n".join(ls).strip()) for no, ls in segs if "\n".join(ls).strip() or no is None]
# lampiran text glued onto the closing pasal ("Peraturan Menteri ini mulai berlaku …" + Lampiran A–G forms)LAMP_START = re.compile(r"^(LAMPIRAN\b|CONTOH FORMAT DOKUMEN|[A-Z]{1,4}\.\s?CONTOH\s?FORMAT)")LAMP_LETTER = re.compile(r"^([A-Z]{1,4})\.\s?CONTOH\s?FORMAT")
def split_lampiran(u: dict) -> list[dict]: """Cut lampiran text off a batang-tubuh unit into units labelled '<reg> Lampiran Huruf X'.""" lines = u["teks"].split("\n") start = next((i for i, ln in enumerate(lines) if LAMP_START.match(ln.strip())), None) if start is None or start == 0: return [u] reg = re.split(r"\s+(?:Pasal|Teks)\b", u["sumber"])[0] pieces, cur, letter = [], [], None for ln in lines[start:]: m = LAMP_LETTER.match(ln.strip()) if m and m.group(1) != letter: if cur: pieces.append((letter, cur)) cur, letter = [], m.group(1) cur.append(ln) pieces.append((letter, cur)) out = [{**u, "teks": "\n".join(lines[:start]).strip()}] for letter, ls in pieces: txt = "\n".join(ls).strip() if len(txt) < 40: continue tag = f"Huruf {letter}" if letter else "(pembuka)" out.append({**u, "unit_id": f"{u['unit_id']}@lamp{letter or '0'}", "sumber": f"{reg} Lampiran {tag}", "pasal": None, "section": "lampiran", "teks": txt, "penjelasan": None}) return out
def _year(slug: str) -> int: m = re.search(r"tahun-(\d{4})", slug) return int(m.group(1)) if m else 0
def split_units(units: list[dict]) -> tuple[list[dict], dict]: """Split units whose text contains missed pasal headings into sub-units `<unit_id>@<pasal>` with a correct label. A sub-unit from a newer amending document supersedes an older body unit of the same (target, pasal). Returns (units, alias) where alias maps every new/superseding id to the unit_id the eval set may use as gold.""" out, alias, n_split = [], {}, 0 existing = {(u["target_slug"], u["pasal"]): u for u in units if u.get("pasal")} superseded = set() for u in units: if u["section"] not in SPLIT_SECTIONS: out.append(u); continue parts = split_missed_headings(u["teks"], _key(u.get("pasal"))) if len(parts) == 1: out.append(u); continue n_split += 1 pj = split_missed_headings(u["penjelasan"], _key(u.get("pasal"))) if u.get("penjelasan") else [(None, None)] pj_by = {no: t for no, t in pj} # a split whose number is already indexed on its own from an equal/newer document is not trusted as a # heading: its text goes back into the previous piece (never dropped) pieces: list[list] = [[None, parts[0][1]]] for no, txt in parts[1:]: old = existing.get((u["target_slug"], no)) if old is not None and old["unit_id"] != u["unit_id"] and _year(u["dari_dokumen"]) <= _year(old["dari_dokumen"]): pieces[-1][1] = f"{pieces[-1][1]}\nPasal {no}\n{txt}".strip() else: pieces.append([no, txt]) if len(pieces) == 1: out.append(u); continue if pieces[0][1]: out.append({**u, "teks": pieces[0][1], "penjelasan": pj_by.get(None)}) base = re.sub(r"\s*\[bagian [^\]]*\]", "", u["sumber"]) for no, txt in pieces[1:]: label = re.sub(r"\bPasal \S+|\bTeks\b", f"Pasal {no}", base, count=1) sub = {**u, "unit_id": f"{u['unit_id']}@{no}", "sumber": label, "pasal": no, "teks": txt, "penjelasan": pj_by.get(no)} old = existing.get((u["target_slug"], no)) if old is not None and old["unit_id"] != u["unit_id"]: superseded.add(old["unit_id"]); alias[sub["unit_id"]] = old["unit_id"] alias.setdefault(sub["unit_id"], u["unit_id"]) out.append(sub) out = [u for u in out if u["unit_id"] not in superseded] final = [] for u in out: parts = split_lampiran(u) if u["section"] in SPLIT_SECTIONS else [u] for x in parts[1:]: alias[x["unit_id"]] = alias.get(u["unit_id"], u["unit_id"].split("@")[0]) final.extend(parts) print(f"lampiran split off: {len(final) - len(out)} units") out = final print(f"split {n_split} units -> {sum('@' in u['unit_id'] for u in out)} sub-units; " f"superseded {len(superseded)}: {sorted(superseded)[:12]}") return out, alias
# --- recovering amended pasal the chunker dropped ---------------------------------------------------------------# chunk_pasal attaches text that follows an amendment instruction ("5 Ketentuan Pasal 17B diubah sehingga berbunyi# sebagai berikut:") to that instruction block until the next recognised heading. When the new pasal's own heading# is OCR-garbled ("Pasal 17E}"), its whole body lands in the instruction block, which is never emitted. Re-running# the chunker would renumber every chunk id, so the text is recovered here from the raw text instead.TEXT_DIR = ROOT / "data" / "regulasi" / "text"ONE_PASAL = re.compile(r"Ketentuan\s+Pasal\s+(\d{1,4}[A-Z]?)\s+diubah|yakni\s+Pasal\s+(\d{1,4}[A-Z]?)\b", re.I)
def recover_dropped_amendments(units: list[dict]) -> tuple[list[dict], dict]: import chunk_pasal as C cs = [json.loads(l) for l in open(CORPUS)] have = {(c["reg_slug"], c["target_slug"], c["target_pasal"]) for c in cs if c["kind"] == "pasal_perubahan" and c["section"] == "batang_tubuh"} penj = {(c["reg_slug"], c["target_slug"], c["target_pasal"]): c["text"] for c in cs if c["kind"] == "pasal_perubahan" and c["section"] == "penjelasan_pasal" and not c["trivial"]} titles = {m["slug"]: m.get("judul") for m in json.load(open(MANIFEST))} if MANIFEST.exists() else {} by_key = {(u["target_slug"], u["pasal"]): u for u in units if u.get("pasal") and "@" not in u["unit_id"]} amending = sorted({c["reg_slug"] for c in cs if c["kind"] == "pasal_perubahan"}) new, alias, superseded = [], {}, set() for reg in amending: tf = TEXT_DIR / f"{reg}.txt" if not tf.exists(): continue lines = C.load_lines(tf) ctx = sorted([c for c in cs if c["reg_slug"] == reg and c["kind"] in ("pasal_perubahan", "instruksi_perubahan", "pembungkus_perubahan", "pasal") and c["page_start"]], key=lambda c: c["page_start"]) k = 0 while k < len(lines): p, s = lines[k] if not C.INSTR.match(s): k += 1; continue blk, j = [s], k + 1 while j < len(lines) and len(blk) < 8 and not re.search(r"(:|\.)$", blk[-1] or "x"): if lines[j][1]: blk.append(lines[j][1]) j += 1 text = " ".join(blk) m = ONE_PASAL.search(text) if not (m and re.search(r"berikut\s*:?$", text)): k = j; continue no = C.fix_pasal_id(m.group(1) or m.group(2)) known_tp = {tp for (r, _t, tp) in have if r == reg} # body: skip the new pasal's heading line, stop at the next heading or instruction body, h_seen = [], False while j < len(lines): q = lines[j][1] is_head = bool(q) and (C.H_PASAL.match(q) or LOOSE_H.match(q)) if q and (C.INSTR.match(q) or C.H_BAB.match(q) or C.H_PENJ.match(q)): break if is_head: # leftover page-header junk ("REPUBL|K INDONESIA") before the heading doesn't count as body if h_seen or sum(len(x) for x in body) > 60: break h_seen = True else: body.append(q) j += 1 # target law = that of the nearest preceding amendment chunk, only if no wrapper/ordinary pasal (which # may switch the amended law) sits in between and it is close; otherwise the target is unknown -> skip before = [c for c in ctx if c["page_start"] <= p] last = before[-1] if before else None tgt = (last["target_slug"] if last and last["kind"] in ("pasal_perubahan", "instruksi_perubahan") and p - (last.get("page_end") or last["page_start"]) <= 3 else None) txt = C.reflow([x for x in body if not re.fullmatch(r"[A-Z|\s]{4,30}", x or "")]).strip() no = C.match_known(no, known_tp | {u_no for (t, u_no) in by_key if t == tgt}) # "278" -> "27B" if tgt and tgt != reg and (reg, tgt, no) not in have and len(txt) > 80: old = by_key.get((tgt, no)) if old is None or _year(old["dari_dokumen"]) < _year(reg): uid = f"{tgt}|{no}@{reg}" new.append({"unit_id": uid, "sumber": f"{C.short_name(tgt)} Pasal {no} (sebagaimana diubah oleh " f"{C.short_name(reg)})", "judul": titles.get(tgt) or (old or {}).get("judul") or tgt, "dari_dokumen": reg, "target_slug": tgt, "pasal": no, "section": "batang_tubuh", "relevan": bool(old and old["relevan"]), "topik": (old or {}).get("topik", []), "teks": txt, "penjelasan": penj.get((reg, tgt, no))}) if old is not None: superseded.add(old["unit_id"]); alias[uid] = old["unit_id"] k = j out = [u for u in units if u["unit_id"] not in superseded] + new print(f"recovered {len(new)} dropped amended pasal; superseded {len(superseded)} older versions, e.g. " f"{[u['sumber'] for u in new if u['target_slug'] == 'uu-no-6-tahun-1983'][:6]}") return out, alias
def windows(text: str) -> list[str]: """Split on line boundaries into ~WIN-char windows with ~OVERLAP chars carried over.""" lines, out, cur = text.split("\n"), [], "" for ln in lines: while len(ln) > WIN: # very long line (flattened table): hard split out.append((cur + "\n" + ln[:WIN]).strip()); cur, ln = ln[WIN - OVERLAP:WIN], ln[WIN:] if len(cur) + len(ln) + 1 > WIN and cur: out.append(cur.strip()); cur = cur[-OVERLAP:] cur += "\n" + ln if cur.strip() and (not out or cur.strip() not in out[-1]): out.append(cur.strip()) return out
def build_passages(units: list[dict]) -> list[dict]: ps = [] for u in units: title = f"{u['sumber']} — {u['judul']}" segs = windows(u["teks"]) + [f"Penjelasan: {w}" for w in windows(u["penjelasan"])] if u["penjelasan"] \ else windows(u["teks"]) for i, s in enumerate(segs): ps.append({"pid": f"{u['unit_id']}#p{i}", "unit_id": u["unit_id"], "title": title, "text": s, "relevan": u["relevan"]}) return ps
def tokenize(s: str, stemmer=None) -> list[str]: """Lowercase; join digit groups (Rp4.800.000 -> 4800000); split glued OCR tokens (Pasal17B -> pasal 17b).""" s = re.sub(r"(?<=\d)[.,](?=\d{3})", "", s.lower()) toks = [t for t in re.findall(r"[a-z]+|\d+[a-z]?", s) if t not in STOP] return stemmer.stemWords(toks) if stemmer else toks
def build_bm25(ps: list[dict]) -> None: import bm25s import Stemmer st = Stemmer.Stemmer("indonesian") corpus = [tokenize(p["title"] + "\n" + p["text"], st) for p in ps] vocab: dict[str, int] = {} ids = [[vocab.setdefault(t, len(vocab)) for t in doc] for doc in corpus] r = bm25s.BM25() r.index(bm25s.tokenization.Tokenized(ids=ids, vocab=vocab), show_progress=False) r.save(OUT / "bm25") json.dump(vocab, open(OUT / "bm25" / "vocab_custom.json", "w")) print(f"bm25: {len(ps)} passages, {len(vocab)} terms")
def build_embeddings(ps: list[dict], name: str, reuse: dict | None = None) -> None: import numpy as np import torch from sentence_transformers import SentenceTransformer cfg = EMBEDDERS[name] dev = "mps" if torch.backends.mps.is_available() else "cpu" m = SentenceTransformer(cfg["repo"], device=dev, config_kwargs=cfg["config_kwargs"] or None, model_kwargs={"torch_dtype": torch.float32}) # embeddinggemma: no float16 docs = [cfg["doc"](p["title"], p["text"]) for p in ps] reuse = reuse or {} todo = [i for i in range(len(docs)) if (ps[i]["title"], ps[i]["text"]) not in reuse] print(f"{name}: reusing {len(docs) - len(todo)} embeddings, encoding {len(todo)}") order = sorted(todo, key=lambda i: len(docs[i])) # length-sorted batches: less padding e = m.encode([docs[i] for i in order], batch_size=16, normalize_embeddings=True, show_progress_bar=True, convert_to_numpy=True) if order else None dim = e.shape[1] if e is not None else len(next(iter(reuse.values()))) out = np.zeros((len(docs), dim), dtype=np.float32) todo_set = set(todo) for i in range(len(docs)): if i not in todo_set: out[i] = reuse[(ps[i]["title"], ps[i]["text"])] if e is not None: out[order] = e np.save(OUT / f"emb_{name}.npy", out.astype(np.float16)) print(f"{name}: {out.shape}")
def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--only", nargs="+", choices=["passages", "bm25", *EMBEDDERS], help="build only these (passages are always rewritten)") a = ap.parse_args() OUT.mkdir(parents=True, exist_ok=True) # embeddings of passages whose title+text is unchanged are reused from the previous build reuse = {} old_ps = OUT / "passages.jsonl" if old_ps.exists(): import numpy as np olds = [json.loads(l) for l in open(old_ps)] for name in EMBEDDERS: f = OUT / f"emb_{name}.npy" if f.exists(): arr = np.load(f) if len(arr) == len(olds): reuse[name] = {(p["title"], p["text"]): arr[i] for i, p in enumerate(olds)} units, alias = split_units(build_units()) units, alias2 = recover_dropped_amendments(units) alias.update(alias2) json.dump(alias, open(OUT / "unit_alias.json", "w"), ensure_ascii=False, indent=0) ps = build_passages(units) with open(OUT / "passages.jsonl", "w") as f: for p in ps: f.write(json.dumps(p, ensure_ascii=False) + "\n") print(f"{len(units)} units ({sum(u['relevan'] for u in units)} app-relevant) -> {len(ps)} passages") if a.only is None or "bm25" in a.only: build_bm25(ps) for name in EMBEDDERS: if a.only is None or name in a.only: build_embeddings(ps, name, reuse.get(name))
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170#!/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 argparseimport asyncioimport jsonimport sysfrom collections import defaultdictfrom 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 = 60JEV_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()README.md+14-7
app.pyAdded+130
data/retrieval/bm25/data.csc.index.npyAdded+3
data/retrieval/bm25/indices.csc.index.npyAdded+3
data/retrieval/bm25/indptr.csc.index.npyAdded+3
data/retrieval/bm25/params.index.jsonAdded+12
data/retrieval/bm25/vocab.index.jsonAdded
data/retrieval/bm25/vocab_custom.jsonAdded
data/retrieval/emb_qwen3-embedding-0.6b.npyAdded+3
data/retrieval/passages.jsonlAdded
requirements.txtAdded+9
scripts/rag_index.pyAdded+454
scripts/rag_retriever.pyAdded+170