tablinum-2 / code /statpearls_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
2.43 kB
"""statpearls_chunk.py NXML_DIR OUT.parquet - StatPearls (NCBI Bookshelf NBK430685 tarball, ~9.3k articles) -> engram passages
(10-20, health table). One passage per ~WORDS words of a section, prefixed "Article — Section: " like chunk.py; bold-only
paragraphs become sub-headings. Same schema as chunk.py; file_idx from OUT's name AAA_BB. Not redistributable: local use only."""
import sys, re, os, glob
import xml.etree.ElementTree as ET
import pyarrow as pa, pyarrow.parquet as pq
WORDS, MIN_WORDS = 140, 12
src, dst = sys.argv[1], sys.argv[2]
a, b = re.search(r"(\d+)_(\d+)\.parquet$", dst).groups(); fidx = int(b) + 100 * int(a)
txt = lambda e: re.sub(r"\s+", " ", "".join(e.itertext())).strip()
cols = {"pid": [], "page_id": [], "title": [], "section": [], "text": []}; n = arts = 0
def emit(title, sec, words, nbk):
global n
for i in range(0, len(words), WORDS):
part = words[i:i + WORDS + 20] if len(words) - i <= WORDS + 20 else words[i:i + WORDS]
if len(part) >= MIN_WORDS:
cols["pid"].append((fidx << 32) | n); cols["page_id"].append(nbk); cols["title"].append(title); cols["section"].append(sec)
cols["text"].append(f"{title} — {sec}: " + " ".join(part)); n += 1
if len(words) - i <= WORDS + 20:
break
for f in sorted(glob.glob(f"{src}/**/*.nxml", recursive=True)):
try:
root = ET.parse(f).getroot()
except ET.ParseError:
continue
t = root.find(".//title"); title = txt(t) if t is not None else os.path.basename(f)[:-5]
nbk = int((re.search(r"NBK(\d+)", f) or re.search(r"(\d+)", "0")).group(1)); arts += 1
for sec in root.iter("sec"):
st = sec.find("title"); sname = txt(st) if st is not None else ""
if sname.lower() in ("references", "review questions", "continuing education activity"):
continue
buf, sub = [], sname
for ch in sec:
if ch.tag == "p" and len(ch) == 1 and ch[0].tag == "bold" and not (ch[0].tail or "").strip() and not (ch.text or "").strip():
emit(title, sub, buf, nbk); buf = []; sub = f"{sname} — {txt(ch)}"
elif ch.tag in ("p", "list", "table-wrap"):
buf += txt(ch).split()
emit(title, sub, buf, nbk)
pq.write_table(pa.table(cols), dst + ".tmp", compression="zstd", row_group_size=4096); os.replace(dst + ".tmp", dst)
print(src, "articles", arts, "passages", n, flush=True)