"""pes2o_full.py SHARD.zst IDX (11-02, tablinum-3 Humanities rank 3, research/humanities_round2.md) - peS2o v3 s2orc FULL-TEXT shard -> papers_humft passages for humanities papers (s2fieldsofstudy has History / Philosophy / Art / Linguistics / Political Science). Text = title line, blank, body. Kept: the first HEAD (4000) words + the last TAIL (500) words, in WORDS-word windows (150, +20 tail merge). A short line with no end punctuation starts a section ("Introduction", "2. The Treaty of ..."); the passage title is "Title (year) — section". Year >= 1970. Reads through zstdcat. ODC-By: local retrieval only, do not redistribute the table. Writes tables/papers_humft/passages/000_.parquet.""" import sys, os, json, ast, re, subprocess import pyarrow as pa, pyarrow.parquet as pq E = os.environ.get("ENGRAM_ROOT", "."); WORDS, HEAD, TAIL, MIN = 150, 4000, 500, 25 HUM = {"History", "Philosophy", "Art", "Linguistics", "Political Science"} src, idx = sys.argv[1], int(sys.argv[2]); fidx = 900000 + idx # file index space apart from papers_hum's cols = {"pid": [], "page_id": [], "title": [], "section": [], "text": []}; n = docs = kept = 0 HDR = re.compile(r"^(\d+(\.\d+)*\.?\s+)?[A-Z][^.!?]{2,80}$") p = subprocess.Popen(["zstdcat", src], stdout=subprocess.PIPE, text=True, bufsize=1 << 20) for line in p.stdout: try: d = json.loads(line) except ValueError: continue docs += 1; m = d.get("metadata") or {} m = ast.literal_eval(m) if isinstance(m, str) else m if not (set(m.get("s2fieldsofstudy") or []) & HUM) or (m.get("year") or 0) < 1970: continue lines = d["text"].split("\n"); title = lines[0].strip()[:200]; y = m.get("year") if not title: continue kept += 1; doc = int(d["id"]) if str(d["id"]).isdigit() else int(__import__("hashlib").sha1(str(d["id"]).encode()).hexdigest()[:15], 16); head = f"{title} ({y})" if y else title # (section, words) runs, then cut to HEAD + TAIL words overall runs, sec, total = [], "", 0 for l in lines[1:]: s = l.strip() if not s: continue if len(s.split()) <= 12 and HDR.match(s): sec = s; continue runs.append((sec, s.split())); total += len(runs[-1][1]) budget = []; seen = 0 for sec_, w in runs: a, b = seen, seen + len(w); seen = b keep = [x for i, x in enumerate(w, a) if i < HEAD or i >= total - TAIL] if keep: budget.append((sec_, keep)) merged = [] for sec_, w in budget: # merge consecutive paragraphs of the same section if merged and merged[-1][0] == sec_: merged[-1][1].extend(w) else: merged.append((sec_, list(w))) for sec_, w in merged: for i in range(0, len(w), WORDS): part = w[i:i + WORDS + 20] if len(w) - i <= WORDS + 20 else w[i:i + WORDS] if len(part) >= MIN: cols["pid"].append((fidx << 32) | n); cols["page_id"].append(doc); cols["title"].append(head); cols["section"].append(sec_) cols["text"].append(f"{head} — {sec_}: " + " ".join(part) if sec_ else f"{head}: " + " ".join(part)); n += 1 if len(w) - i <= WORDS + 20: break out = f"{E}/tables/papers_humft/passages/000_{idx:05d}.parquet"; os.makedirs(os.path.dirname(out), exist_ok=True) pq.write_table(pa.table({k: pa.array(v, type=pa.int64() if k in ("pid", "page_id") else pa.string()) for k, v in cols.items()}), out + ".tmp") os.replace(out + ".tmp", out) print(f"{src}: docs {docs} humanities {kept} passages {n}", flush=True)