beam-engram-tables / code /devdocs_chunk.py
chadstthomas's picture
Engram code
3bc7886 verified
Raw History Blame Contribute Delete
3.76 kB
"""devdocs_chunk.py DOCS.json RAW_DIR OUT_DIR - DevDocs (documents.devdocs.io/<slug>/db.json, one per doc and version) ->
engram passages for the software table (10-20, PLAN-verticals B3). Each page is split at h1-h4 headings; each section becomes
~WORDS-word passages prefixed "Doc Version — page — heading: " so version-specific questions find the right release.
Code blocks are kept (signatures are the facts) but capped at CODE words. Doc i of the sorted slug list -> OUT_DIR/AAA_BB.parquet
(i // 100, i % 100), same schema as chunk.py; page_id = the page's index in db.json. Skips docs whose parquet exists."""
import sys, os, re, json, html
from html.parser import HTMLParser
import pyarrow as pa, pyarrow.parquet as pq
WORDS, MIN_WORDS, CODE = 140, 10, 120
BLOCK = {"p", "li", "pre", "dd", "dt", "td", "th", "blockquote", "div", "tr", "table", "ul", "ol", "dl", "section", "details", "summary", "figcaption"}
class Page(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True); self.secs = [["", []]]; self.cur = []; self.h = None; self.skip = 0; self.pre = 0
def flush(self):
t = re.sub(r"\s+", " ", "".join(self.cur)).strip(); self.cur = []
if t:
w = t.split(); self.secs[-1][1] += w[:CODE] if self.pre else w
def handle_starttag(self, tag, attrs):
a = dict(attrs)
if self.skip or "_attribution" in (a.get("class") or "") or tag in ("script", "style"):
self.skip += tag in ("div", "script", "style", "p") or 0; return
if tag in ("h1", "h2", "h3", "h4"):
self.flush(); self.h = []
elif tag in BLOCK:
self.flush(); self.pre += tag == "pre"
def handle_endtag(self, tag):
if self.skip:
self.skip -= tag in ("div", "script", "style", "p"); return
if tag in ("h1", "h2", "h3", "h4") and self.h is not None:
self.secs.append([re.sub(r"\s+", " ", "".join(self.h)).strip(), []]); self.h = None
elif tag in BLOCK:
self.flush(); self.pre -= tag == "pre" and self.pre > 0
def handle_data(self, d):
if not self.skip:
(self.h if self.h is not None else self.cur).append(d)
docs = sorted(json.load(open(sys.argv[1])), key=lambda x: x["slug"]); raw, out = sys.argv[2], sys.argv[3]; os.makedirs(out, exist_ok=True)
for i, d in enumerate(docs):
dst = f"{out}/{i // 100:03d}_{i % 100:05d}.parquet"; src = f"{raw}/{d['slug']}.json"
if os.path.exists(dst) or not os.path.exists(src):
continue
name = f"{d['name']} {d.get('version') or d.get('release') or ''}".strip(); fidx = i % 100 + 100 * (i // 100)
cols = {"pid": [], "page_id": [], "title": [], "section": [], "text": []}; n = 0
for pi, (path, body) in enumerate(json.load(open(src)).items()):
p = Page(); p.feed(body); p.flush()
page = p.secs[1][0] if len(p.secs) > 1 and p.secs[1][0] else path
for head, w in p.secs:
if len(w) < MIN_WORDS:
continue
pre = f"{name} — {page}" + (f" — {head}" if head and head != page else "") + ": "
for j in range(0, len(w), WORDS):
part = w[j:j + WORDS + 20] if len(w) - j <= WORDS + 20 else w[j:j + WORDS]
if len(part) >= MIN_WORDS:
cols["pid"].append((fidx << 32) | n); cols["page_id"].append(pi); cols["title"].append(f"{name} — {page}")
cols["section"].append(head); cols["text"].append(pre + " ".join(part)); n += 1
if len(w) - j <= WORDS + 20:
break
pq.write_table(pa.table(cols), dst + ".tmp", compression="zstd", row_group_size=4096); os.replace(dst + ".tmp", dst)
print(d["slug"], "->", dst, "passages", n, flush=True)