File size: 2,287 Bytes
12c201b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
#!/usr/bin/env python3
"""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())