forked from speechmatics/speechmatics-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_cli.py
More file actions
421 lines (375 loc) · 13.1 KB
/
test_cli.py
File metadata and controls
421 lines (375 loc) · 13.1 KB
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import argparse
import collections
import copy
import logging
import os
import pytest
import speechmatics.cli as cli
from .utils import path_to_test_resource
@pytest.mark.parametrize(
"args, values",
[
(
["transcribe"],
{
"ssl_mode": "regular",
"enable_partials": False,
"punctuation_permitted_marks": None,
},
),
(["-v", "transcribe"], {"verbose": 1}),
(["-vv", "transcribe"], {"verbose": 2}),
(["transcribe", "--ssl-mode=insecure"], {"ssl_mode": "insecure"}),
(["transcribe", "--ssl-mode=none"], {"ssl_mode": "none"}),
(["transcribe", "--additional-vocab"], {"additional_vocab": []}),
(
["transcribe", "--additional-vocab", "Speechmatics", "gnocchi"],
{"additional_vocab": ["Speechmatics", "gnocchi"]},
),
(
[
"transcribe",
"--additional-vocab",
"gnocchi:nokey,nochi",
"Speechmatics:speechmadticks",
],
{
"additional_vocab": [
{"content": "gnocchi", "sounds_like": ["nokey", "nochi"]},
{
"content": "Speechmatics",
"sounds_like": ["speechmadticks"]
},
]
},
),
(
["transcribe", "--punctuation-permitted-marks", ", ? ."],
{"punctuation_permitted_marks": ", ? ."},
),
(
["transcribe", "--punctuation-permitted-marks", ""],
{"punctuation_permitted_marks": ""}
),
(["transcribe", "--enable-partials"], {"enable_partials": True}),
(
["transcribe", "--speaker-change-token"],
{"speaker_change_token": True}
),
(["transcribe", "--n-best-limit=5"], {"n_best_limit": 5}),
],
)
def test_cli_arg_parse(args, values):
required_args = ["--url=example", "file"]
test_args = args + required_args
actual_values = vars(cli.parse_args(args=test_args))
for (key, val) in values.items():
assert actual_values[key] == val
def test_parse_additional_vocab(tmp_path):
vocab_file = tmp_path / "vocab.json"
vocab_file.write_text('["Speechmatics", "gnocchi"]')
assert cli.parse_additional_vocab(vocab_file) == \
["Speechmatics", "gnocchi"]
vocab_file.write_text('[{"content": "gnocchi", "sounds_like": ["nokey"]}]')
assert cli.parse_additional_vocab(vocab_file) == (
[{"content": "gnocchi", "sounds_like": ["nokey"]}]
)
vocab_file.write_text("[")
with pytest.raises(SystemExit):
cli.parse_additional_vocab(vocab_file)
@pytest.mark.parametrize(
"punctuation_permitted_marks, exp_value",
[
# the optional punctuation_permitted_marks arg isn't given
(None, None),
# an empty string is given to disable all punctuation
("", {"permitted_marks": []}),
# a single space is given to disable all punctuation
(" ", {"permitted_marks": []}),
# only commas are allowed
(",", {"permitted_marks": [","]}),
(" , ", {"permitted_marks": [","]}),
# several marks are allowed
(", . ! ?", {"permitted_marks": [",", ".", "!", "?"]}),
(" . ! ", {"permitted_marks": [".", "!"]}),
],
)
def test_get_transcription_config_punctuation_permitted_marks(
punctuation_permitted_marks, exp_value
):
args = collections.defaultdict(str)
args["punctuation_permitted_marks"] = punctuation_permitted_marks
config = cli.get_transcription_config(args)
assert config.punctuation_overrides == exp_value
@pytest.mark.parametrize(
"enable_partials, exp_value",
[
# the optional enable_partials arg isn't given
# so argparse sets it to False
(False, None),
# enable_partials arg was specified
(True, True),
# shouldn't happen, but just to be paranoid
(None, None),
],
)
def test_get_transcription_config_enable_partials(enable_partials, exp_value):
args = collections.defaultdict(str)
args["enable_partials"] = enable_partials
config = cli.get_transcription_config(args)
assert config.enable_partials == exp_value
def test_additional_vocab_item():
assert cli.additional_vocab_item("a") == "a"
assert cli.additional_vocab_item("a:") == {"content": "a"}
assert cli.additional_vocab_item("a:b,c") == {
"content": "a",
"sounds_like": ["b", "c"],
}
with pytest.raises(argparse.ArgumentTypeError):
cli.additional_vocab_item("")
with pytest.raises(argparse.ArgumentTypeError):
cli.additional_vocab_item("a:b:c")
def test_get_log_level():
assert cli.get_log_level(1) == logging.INFO
with pytest.raises(SystemExit):
cli.get_log_level(3)
def test_main_with_basic_options(mock_server):
args = [
"-vv",
"transcribe",
"--ssl-mode=insecure",
"--url",
mock_server.url,
path_to_test_resource("ch.wav"),
]
cli.main(vars(cli.parse_args(args)))
mock_server.wait_for_clean_disconnects()
assert mock_server.clients_connected_count == 1
assert mock_server.clients_disconnected_count == 1
assert mock_server.messages_received
assert mock_server.messages_sent
assert mock_server.connection_request.path == "/v2"
def test_main_with_all_options(mock_server, tmp_path):
vocab_file = tmp_path / "vocab.json"
vocab_file.write_text(
'["jabberwock", {"content": "brillig", "sounds_like": ["brillick"]}]'
)
chunk_size = 1024 * 8
audio_path = path_to_test_resource("ch.wav")
args = [
"-v",
"transcribe",
"--ssl-mode=insecure",
"--buffer-size=256",
"--debug",
"--url",
"wss://0.0.0.0:8765/v2",
"--lang=en",
"--output-locale=en-US",
"--additional-vocab",
"tumtum",
"borogoves:boreohgofes,borrowgoafs",
"--additional-vocab-file",
str(vocab_file),
"--enable-partials",
"--punctuation-permitted-marks",
"all",
"--punctuation-sensitivity",
"0.1",
"--diarization",
"none",
"--speaker-change-sensitivity",
"0.8",
"--speaker-change-token",
"--max-delay",
"5.0",
"--chunk-size",
str(chunk_size),
audio_path,
]
cli.main(vars(cli.parse_args(args)))
mock_server.wait_for_clean_disconnects()
assert mock_server.clients_connected_count == 1
assert mock_server.clients_disconnected_count == 1
assert mock_server.messages_received
assert mock_server.messages_sent
# Check that the StartRecognition message contains the correct fields
msg = mock_server.find_start_recognition_message()
print(msg)
assert msg["audio_format"]["type"] == "file"
assert len(msg["audio_format"]) == 1
assert msg["transcription_config"]["language"] == "en"
assert msg["transcription_config"]["output_locale"] == "en-US"
assert msg["transcription_config"]["additional_vocab"] == (
[
"jabberwock",
{"content": "brillig", "sounds_like": ["brillick"]},
"tumtum", {
"content": "borogoves", "sounds_like": [
"boreohgofes", "borrowgoafs"
]
},
]
)
assert mock_server.find_sent_messages_by_type("AddPartialTranscript")
assert msg["transcription_config"]["punctuation_overrides"]["permitted_marks"] == [ # noqa
"all"
]
assert msg["transcription_config"]["punctuation_overrides"]["sensitivity"] == 0.1 # noqa
assert msg["transcription_config"]["diarization"] == "none"
assert msg["transcription_config"]["max_delay"] == 5.0
assert msg["transcription_config"]["speaker_change_sensitivity"] == 0.8
# Check that the chunk size argument is respected
add_audio_messages = mock_server.find_add_audio_messages()
size_of_audio_file = os.stat(audio_path).st_size
expected_num_messages = size_of_audio_file / chunk_size
assert -1 <= (len(add_audio_messages) - expected_num_messages) <= 1
def test_add_printing_handlers_transcript_handler(mocker, capsys):
api = mocker.MagicMock()
transcripts = cli.Transcripts(text="", json=[])
cli.add_printing_handlers(api, transcripts)
assert not transcripts.text
assert not transcripts.json
out, err = capsys.readouterr()
assert not out
assert not err
assert api.add_event_handler.called
call_args_dict = {
i[0][0]: i[0][1] for i in api.add_event_handler.call_args_list
}
finals_msg_type = "AddTranscript"
assert finals_msg_type in call_args_dict
transcript_handler_cb_func = call_args_dict[finals_msg_type]
transcript = ""
msg_empty_transcript = {
"message": "AddTranscript",
"results": [],
"metadata": {
"start_time": 58.920005798339844,
"end_time": 60.0000057220459,
"transcript": transcript,
},
"format": "2.4",
}
transcript_handler_cb_func(msg_empty_transcript)
assert transcripts.text == transcript
assert transcripts.json == [msg_empty_transcript]
out, err = capsys.readouterr()
assert not out, "Don't print a newline when the transcript is empty"
assert not err
transcript = "Howdy "
msg_single_word_transcript = copy.deepcopy(msg_empty_transcript)
msg_single_word_transcript["metadata"]["transcript"] = transcript
msg_single_word_transcript["results"].append(
{
"type": "word",
"start_time": 0.08999999612569809,
"end_time": 0.29999998211860657,
"alternatives": [
{
"confidence": 1.0, "content": transcript.strip(),
"language": "en"
}
],
}
)
transcript_handler_cb_func(msg_single_word_transcript)
assert transcripts.text == transcript
assert transcripts.json == \
[msg_empty_transcript, msg_single_word_transcript]
out, err = capsys.readouterr()
assert out == transcript + "\n"
assert not err
transcript_handler_cb_func(msg_empty_transcript)
transcript_handler_cb_func(msg_single_word_transcript)
transcript_handler_cb_func(msg_empty_transcript)
assert transcripts.text == transcript * 2
assert transcripts.json == [
msg_empty_transcript,
msg_single_word_transcript,
msg_empty_transcript,
msg_single_word_transcript,
msg_empty_transcript,
]
out, err = capsys.readouterr()
assert out == transcript + "\n"
assert not err
TRANSCRIPT_TXT_WITH_SC = "Hey\nHello"
TRANSCRIPT_WITH_SC = {
"message": "AddTranscript",
"results": [
{
"type": "word",
"start_time": 0.08999999612569809,
"end_time": 0.29999998211860657,
"alternatives": [
{"confidence": 1.0, "content": "Hey", "language": "en"}
],
},
{
"type": "speaker_change",
"start_time": 0.08999999612569809,
"end_time": 0.29999998211860657,
"score": 1,
},
{
"type": "word",
"start_time": 0.08999999612569809,
"end_time": 0.29999998211860657,
"alternatives": [
{"confidence": 1.0, "content": "Hello", "language": "en"}
],
},
],
"metadata": {
"start_time": 58.920005798339844,
"end_time": 60.0000057220459,
"transcript": TRANSCRIPT_TXT_WITH_SC,
},
"format": "2.4",
}
def check_printing_handlers(
mocker, capsys, transcript, expected_transcript_txt,
speaker_change_token
):
api = mocker.MagicMock()
transcripts = cli.Transcripts(text="", json=[])
cli.add_printing_handlers(
api, transcripts, speaker_change_token=speaker_change_token
)
assert not transcripts.text
assert not transcripts.json
out, err = capsys.readouterr()
assert not out
assert not err
assert api.add_event_handler.called
call_args_dict = {
i[0][0]: i[0][1] for i in api.add_event_handler.call_args_list
}
finals_msg_type = "AddTranscript"
assert finals_msg_type in call_args_dict
transcript_handler_cb_func = call_args_dict[finals_msg_type]
transcript_handler_cb_func(transcript)
assert transcripts.text == expected_transcript_txt
assert transcripts.json == [transcript]
out, err = capsys.readouterr()
assert out == expected_transcript_txt + "\n"
assert not err
def test_add_printing_handlers_with_speaker_change_token(mocker, capsys):
expected_transcript = "Hey\n<sc>\nHello"
check_printing_handlers(
mocker,
capsys,
TRANSCRIPT_WITH_SC,
expected_transcript,
speaker_change_token=True,
)
def test_add_printing_handlers_with_speaker_change_no_token(mocker, capsys):
expected_transcript = "Hey\nHello"
check_printing_handlers(
mocker,
capsys,
TRANSCRIPT_WITH_SC,
expected_transcript,
speaker_change_token=False,
)