File size: 3,154 Bytes
9728219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""primtexts.py MODE SRC OUT.json.gz (11-02, tablinum-3 Humanities rank 2 "humprim", research/humanities_round2.md) - primary texts ->
dolma docs (id, text, metadata.title) for dolma_chunk.py doc. Every passage title carries the work and a locator.
  gutenberg  SRC = sedthh/gutenberg_english parquet. Kept by Library of Congress class (domain, never by benchmark items): B (philosophy,
             psychology, religion), D/E/F (history), J (political science), PA (Greek & Latin classics); PQ/PR/PS/PT (literature) only
             when subjects/bookshelves say drama, poetry, short stories, essays, speeches or letters (no novels). Title "Work (Author)". PD.
  wikisource SRC = wikimedia/wikisource 20231201.en parquet; pages with >= 80 words (drops index/list pages). PD / CC BY-SA.
  sefaria    SRC = Sefaria/english_library data.jsonl; segments grouped into chapter docs by ref ("Genesis 1", "Mishnah Berakhot 2"),
             title = chapter ref. Per-text licences (mostly CC BY / CC BY-SA / PD): local use; check before redistribution."""
import ast, gzip, json, re, sys
import pyarrow.parquet as pq
mode, src, dst = sys.argv[1:4]; out = gzip.open(dst, "at"); n = 0


def put(did, title, text):
    global n
    if len(text.split()) >= 80 or (mode == "sefaria" and len(text.split()) >= 20):
        out.write(json.dumps({"id": did, "text": text, "metadata": {"title": title[:200]}}, ensure_ascii=False) + "\n"); n += 1


if mode == "gutenberg":
    LIT = re.compile(r"drama|plays|poetry|poems|short stories|essays|speeches|orations|letters|correspondence", re.I)
    t = pq.read_table(src)
    for text, md in zip(t.column("TEXT").to_pylist(), t.column("METADATA").to_pylist()):
        m = json.loads(md); locc = [x.strip() for x in (m.get("locc") or "").split(";")]
        ok = any(c[:1] in "BDEFJ" or c[:2] == "PA" for c in locc if c) or \
            (any(c[:2] in ("PQ", "PR", "PS", "PT") for c in locc) and LIT.search((m.get("subjects") or "") + " " + (m.get("bookshelves") or "")))
        if not ok: continue
        title = re.sub(r"\s+", " ", m.get("title") or "").strip(); au = (m.get("authors") or "").split(";")[0].strip()
        put(f"pg{m.get('text_id')}", f"{title} ({au})" if au else title, text.replace("\r\n", "\n"))
elif mode == "wikisource":
    t = pq.read_table(src, columns=["id", "title", "text"])
    for i, ti, tx in zip(t.column("id").to_pylist(), t.column("title").to_pylist(), t.column("text").to_pylist()):
        put(f"ws{i}", f"Wikisource: {ti}", tx)
elif mode == "sefaria":
    key, buf = None, []
    def flush():
        if key and buf: put(f"sef:{key}", key, "\n".join(buf))
    for l in open(src, encoding="utf-8"):
        d = json.loads(l); m = d.get("metadata"); m = ast.literal_eval(m) if isinstance(m, str) else (m or {})
        ref = m.get("ref") or ""; k = re.sub(r"[:.]\d+(-\d+)?$", "", ref) if re.search(r"\d+[:.]\d+$", ref) else re.sub(r"\s+\d+$", "", ref)
        if k != key or sum(len(x.split()) for x in buf) > 600:
            flush(); key, buf = k, []
        buf.append(re.sub(r"<[^>]+>", "", d.get("text") or ""))
    flush()
out.close(); print(mode, src, n, "docs", file=sys.stderr)