File size: 22,780 Bytes
cbc00ce | 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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | # -*- coding: utf-8 -*-
# Copyright (c) Alibaba, Inc. and its affiliates.
# mypy: disable-error-code="annotation-unchecked"
import json
import os
import threading
import time
import uuid
from http import HTTPStatus
from queue import Queue
from threading import Timer
from typing import Any, Dict, List, Union
from dashscope.api_entities.dashscope_response import RecognitionResponse
from dashscope.client.base_api import BaseApi
from dashscope.common.constants import ApiProtocol
from dashscope.common.error import (
InputDataRequired,
InputRequired,
InvalidParameter,
InvalidTask,
ModelRequired,
)
from dashscope.common.logging import logger
from dashscope.common.utils import _get_task_group_and_task
from dashscope.protocol.websocket import WebsocketStreamingMode
class RecognitionResult(RecognitionResponse):
"""The result set of speech recognition, including the single-sentence
recognition result returned by the callback mode, and all recognition
results in a synchronized manner.
"""
def __init__(
self,
response: RecognitionResponse,
sentences: List[Any] = None,
usages: List[Any] = None,
):
self.status_code = response.status_code
self.request_id = response.request_id
self.code = response.code
self.message = response.message
self.usages = usages
if sentences is not None and len(sentences) > 0:
self.output = {"sentence": sentences}
else:
self.output = response.output
if (
self.usages is not None
and len(
self.usages,
)
> 0
and "usage" in self.usages[-1]
):
self.usage = self.usages[-1]["usage"]
else:
self.usage = None
def __str__(self):
return json.dumps(
RecognitionResponse.from_api_response(self),
ensure_ascii=False,
)
def get_sentence(self) -> Union[Dict[str, Any], List[Any]]:
"""The result of speech recognition."""
if self.output and "sentence" in self.output:
return self.output["sentence"]
else:
return None # type: ignore[return-value]
def get_request_id(self) -> str:
"""The request_id of speech recognition."""
return self.request_id
def get_usage(self, sentence: Dict[str, Any]) -> Dict[str, Any]:
"""Get billing for the input sentence."""
if self.usages is not None:
if (
sentence is not None
and "end_time" in sentence
and sentence["end_time"] is not None
):
for usage in self.usages:
if usage["end_time"] == sentence["end_time"]:
return usage["usage"]
return None # type: ignore[return-value]
@staticmethod
def is_sentence_end(sentence: Dict[str, Any]) -> bool:
"""Determine whether the speech recognition result is the end of a sentence. # noqa: E501
This is a static method.
"""
# pylint: disable=simplifiable-if-statement
if (
sentence is not None
and "end_time" in sentence
and sentence["end_time"] is not None
):
return True
else:
return False
class RecognitionCallback:
"""An interface that defines callback methods for getting speech recognition results. # noqa E501 # pylint: disable=line-too-long
Derive from this class and implement its function to provide your own data.
"""
def on_open(self) -> None:
pass
def on_complete(self) -> None:
pass
def on_error(self, result: RecognitionResult) -> None:
pass
def on_close(self) -> None:
pass
def on_event(self, result: RecognitionResult) -> None:
pass
class Recognition(BaseApi):
"""Speech recognition interface.
Args:
model (str): The requested model_id.
callback (RecognitionCallback): A callback that returns
speech recognition results.
format (str): The input audio format for speech recognition.
sample_rate (int): The input audio sample rate for speech recognition.
workspace (str): The dashscope workspace id.
**kwargs:
phrase_id (list, `optional`): The ID of phrase.
disfluency_removal_enabled(bool, `optional`): Filter mood words,
turned off by default.
diarization_enabled (bool, `optional`): Speech auto diarization,
turned off by default.
speaker_count (int, `optional`): The number of speakers.
timestamp_alignment_enabled (bool, `optional`): Timestamp-alignment
calibration, turned off by default.
special_word_filter(str, `optional`): Sensitive word filter.
audio_event_detection_enabled(bool, `optional`):
Audio event detection, turned off by default.
Raises:
InputRequired: Input is required.
"""
SILENCE_TIMEOUT_S = 23
def __init__(
self,
model: str,
callback: RecognitionCallback,
format: str, # pylint: disable=redefined-builtin
sample_rate: int,
workspace: str = None,
**kwargs,
):
if model is None:
raise ModelRequired("Model is required!")
if format is None:
raise InputRequired("format is required!")
if sample_rate is None:
raise InputRequired("sample_rate is required!")
self.model = model
self.format = format
self.sample_rate = sample_rate
# continuous recognition with start() or once recognition with call()
self._recognition_once = False
self._callback = callback
self._running = False
self._stream_data = Queue()
self._worker = None
self._silence_timer = None
self._kwargs = kwargs
self._workspace = workspace
self._start_stream_timestamp = -1
self._first_package_timestamp = -1
self._stop_stream_timestamp = -1
self._on_complete_timestamp = -1
self.request_id_confirmed = False
self.last_request_id = uuid.uuid4().hex
def __del__(self):
if self._running:
self._running = False
self._stream_data = Queue()
if self._worker is not None and self._worker.is_alive():
self._worker.join()
if (
self._silence_timer is not None
and self._silence_timer.is_alive() # noqa E501
):
self._silence_timer.cancel()
self._silence_timer = None
if self._callback:
self._callback.on_close()
def __receive_worker(self):
"""Asynchronously, initiate a real-time speech recognition request and
obtain the result for parsing.
"""
responses = self.__launch_request()
for part in responses: # pylint: disable=R1702
if part.status_code == HTTPStatus.OK:
if len(part.output) == 0 or (
"finished" in part.output
# pylint: disable=singleton-comparison
and part.output["finished"] == True # noqa: E712
):
self._on_complete_timestamp = time.time() * 1000
logger.debug(
"last package delay %s",
self.get_last_package_delay(),
)
self._callback.on_complete()
else:
usage: Dict[str, Any] = None
usages: List[Any] = None
if "sentence" in part.output:
if (
"text" in part.output["sentence"]
and part.output["sentence"]["text"] != ""
):
if self._first_package_timestamp < 0:
self._first_package_timestamp = (
time.time() * 1000
)
logger.debug(
"first package delay %s",
self.get_first_package_delay(),
)
sentence = part.output["sentence"]
if (
"heartbeat" in sentence
# pylint: disable=singleton-comparison
and sentence["heartbeat"] == True # noqa: E712
):
logger.debug("recv heartbeat")
continue
logger.debug(
"Recv Result [rid:%s]:%s, isEnd: %s",
part.request_id,
sentence,
RecognitionResult.is_sentence_end(sentence),
)
if part.usage is not None:
usage = {
"end_time": part.output["sentence"][
"end_time"
],
"usage": part.usage,
}
usages = [usage]
if (
self.request_id_confirmed is False
and part.request_id is not None
):
self.last_request_id = part.request_id
self.request_id_confirmed = True
self._callback.on_event(
RecognitionResult(
RecognitionResponse.from_api_response(part),
usages=usages,
),
)
else:
self._running = False
self._stream_data = Queue()
self._callback.on_error(
RecognitionResult(
RecognitionResponse.from_api_response(part),
),
)
self._callback.on_close()
break
def __launch_request(self):
"""Initiate real-time speech recognition requests."""
resources_list: list = []
if self._phrase is not None and len(self._phrase) > 0:
item = {"resource_id": self._phrase, "resource_type": "asr_phrase"}
resources_list.append(item)
if len(resources_list) > 0:
self._kwargs["resources"] = resources_list
self._tidy_kwargs()
task_name, _ = _get_task_group_and_task(__name__)
responses = super().call(
model=self.model,
task_group="audio",
task=task_name,
function="recognition",
input=self._input_stream_cycle(),
api_protocol=ApiProtocol.WEBSOCKET,
ws_stream_mode=WebsocketStreamingMode.DUPLEX,
is_binary_input=True,
sample_rate=self.sample_rate,
format=self.format,
stream=True,
workspace=self._workspace,
pre_task_id=self.last_request_id,
**self._kwargs,
)
return responses
def start(self, phrase_id: str = None, **kwargs):
"""Real-time speech recognition in asynchronous mode.
Please call 'stop()' after you have completed recognition.
Args:
phrase_id (str, `optional`): The ID of phrase.
**kwargs:
disfluency_removal_enabled(bool, `optional`):
Filter mood words, turned off by default.
diarization_enabled (bool, `optional`):
Speech auto diarization, turned off by default.
speaker_count (int, `optional`): The number of speakers.
timestamp_alignment_enabled (bool, `optional`):
Timestamp-alignment calibration, turned off by default.
special_word_filter(str, `optional`): Sensitive word filter.
audio_event_detection_enabled(bool, `optional`):
Audio event detection, turned off by default.
Raises:
InvalidParameter: This interface cannot be called again
if it has already been started.
InvalidTask: Task create failed.
"""
assert (
self._callback is not None
), "Please set the callback to get the speech recognition result." # noqa E501
if self._running:
raise InvalidParameter("Speech recognition has started.")
self._start_stream_timestamp = -1
self._first_package_timestamp = -1
self._stop_stream_timestamp = -1
self._on_complete_timestamp = -1
self._phrase = phrase_id
self._kwargs.update(**kwargs)
self._recognition_once = False
self._worker = threading.Thread(target=self.__receive_worker)
self._worker.start()
if self._worker.is_alive():
self._running = True
self._callback.on_open()
# If audio data is not received for 23 seconds, the timeout exits
self._silence_timer = Timer(
Recognition.SILENCE_TIMEOUT_S,
self._silence_stop_timer,
)
self._silence_timer.start()
else:
self._running = False
raise InvalidTask("Invalid task, task create failed.")
# pylint: disable=R1702,too-many-branches,too-many-statements
def call( # type: ignore[override] # noqa: E501
self,
file: str,
phrase_id: str = None,
**kwargs,
) -> RecognitionResult:
"""Real-time speech recognition in synchronous mode.
Args:
file (str): The path to the local audio file.
phrase_id (str, `optional`): The ID of phrase.
**kwargs:
disfluency_removal_enabled(bool, `optional`):
Filter mood words, turned off by default.
diarization_enabled (bool, `optional`):
Speech auto diarization, turned off by default.
speaker_count (int, `optional`): The number of speakers.
timestamp_alignment_enabled (bool, `optional`):
Timestamp-alignment calibration, turned off by default.
special_word_filter(str, `optional`): Sensitive word filter.
audio_event_detection_enabled(bool, `optional`):
Audio event detection, turned off by default.
Raises:
InvalidParameter: This interface cannot be called again
if it has already been started.
InputDataRequired: The supplied file was empty.
Returns:
RecognitionResult: The result of speech recognition.
"""
self._start_stream_timestamp = time.time() * 1000
if self._running:
raise InvalidParameter("Speech recognition has been called.")
if os.path.exists(file):
if os.path.isdir(file):
raise IsADirectoryError("Is a directory: " + file)
else:
raise FileNotFoundError("No such file or directory: " + file)
self._recognition_once = True
self._stream_data = Queue()
self._phrase = phrase_id
self._kwargs.update(**kwargs)
error_flag: bool = False
sentences: List[Any] = []
usages: List[Any] = []
response: RecognitionResponse = None
result: RecognitionResult = None
try:
audio_data: bytes = None
# pylint: disable=consider-using-with
f = open(file, "rb")
if os.path.getsize(file):
while True:
audio_data = f.read(12800)
if not audio_data:
break
self._stream_data.put(
audio_data,
) # pylint: disable=no-else-break
else:
raise InputDataRequired(
"The supplied file was empty (zero bytes long)",
)
f.close()
self._stop_stream_timestamp = time.time() * 1000
except Exception as e:
logger.error(e)
raise e
if not self._stream_data.empty():
self._running = True
responses = self.__launch_request()
for part in responses:
if part.status_code == HTTPStatus.OK:
if "sentence" in part.output:
if (
"text" in part.output["sentence"]
and part.output["sentence"]["text"] != ""
):
if self._first_package_timestamp < 0:
self._first_package_timestamp = (
time.time() * 1000
)
logger.debug(
"first package delay %s",
self._first_package_timestamp
- self._start_stream_timestamp,
)
sentence = part.output["sentence"]
logger.debug(
"Recv Result [rid:%s]:%s, isEnd: %s",
part.request_id,
sentence,
RecognitionResult.is_sentence_end(sentence),
)
if RecognitionResult.is_sentence_end(sentence):
sentences.append(sentence)
if part.usage is not None:
usage = {
"end_time": part.output["sentence"][
"end_time"
],
"usage": part.usage,
}
usages.append(usage)
response = RecognitionResponse.from_api_response(part)
else:
response = RecognitionResponse.from_api_response(part)
logger.error(response)
error_flag = True
break
self._on_complete_timestamp = time.time() * 1000
logger.debug(
"last package delay %s",
self.get_last_package_delay(),
)
if error_flag:
result = RecognitionResult(response)
else:
result = RecognitionResult(response, sentences, usages)
self._stream_data = Queue()
self._recognition_once = False
self._running = False
return result
def stop(self):
"""End asynchronous speech recognition.
Raises:
InvalidParameter: Cannot stop an uninitiated recognition.
"""
if self._running is False:
raise InvalidParameter("Speech recognition has stopped.")
self._stop_stream_timestamp = time.time() * 1000
self._running = False
if self._worker is not None and self._worker.is_alive():
self._worker.join()
self._stream_data = Queue()
if self._silence_timer is not None and self._silence_timer.is_alive():
self._silence_timer.cancel()
self._silence_timer = None
if self._callback:
self._callback.on_close()
def send_audio_frame(self, buffer: bytes):
"""Push speech recognition.
Raises:
InvalidParameter: Cannot send data to an uninitiated recognition.
"""
if self._running is False:
raise InvalidParameter("Speech recognition has stopped.")
if self._start_stream_timestamp < 0:
self._start_stream_timestamp = time.time() * 1000
logger.debug("send_audio_frame: %s", len(buffer))
self._stream_data.put(buffer)
def _tidy_kwargs(self):
for k in self._kwargs.copy():
if self._kwargs[k] is None:
self._kwargs.pop(k, None)
def _input_stream_cycle(self):
while self._running:
while self._stream_data.empty():
if self._running:
time.sleep(0.01)
continue
break
# Reset silence_timer when getting stream.
if (
self._silence_timer is not None
and self._silence_timer.is_alive() # noqa E501
):
self._silence_timer.cancel()
self._silence_timer = Timer(
Recognition.SILENCE_TIMEOUT_S,
self._silence_stop_timer,
)
self._silence_timer.start()
while not self._stream_data.empty():
frame = self._stream_data.get()
yield bytes(frame)
if self._recognition_once:
self._running = False
# drain all audio data when invoking stop().
if self._recognition_once is False:
while not self._stream_data.empty():
frame = self._stream_data.get()
yield bytes(frame)
def _silence_stop_timer(self):
"""If audio data is not received for a long time, exit worker."""
self._running = False
if self._silence_timer is not None and self._silence_timer.is_alive():
self._silence_timer.cancel()
self._silence_timer = None
if self._worker is not None and self._worker.is_alive():
self._worker.join()
self._stream_data = Queue()
def get_first_package_delay(self):
"""First Package Delay is the time between start sending audio and receive first words package""" # noqa: E501 # pylint: disable=line-too-long
return self._first_package_timestamp - self._start_stream_timestamp
def get_last_package_delay(self):
"""Last Package Delay is the time between stop sending audio and receive last words package""" # noqa: E501 # pylint: disable=line-too-long
return self._on_complete_timestamp - self._stop_stream_timestamp
# 获取上一个任务的taskId
def get_last_request_id(self):
return self.last_request_id
|