| |
| """Randomly sample entries from a JSON list.""" |
|
|
| import argparse |
| import json |
| import os |
| import random |
| import sys |
|
|
| """ |
| python sample_data/sample_json.py \ |
| --input outputs/results_filter_data_test.json \ |
| --num 10000 \ |
| --output sample_data/sampled_data_1.json |
| |
| python sample_data/sample_json.py \ |
| --input outputs/results_filter_data_test_humo.json \ |
| --num 10000 \ |
| --output sample_data/sampled_data_2.json |
| |
| python sample_data/sample_json.py \ |
| --input outputs/results_filter_data_test_mismatched.json \ |
| --num 10000 \ |
| --output sample_data/sampled_data_3.json |
| |
| """ |
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Randomly sample N items from a JSON list and save to a new file.", |
| ) |
| parser.add_argument( |
| "--input", |
| default="outputs/results_filter_data_test.json", |
| help="Input JSON path (default: outputs/results_filter_data_test.json)", |
| ) |
| parser.add_argument( |
| "--output", |
| required=True, |
| help="Output JSON path for the sampled items", |
| ) |
| parser.add_argument( |
| "--num", |
| type=int, |
| required=True, |
| help="Number of items to sample", |
| ) |
| parser.add_argument( |
| "--seed", |
| type=int, |
| default=42, |
| help="Random seed (default: 42)", |
| ) |
| return parser.parse_args() |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
|
|
| if args.num <= 0: |
| print("--num must be a positive integer", file=sys.stderr) |
| return 2 |
|
|
| with open(args.input, "r", encoding="utf-8") as f: |
| data = json.load(f) |
|
|
| if not isinstance(data, list): |
| print("Input JSON must be a list", file=sys.stderr) |
| return 2 |
|
|
| total = len(data) |
| if args.num > total: |
| print(f"Requested {args.num} items, but only {total} available", file=sys.stderr) |
| return 2 |
|
|
| random.seed(args.seed) |
| sampled = random.sample(data, args.num) |
|
|
| os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) |
| with open(args.output, "w", encoding="utf-8") as f: |
| json.dump(sampled, f, ensure_ascii=False, indent=2) |
|
|
| print(f"Saved {len(sampled)} items to {args.output}") |
| return 0 |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|