File size: 3,114 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""chunk.py IN.parquet OUT.parquet - finewiki enwiki articles -> engram passages (10-19).
Each passage is ~WORDS words of one section, prefixed "Title — Section: " so it stands alone; each infobox becomes one
"Title (infobox): key: value; ..." passage (dates, numbers, names - the facts low-bit weights lose first). Stubs under
MIN_WORDS words and list/disambiguation pages are dropped. Output columns: pid (int64, file_idx<<32 | n), page_id, title,
section, text."""
import sys, re, json
import pyarrow as pa, pyarrow.parquet as pq
WORDS, MIN_WORDS = 120, 30
SKIP = re.compile(r"^(List of|Lists of|Index of|Outline of)\b|\(disambiguation\)$")
H = re.compile(r"^(#{1,6})\s+(.*)$")


def passages(title, text, infob):
    out = []
    try:
        for ib in json.loads(infob or "[]")[:2]:
            kv = "; ".join(f"{k}: {v}" for k, v in (ib.get("data") or {}).items() if v)[:900]
            if kv:
                out.append(("infobox", f"{title} (infobox): {kv}"))
    except (ValueError, AttributeError):
        pass
    sec, buf = "", []

    def flush():
        w = " ".join(buf).split()
        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_WORDS or (i == 0 and len(part) >= 12):
                out.append((sec, f"{title} — {sec}: " + " ".join(part) if sec else f"{title}: " + " ".join(part)))
            if len(w) - i <= WORDS + 20:
                break
    for line in text.split("\n"):
        m = H.match(line)
        if m:
            flush(); buf = []
            sec = "" if len(m.group(1)) == 1 else m.group(2).strip()
            if sec.lower() in ("references", "external links", "see also", "further reading", "notes", "bibliography", "sources", "citations"):
                sec = "\x00"
        elif sec != "\x00" and line.strip():
            buf.append(line.strip())
    if sec != "\x00":
        flush()
    return out


src, dst = sys.argv[1], sys.argv[2]
fidx = int(re.search(r"(\d+)_(\d+)\.parquet$", src).group(2)) + 100 * int(re.search(r"(\d+)_(\d+)\.parquet$", src).group(1))
pf = pq.ParquetFile(src); w = None; n = 0; arts = 0
for rg in range(pf.num_row_groups):
    t = pf.read_row_group(rg, columns=["page_id", "title", "text", "infoboxes"]).to_pylist()
    cols = {"pid": [], "page_id": [], "title": [], "section": [], "text": []}
    for r in t:
        if SKIP.search(r["title"] or "") or len((r["text"] or "").split()) < MIN_WORDS:
            continue
        arts += 1
        for sec, p in passages(r["title"], r["text"] or "", r["infoboxes"]):
            cols["pid"].append((fidx << 32) | n); cols["page_id"].append(r["page_id"]); cols["title"].append(r["title"])
            cols["section"].append(sec); cols["text"].append(p); n += 1
    tb = pa.table(cols)
    w = w or pq.ParquetWriter(dst + ".tmp", tb.schema, compression="zstd")
    w.write_table(tb, row_group_size=4096)   # small row groups: the retriever reads single passages back by pid
w.close()
import os; os.replace(dst + ".tmp", dst)
print(src, "articles", arts, "passages", n, flush=True)