"""ecfr_dolma.py ECFR-titleN.xml OUT.json.gz (10-27) - govinfo eCFR bulk XML -> dolma json.gz for dolma_chunk.py doc: one doc per SECTION (DIV8), title "N CFR ยง x.y Heading" (research/finance.md: questions name the citation, so BM25 needs it in the passage), text = its paragraphs. Public domain.""" import sys, re, json, gzip import xml.etree.ElementTree as ET src, dst = sys.argv[1:3] tn = re.search(r"title-?(\d+)", src).group(1) txt = lambda e: re.sub(r"\s+", " ", "".join(e.itertext())).strip() n, part = 0, "" with gzip.open(dst + ".tmp", "wt") as f: for ev, e in ET.iterparse(src, events=("end",)): if e.tag.startswith("DIV") and e.get("TYPE") == "PART": e.clear(); continue if e.tag.startswith("DIV") and e.get("TYPE") == "SECTION": h = e.find("HEAD"); head = txt(h) if h is not None else e.get("N", "") body = "\n".join(txt(p) for p in e.iter() if p.tag in ("P", "FP", "NOTE", "EXTRACT") and txt(p)) if len(body.split()) >= 20: f.write(json.dumps({"id": f"ecfr{tn}-{n}", "text": body, "metadata": {"title": f"{tn} CFR {head}"[:160]}}) + "\n"); n += 1 e.clear() import os # noqa: E402 os.replace(dst + ".tmp", dst) print(src, "sections", n, flush=True)