File size: 3,340 Bytes
8c9d5ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#!/usr/bin/env python3
"""Stream stackbuild sample Parquet files and inspect their structured fields."""

from __future__ import annotations

import argparse
import json
from pathlib import Path

import pyarrow.dataset as ds


def _expand_paths(values: list[str]) -> list[str]:
    paths: list[str] = []
    for value in values:
        path = Path(value)
        if path.is_dir():
            paths.extend(str(item) for item in sorted(path.glob("*.parquet")))
        else:
            paths.append(value)
    if not paths:
        raise SystemExit("no Parquet files found")
    return paths


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("paths", nargs="+", help="Parquet files, globs, or a directory")
    parser.add_argument("--limit", type=int, default=3, help="maximum matching samples to print")
    parser.add_argument("--repo", help="filter by exact repo_id")
    parser.add_argument("--kind", choices=("dependency", "target_context"), help="filter by sample kind")
    parser.add_argument("--text-chars", type=int, default=400,
                        help="characters of sample text to include; 0 prints all text")
    parser.add_argument("--json", action="store_true", help="emit one JSON object per sample")
    args = parser.parse_args()
    if args.limit < 1:
        parser.error("--limit must be positive")
    if args.text_chars < 0:
        parser.error("--text-chars must be non-negative")

    expression = None
    if args.repo:
        expression = ds.field("repo_id") == args.repo
    if args.kind:
        kind_expression = ds.field("kind") == args.kind
        expression = kind_expression if expression is None else expression & kind_expression
    dataset = ds.dataset(_expand_paths(args.paths), format="parquet")
    scanner = dataset.scanner(
        columns=["sample_id", "repo_id", "revision_id", "kind", "text", "files",
                 "token_count", "metadata_json"],
        filter=expression,
        batch_size=256,
    )
    printed = 0
    for batch in scanner.to_batches():
        for row in batch.to_pylist():
            text = row["text"]
            record = {
                "sample_id": row["sample_id"],
                "repo_id": row["repo_id"],
                "revision_id": row["revision_id"],
                "kind": row["kind"],
                "token_count": row["token_count"],
                "metadata": json.loads(row["metadata_json"]),
                "files": row["files"],
                "text": text if args.text_chars == 0 else text[:args.text_chars],
            }
            if args.json:
                print(json.dumps(record, ensure_ascii=False))
            else:
                print(f"sample_id: {record['sample_id']}")
                print(f"repo_id:   {record['repo_id']}")
                print(f"kind:      {record['kind']}")
                print(f"tokens:    {record['token_count']}")
                print(f"files:     {', '.join(item['path'] for item in record['files'][:8])}")
                print(f"metadata:  {json.dumps(record['metadata'], ensure_ascii=False)}")
                print("text:")
                print(record["text"])
                print("-" * 72)
            printed += 1
            if printed >= args.limit:
                return


if __name__ == "__main__":
    main()