File size: 2,273 Bytes
a4e6b16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
"""Render a few parquet rows as readable markdown for a PR description.

Usage: python3 src/render_sample.py data/<key>/<key>.parquet [-n 3] [--max-chars 800]

Each document becomes a fenced block: metadata as `key: value` lines, a blank
line, then the text with real newlines, truncated with `[…]`.
"""
import argparse
import random
import re

import pyarrow.parquet as pq


def sample_rows(path, n, seed=0):
    """n rows from distinct random row groups (seeded), so a 2B-token shard isn't read whole."""
    pf = pq.ParquetFile(path)
    if pf.num_row_groups == 0 or n <= 0:
        return []
    rng = random.Random(seed)
    groups = rng.sample(range(pf.num_row_groups), min(n, pf.num_row_groups))
    per_group = -(-n // len(groups))  # ceil: few row groups -> several rows each
    rows = []
    for g in sorted(groups):
        batch = pf.read_row_group(g).to_pylist()
        rows += rng.sample(batch, min(per_group, len(batch)))
    return rows[:n]


def truncate(text, max_chars):
    text = text.strip()
    if len(text) <= max_chars:
        return text
    cut = text[:max_chars]
    space = max(cut.rfind(" "), cut.rfind("\n"))
    return (cut[:space] if space > 0 else cut).rstrip() + " […]"


def fmt_value(v):
    if isinstance(v, (list, tuple)):
        return ", ".join(fmt_value(x) for x in v)
    if hasattr(v, "isoformat"):
        return v.isoformat()
    return str(v)


def render_doc(row, max_chars):
    meta = [f"{k}: {fmt_value(v)}" for k, v in row.items() if k != "text"]
    body = "\n".join(meta) + "\n\n" + truncate(row.get("text") or "", max_chars)
    longest = max((len(m) for m in re.findall(r"`+", body)), default=0)
    fence = "`" * max(3, longest + 1)
    return f"{fence}\n{body}\n{fence}"


def render(path, n=3, max_chars=800, seed=0):
    return "\n\n".join(render_doc(r, max_chars) for r in sample_rows(path, n, seed))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("parquet")
    ap.add_argument("-n", type=int, default=3)
    ap.add_argument("--max-chars", type=int, default=800)
    ap.add_argument("--seed", type=int, default=0)
    a = ap.parse_args()
    print(render(a.parquet, a.n, a.max_chars, a.seed))