forked from espnet/espnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsplitjson.py
executable file
·73 lines (60 loc) · 2.16 KB
/
splitjson.py
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
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import argparse
import codecs
import json
import logging
import os
import sys
import numpy as np
from espnet.utils.cli_utils import get_commandline_args
def get_parser():
parser = argparse.ArgumentParser(
description="split a json file for parallel processing",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument("json", type=str, help="json file")
parser.add_argument(
"--parts", "-p", type=int, help="Number of subparts to be prepared", default=0
)
return parser
if __name__ == "__main__":
args = get_parser().parse_args()
# logging info
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s (%(module)s:%(lineno)d) %(levelname)s: %(message)s",
)
logging.info(get_commandline_args())
# check directory
filename = os.path.basename(args.json).split(".")[0]
dirname = os.path.dirname(args.json)
dirname = "{}/split{}utt".format(dirname, args.parts)
if not os.path.exists(dirname):
os.makedirs(dirname)
# load json and split keys
j = json.load(codecs.open(args.json, "r", encoding="utf-8"))
utt_ids = sorted(list(j["utts"].keys()))
logging.info("number of utterances = %d" % len(utt_ids))
if len(utt_ids) < args.parts:
logging.error("#utterances < #splits. Use smaller split number.")
sys.exit(1)
utt_id_lists = np.array_split(utt_ids, args.parts)
utt_id_lists = [utt_id_list.tolist() for utt_id_list in utt_id_lists]
for i, utt_id_list in enumerate(utt_id_lists):
new_dic = dict()
for utt_id in utt_id_list:
new_dic[utt_id] = j["utts"][utt_id]
jsonstring = json.dumps(
{"utts": new_dic},
indent=4,
ensure_ascii=False,
sort_keys=True,
separators=(",", ": "),
)
fl = "{}/{}.{}.json".format(dirname, filename, i + 1)
sys.stdout = codecs.open(fl, "w+", encoding="utf-8")
print(jsonstring)
sys.stdout.close()