File size: 2,175 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 | """usc_dolma.py PKG.zip OUT.json.gz (10-27) - US Code title package from govinfo (USCODE-<year>-title<N>.zip, public domain;
research/finance.md #3 "USC with notes") -> dolma json.gz for dolma_chunk.py doc. Reads the full-title HTML inside the zip, one doc
per section (<h3 class="section-head">), title "<N> U.S.C. § x. Heading" (questions cite sections, BM25 needs the citation).
Statutory text first; tables flattened to "a | b" rows; the editorial notes (amendments, effective dates) are appended but capped at
NOTE_WORDS words so amendment histories do not swamp the table."""
import sys, re, json, gzip, zipfile, os, html
src, dst = sys.argv[1:3]; NOTE_WORDS = int(os.environ.get("NOTE_WORDS", 300))
zf = zipfile.ZipFile(src)
tn = re.search(r"title(\d+[a-z]?)", os.path.basename(src)).group(1)
main = [n for n in zf.namelist() if re.search(rf"/html/USCODE-\d+-title{tn}\.htm$", n)]
H = zf.read(main[0]).decode("utf-8", "replace")
clean = lambda s: re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", s))).strip()
n = 0
with gzip.open(dst + ".tmp", "wt") as f:
parts = re.split(r'<h3 class="section-head">', H)
for p in parts[1:]:
head, _, body = p.partition("</h3>")
head = clean(head)
if not head or "Repealed" in head[:80] or "Omitted" in head[:80]:
continue
body = re.split(r'<h3 class="', body, maxsplit=1)[0] # stop at the next part/chapter heading
body = re.sub(r"</t[dh]>\s*<t[dh][^>]*>", " | ", body); body = re.sub(r"</(p|h4|tr|li)>", "\n", body)
lines = [clean(x) for x in body.split("\n")]; lines = [x for x in lines if x]
k = next((i for i, x in enumerate(lines) if re.match(r"(Editorial Notes|Statutory Notes|References in Text|Amendments|Prior Provisions)\b", x)), len(lines))
stat, notes = "\n".join(lines[:k]), " ".join(" ".join(lines[k:]).split()[:NOTE_WORDS])
if len(stat.split()) < 15:
continue
f.write(json.dumps({"id": f"usc{tn}-{n}", "text": stat + ("\nNotes\n" + notes if notes else ""), "metadata": {"title": f"{tn} U.S.C. {head}"[:160]}}) + "\n"); n += 1
os.replace(dst + ".tmp", dst)
print(src, "sections", n, flush=True)
|