asxasx
This commit is contained in:
Alireza Jahanshahlou 2025-10-21 13:17:53 +03:30
parent 6aedb3c3f5
commit 4ebb4bc410
52 changed files with 1303 additions and 112 deletions

BIN
Build Tools.docx Normal file

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 189 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 119 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

View file

@ -45,10 +45,10 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28", "Version": "2019-02-28",
} }
# 构造规范化的请求字符串 # Construct a normalized request string
query_string = AccessToken._encode_dict(parameters) query_string = AccessToken._encode_dict(parameters)
# print('规范化的请求字符串: %s' % query_string) # print('Normalized request string: %s' % query_string)
# 构造待签名字符串 # Construct a string to be signed
string_to_sign = ( string_to_sign = (
"GET" "GET"
+ "&" + "&"
@ -56,25 +56,25 @@ class AccessToken:
+ "&" + "&"
+ AccessToken._encode_text(query_string) + AccessToken._encode_text(query_string)
) )
# print('待签名的字符串: %s' % string_to_sign) # print('String to be signed: %s' % string_to_sign)
# 计算签名 # Compute signature
secreted_string = hmac.new( secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"), bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"), bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1, hashlib.sha1,
).digest() ).digest()
signature = base64.b64encode(secreted_string) signature = base64.b64encode(secreted_string)
# print('签名: %s' % signature) # print('sign: %s' % signature)
# 进行URL编码 # perform url encoding
signature = AccessToken._encode_text(signature) signature = AccessToken._encode_text(signature)
# print('URL编码后的签名: %s' % signature) # print('Url encoded signature: %s' % signature)
# 调用服务 # Call service
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % ( full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature, signature,
query_string, query_string,
) )
# print('url: %s' % full_url) # print('url: %s' % full_url)
# 提交HTTP GET请求 # Submit HTTP GET request
response = requests.get(full_url) response = requests.get(full_url)
if response.ok: if response.ok:
root_obj = response.json() root_obj = response.json()
@ -91,8 +91,8 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool): def __init__(self, config: dict, delete_audio_file: bool):
super().__init__() super().__init__()
self.interface_type = InterfaceType.NON_STREAM self.interface_type = InterfaceType.NON_STREAM
"""阿里云ASR初始化""" """Alibaba Cloud asr initialization"""
# 新增空值判断逻辑 # Added null value judgment logic
self.access_key_id = config.get("access_key_id") self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret") self.access_key_secret = config.get("access_key_secret")
@ -105,27 +105,27 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
if self.access_key_id and self.access_key_secret: if self.access_key_id and self.access_key_secret:
# 使用密钥对生成临时token # Generate temporary token using key pair
self._refresh_token() self._refresh_token()
else: else:
# 直接使用预生成的长期token # Use pre-generated long-term tokens directly
self.token = config.get("token") self.token = config.get("token")
self.expire_time = None self.expire_time = None
# 确保输出目录存在 # Make sure the output directory exists
os.makedirs(self.output_dir, exist_ok=True) os.makedirs(self.output_dir, exist_ok=True)
def _refresh_token(self): def _refresh_token(self):
"""刷新Token并记录过期时间""" """Refresh the token and record the expiration time"""
if self.access_key_id and self.access_key_secret: if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token( self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret self.access_key_id, self.access_key_secret
) )
if not expire_time_str: if not expire_time_str:
raise ValueError("无法获取有效的Token过期时间") raise ValueError("Unable to obtain valid token expiration time")
try: try:
# 统一转换为字符串处理 # Unified conversion to string processingnversion to string processing
expire_str = str(expire_time_str).strip() expire_str = str(expire_time_str).strip()
if expire_str.isdigit(): if expire_str.isdigit():
@ -134,28 +134,28 @@ class ASRProvider(ASRProviderBase):
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ") expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60 self.expire_time = expire_time.timestamp() - 60
except Exception as e: except Exception as e:
raise ValueError(f"无效的过期时间格式: {expire_str}") from e raise ValueError(f"Invalid expiration time format: {expire_str}") from e
else: else:
self.expire_time = None self.expire_time = None
if not self.token: if not self.token:
raise ValueError("无法获取有效的访问Token") raise ValueError("Unable to obtain valid access token")
def _is_token_expired(self): def _is_token_expired(self):
"""检查Token是否过期""" """Check if the token has expired"""
if not self.expire_time: if not self.expire_time:
return False # 长期Token不过期 return False # Long-term tokens do not expire
# 新增调试日志 # Add debug log
# current_time = time.time() # current_time = time.time()
# remaining = self.expire_time - current_time # remaining = self.expire_time - current_time
# print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | " # print(f"Token expiration check: current time {datetime.fromtimestamp(current_time)} | "
# f"过期时间 {datetime.fromtimestamp(self.expire_time)} | " # f"Expiration time {datetime.fromtimestamp(self.expire_time)} | "
# f"剩余 {remaining:.2f}秒") # f"Remaining {remaining:.2f}Second")
return time.time() > self.expire_time return time.time() > self.expire_time
def _construct_request_url(self) -> str: def _construct_request_url(self) -> str:
"""构造请求URL,包含参数""" """Construct the request url, including parameters"""
request = f"{self.base_url}?appkey={self.app_key}" request = f"{self.base_url}?appkey={self.app_key}"
request += f"&format={self.format}" request += f"&format={self.format}"
request += f"&sample_rate={self.sample_rate}" request += f"&sample_rate={self.sample_rate}"
@ -165,16 +165,16 @@ class ASRProvider(ASRProviderBase):
return request return request
async def _send_request(self, pcm_data: bytes) -> Optional[str]: async def _send_request(self, pcm_data: bytes) -> Optional[str]:
"""发送请求到阿里云ASR服务""" """Send a request to Alibaba Cloud ASR service"""
try: try:
# 设置HTTP头 # Set http header
headers = { headers = {
"X-NLS-Token": self.token, "X-NLS-Token": self.token,
"Content-type": "application/octet-stream", "Content-type": "application/octet-stream",
"Content-Length": str(len(pcm_data)), "Content-Length": str(len(pcm_data)),
} }
# 创建连接并发送请求 # Create connection and send request
conn = http.client.HTTPSConnection(self.host) conn = http.client.HTTPSConnection(self.host)
request_url = self._construct_request_url() request_url = self._construct_request_url()
@ -186,56 +186,56 @@ class ASRProvider(ASRProviderBase):
), ),
) )
# 获取响应 # Get response
response = await loop.run_in_executor(None, conn.getresponse) response = await loop.run_in_executor(None, conn.getresponse)
body = await loop.run_in_executor(None, response.read) body = await loop.run_in_executor(None, response.read)
conn.close() conn.close()
# 解析响应 # Parse response
try: try:
body_json = json.loads(body) body_json = json.loads(body)
status = body_json.get("status") status = body_json.get("status")
if status == 20000000: if status == 20000000:
result = body_json.get("result", "") result = body_json.get("result", "")
logger.bind(tag=TAG).debug(f"ASR结果: {result}") logger.bind(tag=TAG).debug(f"Asr results: {result}")
return result return result
else: else:
logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}") logger.bind(tag=TAG).error(f"Asr failed, status code: {status}")
return None return None
except ValueError: except ValueError:
logger.bind(tag=TAG).error("响应不是JSON格式") logger.bind(tag=TAG).error("Response is not in json format")
return None return None
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True) logger.bind(tag=TAG).error(f"Asr request failed: {e}", exc_info=True)
return None return None
async def speech_to_text( async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本""" """Convert voice data to text"""
if self._is_token_expired(): if self._is_token_expired():
logger.warning("Token已过期,正在自动刷新...") logger.warning("Token has expired and is being refreshed automatically...")
self._refresh_token() self._refresh_token()
file_path = None file_path = None
try: try:
# 解码Opus为PCM # Decode opus to pcm
if audio_format == "pcm": if audio_format == "pcm":
pcm_data = opus_data pcm_data = opus_data
else: else:
pcm_data = self.decode_opus(opus_data) pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data) combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件 # Determine whether to save as wav fileether to save as wav file
if self.delete_audio_file: if self.delete_audio_file:
pass pass
else: else:
file_path = self.save_audio_to_file(pcm_data, session_id) file_path = self.save_audio_to_file(pcm_data, session_id)
# 发送请求并获取文本 # Send request and get text
text = await self._send_request(combined_pcm_data) text = await self._send_request(combined_pcm_data)
if text: if text:
@ -244,5 +244,5 @@ class ASRProvider(ASRProviderBase):
return "", file_path return "", file_path
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True) logger.bind(tag=TAG).error(f"Voice recognition failed: {e}", exc_info=True)
return "", file_path return "", file_path

View file

@ -76,19 +76,19 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None self.asr_ws = None
self.forward_task = None self.forward_task = None
self.is_processing = False self.is_processing = False
self.server_ready = False # 服务器准备状态 self.server_ready = False # Server readiness status
# 基础配置 # Basic configuration
self.access_key_id = config.get("access_key_id") self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret") self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey") self.appkey = config.get("appkey")
self.token = config.get("token") self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com") self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
# 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议 # If the configured internal network address (including internal.aliyuncs.com) is configured, the ws protocol is used. The default is wss protocol.
if "-internal." in self.host: if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1" self.ws_url = f"ws://{self.host}/ws/v1"
else: else:
# 默认使用wss协议 # Use wss protocol by default
self.ws_url = f"wss://{self.host}/ws/v1" self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence") self.max_sentence_silence = config.get("max_sentence_silence")
@ -96,17 +96,17 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file self.delete_audio_file = delete_audio_file
self.expire_time = None self.expire_time = None
# Token管理 # Token management
if self.access_key_id and self.access_key_secret: if self.access_key_id and self.access_key_secret:
self._refresh_token() self._refresh_token()
elif not self.token: elif not self.token:
raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token") raise ValueError("Access key id+access key secret or token must be provided directly")
def _refresh_token(self): def _refresh_token(self):
"""刷新Token""" """Refresh token"""
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret) self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
if not self.token: if not self.token:
raise ValueError("无法获取有效的访问Token") raise ValueError("Unable to obtain valid access token")
try: try:
expire_str = str(expire_time_str).strip() expire_str = str(expire_time_str).strip()
@ -119,30 +119,30 @@ class ASRProvider(ASRProviderBase):
self.expire_time = None self.expire_time = None
def _is_token_expired(self): def _is_token_expired(self):
"""检查Token是否过期""" """Check if the token has expired"""
return self.expire_time and time.time() > self.expire_time return self.expire_time and time.time() > self.expire_time
async def open_audio_channels(self, conn): async def open_audio_channels(self, conn):
await super().open_audio_channels(conn) await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice): async def receive_audio(self, conn, audio, audio_have_voice):
# 初始化音频缓存 # Initialize audio cache
if not hasattr(conn, 'asr_audio_for_voiceprint'): if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = [] conn.asr_audio_for_voiceprint = []
# 存储音频数据 # Store audio data
if audio: if audio:
conn.asr_audio_for_voiceprint.append(audio) conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio) conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:] conn.asr_audio = conn.asr_audio[-10:]
# 只在有声音且没有连接时建立连接 # Only establish connection when there is sound and no connection
if audio_have_voice and not self.is_processing: if audio_have_voice and not self.is_processing:
try: try:
await self._start_recognition(conn) await self._start_recognition(conn)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}") logger.bind(tag=TAG).error(f"Start recognition failed: {str(e)}")
await self._cleanup(conn) await self._cleanup(conn)
return return
@ -151,15 +151,15 @@ class ASRProvider(ASRProviderBase):
pcm_frame = self.decoder.decode(audio, 960) pcm_frame = self.decoder.decode(audio, 960)
await self.asr_ws.send(pcm_frame) await self.asr_ws.send(pcm_frame)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}") logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup(conn) await self._cleanup(conn)
async def _start_recognition(self, conn): async def _start_recognition(self, conn):
"""开始识别会话""" """Start recognition session"""
if self._is_token_expired(): if self._is_token_expired():
self._refresh_token() self._refresh_token()
# 建立连接 # Establish connection
headers = {"X-NLS-Token": self.token} headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect( self.asr_ws = await websockets.connect(
self.ws_url, self.ws_url,
@ -171,10 +171,10 @@ class ASRProvider(ASRProviderBase):
) )
self.is_processing = True self.is_processing = True
self.server_ready = False # 重置服务器准备状态 self.server_ready = False # Reset server readiness status
self.forward_task = asyncio.create_task(self._forward_results(conn)) self.forward_task = asyncio.create_task(self._forward_results(conn))
# 发送开始请求 # Send start request
start_request = { start_request = {
"header": { "header": {
"namespace": "SpeechTranscriber", "namespace": "SpeechTranscriber",
@ -196,10 +196,10 @@ class ASRProvider(ASRProviderBase):
} }
} }
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False)) await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
logger.bind(tag=TAG).info("已发送开始请求,等待服务器准备...") logger.bind(tag=TAG).info("Start request sent, waiting for server to prepare...")
async def _forward_results(self, conn): async def _forward_results(self, conn):
"""转发识别结果""" """Forward recognition results"""
try: try:
while self.asr_ws and not conn.stop_event.is_set(): while self.asr_ws and not conn.stop_event.is_set():
try: try:
@ -212,51 +212,51 @@ class ASRProvider(ASRProviderBase):
status = header.get("status", 0) status = header.get("status", 0)
if status != 20000000: if status != 20000000:
if status in [40000004, 40010004]: # 连接超时或客户端断开 if status in [40000004, 40010004]: # Connection timed out or client disconnected
logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}") logger.bind(tag=TAG).warning(f"Connection problem, status code: {status}")
break break
elif status in [40270002, 40270003]: # 音频问题 elif status in [40270002, 40270003]: # Audio issues
logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}") logger.bind(tag=TAG).warning(f"Audio processing issues, status codes: {status}")
continue continue
else: else:
logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}") logger.bind(tag=TAG).error(f"Recognition error, status code: {status}, 消息: {header.get('status_text', '')}")
continue continue
# 收到TranscriptionStarted表示服务器准备好接收音频数据 # Receiving transcription started indicates that the server is ready to receive audio data
if message_name == "TranscriptionStarted": if message_name == "TranscriptionStarted":
self.server_ready = True self.server_ready = True
logger.bind(tag=TAG).info("服务器已准备,开始发送缓存音频...") logger.bind(tag=TAG).info("The server is ready to start sending cached audio...")
# 发送缓存音频 # Send buffered audio
if conn.asr_audio: if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]: for cached_audio in conn.asr_audio[-10:]:
try: try:
pcm_frame = self.decoder.decode(cached_audio, 960) pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame) await self.asr_ws.send(pcm_frame)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}") logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break break
continue continue
if message_name == "TranscriptionResultChanged": if message_name == "TranscriptionResultChanged":
# 中间结果 # intermediate results
text = payload.get("result", "") text = payload.get("result", "")
if text: if text:
self.text = text self.text = text
elif message_name == "SentenceEnd": elif message_name == "SentenceEnd":
# 最终结果 # final result
text = payload.get("result", "") text = payload.get("result", "")
if text: if text:
self.text = text self.text = text
conn.reset_vad_states() conn.reset_vad_states()
# 传递缓存的音频数据 # Pass cached audio dataed audio data
audio_data = getattr(conn, 'asr_audio_for_voiceprint', []) audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data) await self.handle_voice_stop(conn, audio_data)
# 清空缓存 # Clear cache
conn.asr_audio_for_voiceprint = [] conn.asr_audio_for_voiceprint = []
break break
elif message_name == "TranscriptionCompleted": elif message_name == "TranscriptionCompleted":
# 识别完成 # Recognition completed
self.is_processing = False self.is_processing = False
break break
@ -265,26 +265,26 @@ class ASRProvider(ASRProviderBase):
except websockets.exceptions.ConnectionClosed: except websockets.exceptions.ConnectionClosed:
break break
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}") logger.bind(tag=TAG).error(f"Processing result failed: {str(e)}")
break break
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}") logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally: finally:
await self._cleanup(conn) await self._cleanup(conn)
async def _cleanup(self, conn): async def _cleanup(self, conn):
"""清理资源""" """Clean up resources"""
logger.bind(tag=TAG).info(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}") logger.bind(tag=TAG).info(f"Start asr session cleanup | Current status: processing={self.is_processing}, server_ready={self.server_ready}")
# 清理连接的音频缓存 # Clear connected audio cache
if conn and hasattr(conn, 'asr_audio_for_voiceprint'): if conn and hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = [] conn.asr_audio_for_voiceprint = []
# 判断是否需要发送终止请求 # Determine whether a termination request needs to be sent
should_stop = self.is_processing or self.server_ready should_stop = self.is_processing or self.server_ready
# 发送停止识别请求 # Send stop recognition request
if self.asr_ws and should_stop: if self.asr_ws and should_stop:
try: try:
stop_msg = { stop_msg = {
@ -297,47 +297,47 @@ class ASRProvider(ASRProviderBase):
"appkey": self.appkey "appkey": self.appkey
} }
} }
logger.bind(tag=TAG).info("正在发送ASR终止请求") logger.bind(tag=TAG).info("Sending asr termination request")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False)) await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
await asyncio.sleep(0.1) await asyncio.sleep(0.1)
logger.bind(tag=TAG).info("ASR终止请求已发送") logger.bind(tag=TAG).info("Asr termination request sent")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"ASR终止请求发送失败: {e}") logger.bind(tag=TAG).error(f"Asr termination request failed to send: {e}")
# 状态重置(在终止请求发送后) # Status reset (after termination request sent)
self.is_processing = False self.is_processing = False
self.server_ready = False self.server_ready = False
logger.bind(tag=TAG).info("ASR状态已重置") logger.bind(tag=TAG).info("Asr status has been reset")
# 清理任务 # Cleanup tasks
if self.forward_task and not self.forward_task.done(): if self.forward_task and not self.forward_task.done():
self.forward_task.cancel() self.forward_task.cancel()
try: try:
await asyncio.wait_for(self.forward_task, timeout=1.0) await asyncio.wait_for(self.forward_task, timeout=1.0)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).debug(f"forward_task取消异常: {e}") logger.bind(tag=TAG).debug(f"Forward task cancellation exception: {e}")
finally: finally:
self.forward_task = None self.forward_task = None
# 关闭连接 # close connection
if self.asr_ws: if self.asr_ws:
try: try:
logger.bind(tag=TAG).debug("正在关闭WebSocket连接") logger.bind(tag=TAG).debug("Closing web socket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0) await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
logger.bind(tag=TAG).debug("WebSocket连接已关闭") logger.bind(tag=TAG).debug("Web socket connection closed")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}") logger.bind(tag=TAG).error(f"Failed to close web socket connection: {e}")
finally: finally:
self.asr_ws = None self.asr_ws = None
logger.bind(tag=TAG).info("ASR会话清理完成") logger.bind(tag=TAG).info("Asr session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format): async def speech_to_text(self, opus_data, session_id, audio_format):
"""获取识别结果""" """Get recognition results"""
result = self.text result = self.text
self.text = "" self.text = ""
return result, None return result, None
async def close(self): async def close(self):
"""关闭资源""" """close resource"""
await self._cleanup() await self._cleanup()

View file

@ -26,39 +26,39 @@ class ASRProvider(ASRProviderBase):
self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key) self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key)
# 确保输出目录存在 # Make sure the output directory exists
os.makedirs(self.output_dir, exist_ok=True) os.makedirs(self.output_dir, exist_ok=True)
async def speech_to_text( async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus" self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]: ) -> Tuple[Optional[str], Optional[str]]:
"""将语音数据转换为文本""" """Convert voice data to text"""
if not opus_data: if not opus_data:
logger.bind(tag=TAG).warning("音频数据为空!") logger.bind(tag=TAG).warning("Audio data is empty!")
return None, None return None, None
file_path = None file_path = None
try: try:
# 检查配置是否已设置 # Check if the configuration is set
if not self.app_id or not self.api_key or not self.secret_key: if not self.app_id or not self.api_key or not self.secret_key:
logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别") logger.bind(tag=TAG).error("Baidu speech recognition configuration is not set and recognition cannot be performed")
return None, file_path return None, file_path
# 将Opus音频数据解码为PCM # Decode opus audio data to pcm
if audio_format == "pcm": if audio_format == "pcm":
pcm_data = opus_data pcm_data = opus_data
else: else:
pcm_data = self.decode_opus(opus_data) pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data) combined_pcm_data = b"".join(pcm_data)
# 判断是否保存为WAV文件 # Determine whether to save as wav file
if self.delete_audio_file: if self.delete_audio_file:
pass pass
else: else:
self.save_audio_to_file(pcm_data, session_id) self.save_audio_to_file(pcm_data, session_id)
start_time = time.time() start_time = time.time()
# 识别本地文件 # Identify local files
result = self.client.asr( result = self.client.asr(
combined_pcm_data, combined_pcm_data,
"pcm", "pcm",
@ -70,16 +70,16 @@ class ASRProvider(ASRProviderBase):
if result and result["err_no"] == 0: if result and result["err_no"] == 0:
logger.bind(tag=TAG).debug( logger.bind(tag=TAG).debug(
f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}" f"Baidu speech recognition takes timeeech recognition takes time: {time.time() - start_time:.3f}s | result: {result}"
) )
result = result["result"][0] result = result["result"][0]
return result, file_path return result, file_path
else: else:
raise Exception( raise Exception(
f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}" f"Baidu speech recognition failed, error code: {result['err_no']},error message: {result['err_msg']}"
) )
return None, file_path return None, file_path
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True) logger.bind(tag=TAG).error(f"An error occurred while processing audio!{e}", exc_info=True)
return None, file_path return None, file_path

View file

@ -3,7 +3,7 @@ from typing import Union, Optional
class InterfaceType(Enum): class InterfaceType(Enum):
# 接口类型 # Interface type
STREAM = "STREAM" # 流式接口 STREAM = "STREAM" # streaming interface
NON_STREAM = "NON_STREAM" # 非流式接口 NON_STREAM = "NON_STREAM" # non-streaming interface
LOCAL = "LOCAL" # 本地服务 LOCAL = "LOCAL" # local service