tablinum-2 / code /medrag_chunk.py
chadstthomas's picture
Tablinum-2: the Lite-Beam engram, release 2 (card, code, recipes, 9 released tables)
901f964 verified
Raw History Blame Contribute Delete
1.67 kB
"""medrag_chunk.py IN.jsonl OUT.parquet [SOURCE] - MedRAG corpus snippets (textbooks / pubmed, {id, title, content}) -> engram
passages, same schema as chunk.py (pid = file_idx << 32 | n, page_id, title, section, text) (10-20, health table). Text is
"Title: content", split into WORDS-word windows when longer, so the re-ranker's 256-token window sees the whole passage.
file_idx comes from OUT's name AAA_BB (BB + 100*AAA), as engram.Passages expects. Textbook titles are file names
(Anatomy_Gray) -> "Anatomy Gray"."""
import sys, re, json, os
import pyarrow as pa, pyarrow.parquet as pq
WORDS = 180
src, dst = sys.argv[1], sys.argv[2]; source = sys.argv[3] if len(sys.argv) > 3 else os.path.basename(src)[:-6]
a, b = re.search(r"(\d+)_(\d+)\.parquet$", dst).groups(); fidx = int(b) + 100 * int(a)
cols = {"pid": [], "page_id": [], "title": [], "section": [], "text": []}; n = 0
for line in open(src):
r = json.loads(line); title = r["title"].strip()
if source == "textbooks":
title = title.replace("_", " ")
w = r["content"].split()
for i in range(0, max(len(w), 1), WORDS):
part = w[i:i + WORDS + 30] if len(w) - i <= WORDS + 30 else w[i:i + WORDS]
if len(part) < 8:
break
cols["pid"].append((fidx << 32) | n); cols["page_id"].append(int(r.get("PMID") or 0)); cols["title"].append(title)
cols["section"].append(source); cols["text"].append(f"{title}: " + " ".join(part)); n += 1
if len(w) - i <= WORDS + 30:
break
pq.write_table(pa.table(cols), dst + ".tmp", compression="zstd", row_group_size=4096); os.replace(dst + ".tmp", dst)
print(src, "->", dst, "passages", n, flush=True)