File size: 2,429 Bytes
901f964
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""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)