| |
| """Merge multiple JSON list files into one training JSON.""" |
|
|
| import argparse |
| import json |
| import os |
| import sys |
| from typing import List, Tuple |
|
|
|
|
| """ |
| python sample_data/merge_json.py \ |
| --inputs /share/zhaohu_workspace/VideoDataProcessing/syncnet_claude/sample_data/sampled_data_1.json /share/zhaohu_workspace/VideoDataProcessing/syncnet_claude/sample_data/sampled_data_2.json /share/zhaohu_workspace/VideoDataProcessing/syncnet_claude/sample_data/sampled_data_3.json \ |
| --output sample_data/train_merged.json \ |
| --shuffle --seed 123 \ |
| --bins "0,2;2,5;5,8;8,10" |
| """ |
| def parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser( |
| description="Merge multiple JSON list files into a single JSON file.", |
| ) |
| parser.add_argument( |
| "--inputs", |
| nargs="+", |
| required=True, |
| help="Input JSON paths (each must be a list)", |
| ) |
| parser.add_argument( |
| "--output", |
| required=True, |
| help="Output JSON path", |
| ) |
| parser.add_argument( |
| "--shuffle", |
| action="store_true", |
| help="Shuffle merged items before saving", |
| ) |
| parser.add_argument( |
| "--seed", |
| type=int, |
| default=42, |
| help="Random seed used when --shuffle is set (default: 42)", |
| ) |
| parser.add_argument( |
| "--bins", |
| default="0,2;2,5", |
| help=( |
| "Score bins as 'start,end;start,end;...'. " |
| "Example: 0,2;2,5;5,10 (default: 0,2;2,5)" |
| ), |
| ) |
| return parser.parse_args() |
|
|
|
|
| def main() -> int: |
| args = parse_args() |
|
|
| merged = [] |
| null_dropped = 0 |
| score_null_dropped = 0 |
| total_scored = 0 |
| for path in args.inputs: |
| with open(path, "r", encoding="utf-8") as f: |
| data = json.load(f) |
| if not isinstance(data, list): |
| print(f"Input JSON must be a list: {path}", file=sys.stderr) |
| return 2 |
| for item in data: |
| if item is None: |
| null_dropped += 1 |
| continue |
| if isinstance(item, dict) and item.get("syncnet_confidence_score") is None: |
| score_null_dropped += 1 |
| continue |
| merged.append(item) |
|
|
| if args.shuffle: |
| import random |
|
|
| random.seed(args.seed) |
| random.shuffle(merged) |
|
|
| bins = _parse_bins(args.bins) |
| bin_counts = [0 for _ in bins] |
| for item in merged: |
| if not isinstance(item, dict): |
| continue |
| score = item.get("syncnet_confidence_score") |
| if score is None: |
| continue |
| total_scored += 1 |
| for i, (start, end) in enumerate(bins): |
| if start <= score < end: |
| bin_counts[i] += 1 |
| break |
|
|
| os.makedirs(os.path.dirname(args.output) or ".", exist_ok=True) |
| with open(args.output, "w", encoding="utf-8") as f: |
| json.dump(merged, f, ensure_ascii=False, indent=2) |
|
|
| print( |
| f"Merged {len(args.inputs)} files, total {len(merged)} items " |
| f"(dropped {null_dropped} nulls, " |
| f"{score_null_dropped} missing syncnet_confidence_score) -> {args.output}" |
| ) |
| _print_bin_stats(bins, bin_counts, total_scored) |
| return 0 |
|
|
|
|
| def _parse_bins(text: str) -> List[Tuple[float, float]]: |
| bins: List[Tuple[float, float]] = [] |
| for part in text.split(";"): |
| part = part.strip() |
| if not part: |
| continue |
| try: |
| start_str, end_str = part.split(",") |
| start = float(start_str) |
| end = float(end_str) |
| except ValueError as exc: |
| raise SystemExit(f"Invalid --bins value: {part}") from exc |
| if end <= start: |
| raise SystemExit(f"Invalid --bins range (end<=start): {part}") |
| bins.append((start, end)) |
| if not bins: |
| raise SystemExit("No valid bins parsed from --bins") |
| return bins |
|
|
|
|
| def _print_bin_stats( |
| bins: List[Tuple[float, float]], |
| bin_counts: List[int], |
| total_scored: int, |
| ) -> None: |
| if total_scored == 0: |
| print("Score bin stats: no valid scores to analyze") |
| return |
| print("Score bin stats:") |
| for (start, end), count in zip(bins, bin_counts): |
| ratio = count / total_scored |
| print(f" [{start}, {end}): {count} ({ratio:.2%})") |
|
|
|
|
| if __name__ == "__main__": |
| raise SystemExit(main()) |
|
|