"""hf_dolma.py SOURCE RAW OUT.json.gz (10-27) - one Hugging Face dataset file -> dolma json.gz (id, text, metadata.title) for dolma_chunk.py doc. Batch 1 of the research/*.md builds. Each source gets a title prefix naming where the passage came from (research/health.md: the model should see when a number belongs to a different source), light markup cleanup and a drop of bibliography / reference tails. SOURCE: sep nlab proofwiki stacks guidelines crs eb1911 se eurlex.""" import sys, os, re, json, gzip import pyarrow.parquet as pq src, raw, dst = sys.argv[1:4] def rows(): if os.path.isdir(raw): # 10-27: a directory of parquet files (EUR-Lex: one file per day) for fn in sorted(os.listdir(raw)): if fn.endswith(".parquet"): for b in pq.ParquetFile(f"{raw}/{fn}").iter_batches(batch_size=256): yield from b.to_pylist() elif raw.endswith(".parquet"): for b in pq.ParquetFile(raw).iter_batches(batch_size=512): yield from b.to_pylist() else: # 10-27: .jsonl.gz too (common-pile stackexchange) for line in (gzip.open(raw, "rt") if raw.endswith(".gz") else open(raw)): if line.strip(): yield json.loads(line) FIN = re.compile(r"\b(bank|credit institution|insurance|reinsurance|financial|investment|securities|capital requirement|solvency|liquidity|" r"derivative|accounting|audit|taxation|tax |vat|payment|monetary|money laundering|fund|stock exchange|prospectus|" r"market abuse|rating agenc|clearing|benchmark|crypto|pension|company law|interest rate)") TAIL = re.compile(r"\n\s*#*\s*(Bibliography|References|Academic Tools|Other Internet Resources|Related Entries|Sources)\s*\n", re.I) cut = lambda t: t[:m.start()] if (m := TAIL.search(t)) and m.start() > len(t) // 3 else t def nlab(t): t = re.sub(r"\[\[!include[^\]]*\]\]", "", t) t = re.sub(r"\[\[([^\]|]*)\|([^\]]*)\]\]", r"\2", t); t = re.sub(r"\[\[([^\]]*)\]\]", r"\1", t) t = "\n".join(x for x in t.replace("\r", "").split("\n") if not re.match(r"\s*(\+--|=--|\{:|\* table of contents)", x)) return re.sub(r"^#+\s*", "", t, flags=re.M) def conv(d): # 10-27: some rows hold lists of paragraphs (SEP content) -> join them d = {k: "\n".join(map(str, v)) if isinstance(v, list) else v for k, v in d.items()} if src == "sep": return "SEP: " + d["title"], cut(d["content"]) if src == "nlab": return "nLab: " + d["title"], cut(nlab(d["content"])) if src == "proofwiki": return "ProofWiki: " + (d.get("title") or ""), (d.get("problem") or "") + "\nProof\n" + (d.get("solution") or "") if src == "stacks": return "Stacks Project: " + d["title"].replace("stacks-", "").replace("-", " "), d["text"] if src == "guidelines": t = d.get("title") if d.get("title") not in (None, "None", "") else (d.get("clean_text") or "").strip().split("\n", 1)[0][:120] return f"Clinical guideline ({d.get('source', '?').upper()}): {t}", cut(d.get("clean_text") or "") if src == "crs": t = d["text"].replace("\r", "") return "CRS report: " + " ".join(t.strip().split("\n")[:2])[:150], cut(t) if src == "eb1911": return "Encyclopaedia Britannica 1911: " + d["title"], d.get("markdown") or "" if src == "eurlex": # finance / tax / company-law acts only (research/finance.md #5), by EuroVoc concept or title keyword k = (str(d.get("eurovoc_concepts")) + " " + (d.get("title") or "")).lower() if not FIN.search(k): return "", "" t = d.get("text") or ""; i = t.find(d.get("celex") or "\0", t.find("EUR-Lex") + 30); t = t[i:] if i > 0 else t return f"EU law {d.get('celex', '')}: {(d.get('title') or '')[:140]} ({d.get('date', '')})", t if src == "se": # question + top-voted answers (docs are vote-sorted, comments included): first SE_WORDS words only t = d["text"].split("\n", 1); site = (d.get("metadata") or {}).get("site", "stackexchange").replace(".stackexchange.com", "") return f"Stack Exchange ({site}): {t[0][:150]}", " ".join((t[1] if len(t) > 1 else "").split(" ")[:int(os.environ.get("SE_WORDS", 450))]) raise SystemExit(f"unknown source {src}") n = 0 with gzip.open(dst + ".tmp", "wt") as f: for i, d in enumerate(rows()): title, text = conv(d) if len((text or "").split()) < 30: continue f.write(json.dumps({"id": f"{src}-{i}", "text": text, "metadata": {"title": re.sub(r"\s+", " ", title).strip()}}) + "\n"); n += 1 import os # noqa: E402 os.replace(dst + ".tmp", dst) print(src, raw, "docs", n, flush=True)