Download scripts/rag_index.py from codingforfun/aiccounting-demo: direct link, hf CLI and curl.
- Browser
- Download file 23.4 kB
-
https://huggingface.co/spaces/codingforfun/aiccounting-demo/resolve/main/scripts/rag_index.py
- Command line
-
hf download hf://spaces/codingforfun/aiccounting-demo/scripts/rag_index.py
-
curl -L -o rag_index.py https://huggingface.co/spaces/codingforfun/aiccounting-demo/resolve/main/scripts/rag_index.py
23.4 kB
| #!/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>.npy | |
| Usage: | |
| .venv/bin/python scripts/rag_index.py # passages + BM25 + all embedding models | |
| .venv/bin/python scripts/rag_index.py --only bm25 | |
| No API calls; embeddings run locally (MPS/CPU). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import re | |
| from collections import defaultdict | |
| from pathlib import Path | |
| ROOT = Path(__file__).resolve().parent.parent | |
| CORPUS = 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 queries | |
| EMBEDDERS = { | |
| "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 bagi | |
| juga serta apakah bagaimana berapa kami saya kita ada sudah telah harus jika bila apabila maka karena kepada | |
| para suatu sebuah se tiap setiap hal tentang atas antara lain apa siapa kapan mana mengapa kenapa perlu bisa | |
| boleh 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 own | |
| LOOSE_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() | |