forked from k2-fsa/sherpa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode_manifest.py
executable file
·201 lines (164 loc) · 5.4 KB
/
decode_manifest.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
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python3
# Copyright 2022 Xiaomi Corp. (authors: Fangjun Kuang)
#
# See LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
This script loads a manifest in lhotse format and sends it to the server
for decoding, in parallel.
Usage:
./decode_manifest.py
(Note: You have to first start the server before starting the client)
"""
import argparse
import asyncio
import time
from pathlib import Path
import numpy as np
import websockets
from icefall.utils import store_transcripts, write_error_stats
from lhotse import CutSet, load_manifest
DEFAULT_MANIFEST_FILENAME = "/ceph-fj/fangjun/open-source/icefall-tdnnf/egs/librispeech/ASR/data/fbank/librispeech_cuts_test-clean.jsonl.gz" # noqa
def get_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"--server-addr",
type=str,
default="localhost",
help="Address of the server",
)
parser.add_argument(
"--server-port",
type=int,
default=6006,
help="Port of the server",
)
parser.add_argument(
"--manifest-filename",
type=str,
default=DEFAULT_MANIFEST_FILENAME,
help="Path to the manifest for decoding",
)
parser.add_argument(
"--num-tasks",
type=int,
default=50,
help="Number of tasks to use for sending",
)
parser.add_argument(
"--log-interval",
type=int,
default=5,
help="Controls how frequently we print the log.",
)
parser.add_argument(
"--compute-cer",
action="store_true",
default=False,
help="""True to compute CER, e.g., for Chinese.
False to compute WER, e.g., for English words.
""",
)
return parser.parse_args()
async def send(
cuts: CutSet,
name: str,
server_addr: str,
server_port: int,
log_interval: int,
compute_cer: bool,
):
total_duration = 0.0
results = []
async with websockets.connect(
f"ws://{server_addr}:{server_port}"
) as websocket: # noqa
for i, c in enumerate(cuts):
if i % log_interval == 0:
print(f"{name}: {i}/{len(cuts)}")
samples = c.load_audio().reshape(-1).astype(np.float32)
num_bytes = samples.nbytes
await websocket.send((num_bytes).to_bytes(8, "little", signed=True))
frame_size = (2 ** 20) // 4 # max payload is 1MB
start = 0
while start < samples.size:
end = start + frame_size
await websocket.send(samples.data[start:end])
start = end
decoding_results = await websocket.recv()
total_duration += c.duration
if compute_cer:
ref = c.supervisions[0].text.split()
hyp = decoding_results.split()
ref = list("".join(ref))
hyp = list("".join(hyp))
results.append((ref, hyp))
else:
results.append(
(c.supervisions[0].text.split(), decoding_results.split())
) # noqa
await websocket.send(b"Done")
return total_duration, results
async def main():
args = get_args()
filename = args.manifest_filename
server_addr = args.server_addr
server_port = args.server_port
num_tasks = args.num_tasks
log_interval = args.log_interval
compute_cer = args.compute_cer
cuts = load_manifest(filename)
cuts_list = cuts.split(num_tasks)
tasks = []
start_time = time.time()
for i in range(num_tasks):
task = asyncio.create_task(
send(
cuts=cuts_list[i],
name=f"task-{i}",
server_addr=server_addr,
server_port=server_port,
log_interval=log_interval,
compute_cer=compute_cer,
)
)
tasks.append(task)
ans_list = await asyncio.gather(*tasks)
end_time = time.time()
elapsed = end_time - start_time
results = []
total_duration = 0.0
for ans in ans_list:
total_duration += ans[0]
results += ans[1]
rtf = elapsed / total_duration
print(f"RTF: {rtf:.4f}")
print(
f"total_duration: {total_duration:.3f} seconds "
f"({total_duration/3600:.2f} hours)"
)
print(
f"processing time: {elapsed:.3f} seconds " f"({elapsed/3600:.2f} hours)"
) # noqa
name = Path(filename).stem.split(".")[0]
store_transcripts(filename=f"recogs-{name}.txt", texts=results)
with open(f"errs-{name}.txt", "w") as f:
write_error_stats(f, "test-set", results, enable_log=True)
with open(f"errs-{name}.txt", "r") as f:
print(f.readline()) # WER
print(f.readline()) # Detailed errors
if __name__ == "__main__":
asyncio.run(main())