the-stack-go / stackgo /examples /read_samples.py
s0duku's picture
Add sample reading examples
8c9d5ac verified
Raw History Blame Contribute Delete
3.34 kB
#!/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()