huangmingming
2023-01-30 adcee8828ef5d78b575043954deb662a35e318f7
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
from __future__ import print_function
import numpy as np
import os
import kaldiio
from multiprocessing import Pool
import argparse
from tqdm import tqdm
import math
 
 
class MultiProcessRunner:
    def __init__(self, fn):
        self.args = None
        self.process = fn
 
    def run(self):
        parser = argparse.ArgumentParser("")
        # Task-independent options
        parser.add_argument("--nj", type=int, default=16)
        parser.add_argument("--debug", action="store_true", default=False)
        parser.add_argument("--no_pbar", action="store_true", default=False)
        parser.add_argument("--verbose", action="store_ture", default=False)
 
        task_list, args = self.prepare(parser)
        result_list = self.pool_run(task_list, args)
        self.post(result_list, args)
 
    def prepare(self, parser):
        raise NotImplementedError("Please implement the prepare function.")
 
    def post(self, result_list, args):
        raise NotImplementedError("Please implement the post function.")
 
    def pool_run(self, tasks, args):
        results = []
        if args.debug:
            one_result = self.process(tasks[0])
            results.append(one_result)
        else:
            pool = Pool(args.nj)
            for one_result in tqdm(pool.imap(self.process, tasks), total=len(tasks), ascii=True, disable=args.no_pbar):
                results.append(one_result)
            pool.close()
 
        return results
 
 
class MultiProcessRunnerV2:
    def __init__(self, fn):
        self.args = None
        self.process = fn
 
    def run(self):
        parser = argparse.ArgumentParser("")
        # Task-independent options
        parser.add_argument("--nj", type=int, default=16)
        parser.add_argument("--debug", action="store_true", default=False)
        parser.add_argument("--no_pbar", action="store_true", default=False)
        parser.add_argument("--verbose", action="store_true", default=False)
 
        task_list, args = self.prepare(parser)
        chunk_size = int(math.ceil(float(len(task_list)) / args.nj))
        if args.verbose:
            print("Split {} tasks into {} sub-tasks with chunk_size {}".format(len(task_list), args.nj, chunk_size))
        subtask_list = [task_list[i*chunk_size: (i+1)*chunk_size] for i in range(args.nj)]
        result_list = self.pool_run(subtask_list, args)
        self.post(result_list, args)
 
    def prepare(self, parser):
        raise NotImplementedError("Please implement the prepare function.")
 
    def post(self, result_list, args):
        raise NotImplementedError("Please implement the post function.")
 
    def pool_run(self, tasks, args):
        results = []
        if args.debug:
            one_result = self.process(tasks[0])
            results.append(one_result)
        else:
            pool = Pool(args.nj)
            for one_result in tqdm(pool.imap(self.process, tasks), total=len(tasks), ascii=True, disable=args.no_pbar):
                results.append(one_result)
            pool.close()
 
        return results
 
 
class MultiProcessRunnerV3(MultiProcessRunnerV2):
    def run(self):
        parser = argparse.ArgumentParser("")
        # Task-independent options
        parser.add_argument("--nj", type=int, default=16)
        parser.add_argument("--debug", action="store_true", default=False)
        parser.add_argument("--no_pbar", action="store_true", default=False)
        parser.add_argument("--verbose", action="store_true", default=False)
        parser.add_argument("--sr", type=int, default=16000)
 
        task_list, shared_param, args = self.prepare(parser)
        chunk_size = int(math.ceil(float(len(task_list)) / args.nj))
        if args.verbose:
            print("Split {} tasks into {} sub-tasks with chunk_size {}".format(len(task_list), args.nj, chunk_size))
        subtask_list = [(i, task_list[i * chunk_size: (i + 1) * chunk_size], shared_param, args)
                        for i in range(args.nj)]
        result_list = self.pool_run(subtask_list, args)
        self.post(result_list, args)
 
 
 
class MyRunner(MultiProcessRunnerV3):
    def prepare(self, parser):
        assert isinstance(parser, argparse.ArgumentParser)
        parser.add_argument("enroll_dir", type=str)
        parser.add_argument("trial_in", type=str)
        parser.add_argument("trial_out", type=str)
        args = parser.parse_args()
 
        if not os.path.exists(os.path.dirname(args.trial_out)):
            os.makedirs(os.path.dirname(args.trial_out))
 
        flist_path = os.path.join(args.enroll_dir, "spk2xvec.flist")
        spk2xvec = {}
        for _path in open(flist_path, "r"):
            for key, value in kaldiio.load_ark(_path.strip()):
                if "-enroll" in key:
                    key = key.replace("-enroll", "")
                spk2xvec[key] = value
 
        flist_path = os.path.join(args.enroll_dir, "utt2xvec.flist")
        utt2xvec = {}
        for _path in open(flist_path, 'r'):
            for key, value in kaldiio.load_ark(_path.strip()):
                utt2xvec[key] = value
 
        task_list = [one_line.strip().split(" ") for one_line in open(args.trial_in, "rt")]
        return task_list, [spk2xvec, utt2xvec], args
 
    def post(self, results_list, args):
        with open(args.trial_out, "wt") as fs:
            for results in results_list:
                for one_item in results:
                    fs.write(one_item+"\n")
 
 
def process(task_args):
    task_id, task_list, [spk2xvec, utt2xvec], args = task_args
    results = []
    for spk, utt, _ in task_list:
        xvec = utt2xvec[utt]
        normed_x = xvec / np.linalg.norm(xvec)
        normed_y = spk2xvec[spk] / np.linalg.norm(spk2xvec[spk])
        score = np.sum(normed_x * normed_y)
        results.append("{} {} {:.5f}".format(spk, utt, score))
 
    return results
 
 
if __name__ == '__main__':
    my_runner = MyRunner(process)
    my_runner.run()