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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import subprocess
2
+ import tempfile
3
+ import os
4
+ # import json
5
+ # import shutil
6
+ import time
7
+ import librosa
8
+ import torch
9
+ import argparse
10
+ import soundfile as sf
11
+ # from pathlib import Path
12
+ import cn2an
13
+ import requests
14
+ import re
15
+ import numpy as np
16
+ import onnxruntime as ort
17
+ import axengine as axe
18
+ import threading
19
+ import queue
20
+ from collections import deque
21
+
22
+ # 导入SenseVoice相关模块
23
+ from model import SinusoidalPositionEncoder
24
+ from utils.ax_model_bin import AX_SenseVoiceSmall
25
+ from utils.ax_vad_bin import AX_Fsmn_vad
26
+ from utils.vad_utils import merge_vad
27
+ from funasr.tokenizer.sentencepiece_tokenizer import SentencepiecesTokenizer
28
+
29
+ # 导入MeloTTS相关模块
30
+ from libmelotts.python.split_utils import split_sentence
31
+ from libmelotts.python.text import cleaned_text_to_sequence
32
+ from libmelotts.python.text.cleaner import clean_text
33
+ from libmelotts.python.symbols import LANG_TO_SYMBOL_MAP
34
+
35
+ # 配置参数
36
+ # tts 参数
37
+ TTS_MODEL_DIR = "libmelotts/models"
38
+ TTS_MODEL_FILES = {
39
+ "g": "g-zh_mix_en.bin",
40
+ "encoder": "encoder-zh.onnx",
41
+ "decoder": "decoder-zh.axmodel"
42
+ }
43
+
44
+ # Qwen大模型翻译API参数
45
+ QWEN_API_URL = "http://10.126.29.158:8000" # API服务地址
46
+
47
+ # TTS辅助函数
48
+ def intersperse(lst, item):
49
+ result = [item] * (len(lst) * 2 + 1)
50
+ result[1::2] = lst
51
+ return result
52
+
53
+ # def get_text_for_tts_infer(text, language_str, symbol_to_id=None):
54
+ # norm_text, phone, tone, word2ph = clean_text(text, language_str)
55
+ # phone, tone, language = cleaned_text_to_sequence(phone, tone, language_str, symbol_to_id)
56
+
57
+ # phone = intersperse(phone, 0)
58
+ # tone = intersperse(tone, 0)
59
+ # language = intersperse(language, 0)
60
+
61
+ # phone = np.array(phone, dtype=np.int32)
62
+ # tone = np.array(tone, dtype=np.int32)
63
+ # language = np.array(language, dtype=np.int32)
64
+ # word2ph = np.array(word2ph, dtype=np.int32) * 2
65
+ # word2ph[0] += 1
66
+
67
+ # return phone, tone, language, norm_text, word2ph
68
+
69
+ # 处理字符无法不识别
70
+ def get_text_for_tts_infer(text, language_str, symbol_to_id=None):
71
+ """修复版音素处理:确保所有数组长度一致"""
72
+ try:
73
+ norm_text, phone, tone, word2ph = clean_text(text, language_str)
74
+
75
+ # 特殊音素直接映射为空字符串
76
+ phone_mapping = {
77
+ 'ɛ': '', 'æ': '', 'ʌ': '', 'ʊ': '', 'ɔ': '', 'ɪ': '', 'ɝ': '', 'ɚ': '', 'ɑ': '',
78
+ 'ʒ': '', 'θ': '', 'ð': '', 'ŋ': '', 'ʃ': '', 'ʧ': '', 'ʤ': '', 'ː': '', 'ˈ': '',
79
+ 'ˌ': '', 'ʰ': '', 'ʲ': '', 'ʷ': '', 'ʔ': '', 'ɾ': '', 'ɹ': '', 'ɫ': '', 'ɡ': '',
80
+ }
81
+
82
+ # 同步处理 phone 和 tone,确保它们长度一致
83
+ processed_phone = []
84
+ processed_tone = []
85
+ removed_symbols = set()
86
+
87
+ for p, t in zip(phone, tone):
88
+ if p in phone_mapping:
89
+ # 特殊音素直接删除,同时删除对应的 tone
90
+ removed_symbols.add(p)
91
+ elif p in symbol_to_id:
92
+ # 正常音素保留,同时保留对应的 tone
93
+ processed_phone.append(p)
94
+ processed_tone.append(t)
95
+ else:
96
+ # 其他未知音素也删除
97
+ removed_symbols.add(p)
98
+
99
+ # 记录被删除的音素
100
+ if removed_symbols:
101
+ print(f"[音素过滤] 删除了 {len(removed_symbols)} 个特殊音素: {sorted(removed_symbols)}")
102
+ print(f"[音素过滤] 处理后音素序列长度: {len(processed_phone)}")
103
+ print(f"[音素过滤] 处理后音调序列长度: {len(processed_tone)}")
104
+
105
+ # 如果没有有效音素,使用默认音素,
106
+ if not processed_phone:
107
+ print("[警告] 没有有效音素,使用默认中文音素")
108
+ processed_phone = ['ni', 'hao']
109
+ processed_tone = ['1', '3']
110
+ word2ph = [1, 1]
111
+
112
+ # 确保 word2ph 的长度与处理后的音素序列匹配
113
+ if len(processed_phone) != len(phone):
114
+ print(f"[警告] 音素序列长度变化: {len(phone)} -> {len(processed_phone)}")
115
+ # 简单处理:重新计算 word2ph
116
+ word2ph = [1] * len(processed_phone)
117
+
118
+ phone, tone, language = cleaned_text_to_sequence(processed_phone, processed_tone, language_str, symbol_to_id)
119
+
120
+ phone = intersperse(phone, 0)
121
+ tone = intersperse(tone, 0)
122
+ language = intersperse(language, 0)
123
+
124
+ phone = np.array(phone, dtype=np.int32)
125
+ tone = np.array(tone, dtype=np.int32)
126
+ language = np.array(language, dtype=np.int32)
127
+ word2ph = np.array(word2ph, dtype=np.int32) * 2
128
+ word2ph[0] += 1
129
+
130
+ return phone, tone, language, norm_text, word2ph
131
+
132
+ except Exception as e:
133
+ print(f"[错误] 文本处理失败: {e}")
134
+ import traceback
135
+ traceback.print_exc()
136
+ raise e
137
+
138
+ def audio_numpy_concat(segment_data_list, sr, speed=1.):
139
+ audio_segments = []
140
+ for segment_data in segment_data_list:
141
+ audio_segments += segment_data.reshape(-1).tolist()
142
+ audio_segments += [0] * int((sr * 0.05) / speed)
143
+ audio_segments = np.array(audio_segments).astype(np.float32)
144
+ return audio_segments
145
+
146
+ def merge_sub_audio(sub_audio_list, pad_size, audio_len):
147
+ if pad_size > 0:
148
+ for i in range(len(sub_audio_list) - 1):
149
+ sub_audio_list[i][-pad_size:] += sub_audio_list[i+1][:pad_size]
150
+ sub_audio_list[i][-pad_size:] /= 2
151
+ if i > 0:
152
+ sub_audio_list[i] = sub_audio_list[i][pad_size:]
153
+
154
+ sub_audio = np.concatenate(sub_audio_list, axis=-1)
155
+ return sub_audio[:audio_len]
156
+
157
+ def calc_word2pronoun(word2ph, pronoun_lens):
158
+ indice = [0]
159
+ for ph in word2ph[:-1]:
160
+ indice.append(indice[-1] + ph)
161
+ word2pronoun = []
162
+ for i, ph in zip(indice, word2ph):
163
+ word2pronoun.append(np.sum(pronoun_lens[i : i + ph]))
164
+ return word2pronoun
165
+
166
+ def generate_slices(word2pronoun, dec_len):
167
+ pn_start, pn_end = 0, 0
168
+ zp_start, zp_end = 0, 0
169
+ zp_len = 0
170
+ pn_slices = []
171
+ zp_slices = []
172
+ while pn_end < len(word2pronoun):
173
+ if pn_end - pn_start > 2 and np.sum(word2pronoun[pn_end - 2 : pn_end + 1]) <= dec_len:
174
+ zp_len = np.sum(word2pronoun[pn_end - 2 : pn_end])
175
+ zp_start = zp_end - zp_len
176
+ pn_start = pn_end - 2
177
+ else:
178
+ zp_len = 0
179
+ zp_start = zp_end
180
+ pn_start = pn_end
181
+
182
+ while pn_end < len(word2pronoun) and zp_len + word2pronoun[pn_end] <= dec_len:
183
+ zp_len += word2pronoun[pn_end]
184
+ pn_end += 1
185
+ zp_end = zp_start + zp_len
186
+ pn_slices.append(slice(pn_start, pn_end))
187
+ zp_slices.append(slice(zp_start, zp_end))
188
+ return pn_slices, zp_slices
189
+
190
+ # 确认中英文
191
+ def lang_detect_with_regex(text):
192
+ text_without_digits = re.sub(r'\d+', '', text)
193
+
194
+ if not text_without_digits:
195
+ return 'unknown'
196
+
197
+ if re.search(r'[\u4e00-\u9fff]', text_without_digits):
198
+ return 'chinese'
199
+ else:
200
+ if re.search(r'[a-zA-Z]', text_without_digits):
201
+ return 'english'
202
+ else:
203
+ return 'unknown'
204
+
205
+ class QwenTranslationAPI:
206
+ def __init__(self, api_url=QWEN_API_URL):
207
+ self.api_url = api_url
208
+ self.session_id = f"speech_translate_{int(time.time())}"
209
+ self.last_reset_time = time.time()
210
+ self.request_count = 0
211
+ self.max_requests_before_reset = 10
212
+
213
+ def reset_context(self):
214
+ """重置API上下文"""
215
+ try:
216
+ reset_url = f"{self.api_url}/api/reset"
217
+ response = requests.post(reset_url, json={}, timeout=5)
218
+ if response.status_code == 200:
219
+ print("[翻译API] ✓ 上下文重置成功")
220
+ self.last_reset_time = time.time()
221
+ self.request_count = 0
222
+ return True
223
+ else:
224
+ print(f"[翻译API] ✗ 重置失败,状态码: {response.status_code}, 响应: {response.text}")
225
+ except Exception as e:
226
+ print(f"[翻译API] ✗ 重置上下文失败: {e}")
227
+ return False
228
+
229
+ def check_and_reset_if_needed(self):
230
+ """检查是否需要重置上下文"""
231
+ current_time = time.time()
232
+ if (self.request_count >= 10 or
233
+ current_time - self.last_reset_time > 120): # 2分钟
234
+ print(f"[翻译API] 重置 (请求数: {self.request_count}, 时间: {current_time - self.last_reset_time:.1f}秒)")
235
+ return self.reset_context()
236
+ return True
237
+
238
+ def translate(self, text_content, max_retries=3, timeout=120):
239
+ if not text_content or text_content.strip() == "":
240
+ return "输入文本为空"
241
+
242
+ # 过滤太短的文本
243
+ if len(text_content.strip()) < 3:
244
+ return text_content
245
+
246
+ if lang_detect_with_regex(text_content)=='chinese':
247
+ prompt_f = "翻译成英文"
248
+ else:
249
+ prompt_f= "翻译成中文"
250
+
251
+ prompt = f"{prompt_f}:{text_content}"
252
+ print(f"[翻译API] 发送请求: {prompt}")
253
+
254
+ # 检查是否需要重置
255
+ self.check_and_reset_if_needed()
256
+
257
+ for attempt in range(max_retries):
258
+ try:
259
+ generate_url = f"{self.api_url}/api/generate"
260
+ payload = {
261
+ "prompt": prompt,
262
+ "temperature": 0.1,
263
+ "repetition_penalty": 1.0,
264
+ "top-p": 0.9,
265
+ "top-k": 40,
266
+ "max_new_tokens": 512
267
+ }
268
+
269
+ print(f"[翻译API] 开始生成请求 (尝试 {attempt + 1}/{max_retries})")
270
+ response = requests.post(generate_url, json=payload, timeout=30)
271
+ response.raise_for_status()
272
+ print("[翻译API] 生成请求成功")
273
+
274
+ result_url = f"{self.api_url}/api/generate_provider"
275
+ start_time = time.time()
276
+ full_translation = ""
277
+ error_detected = False
278
+
279
+ while time.time() - start_time < timeout:
280
+ try:
281
+ result_response = requests.get(result_url, timeout=10)
282
+ result_data = result_response.json()
283
+
284
+ current_chunk = result_data.get("response", "")
285
+
286
+ # 检查是否有错误
287
+ if "error:" in current_chunk.lower() or "setkvcache failed" in current_chunk.lower():
288
+ print(f"[翻译API] ✗ 检测到错误: {current_chunk}")
289
+ error_detected = True
290
+ print("[翻译API] 立即重置上下文...")
291
+ self.reset_context()
292
+ break
293
+
294
+ full_translation += current_chunk
295
+
296
+ if result_data.get("done", False):
297
+ if full_translation and len(full_translation.strip()) > 0:
298
+ self.request_count += 1
299
+ print(f"[翻译API] ✓ 翻译完成: {full_translation}")
300
+ return full_translation
301
+ else:
302
+ print(f"[翻译API] ✗ 翻译结果为空")
303
+ break
304
+
305
+ time.sleep(0.05)
306
+
307
+ except requests.exceptions.RequestException as e:
308
+ print(f"[翻译API] 轮询请求失败: {e}")
309
+ if time.time() - start_time > timeout:
310
+ break
311
+ time.sleep(0.5)
312
+ continue
313
+
314
+ if error_detected:
315
+ if attempt < max_retries - 1:
316
+ wait_time = 1
317
+ print(f"[翻译API] 等待 {wait_time} 秒后重试...")
318
+ time.sleep(wait_time)
319
+ continue
320
+ else:
321
+ print("[翻译API] 达到最大重试次数,返回原文")
322
+ return text_content
323
+
324
+ print(f"[翻译API] 轮询超时,尝试第 {attempt + 1} 次重试")
325
+
326
+ except requests.exceptions.RequestException as e:
327
+ print(f"[翻译API] 请求失败 (尝试 {attempt + 1}/{max_retries}): {e}")
328
+ if attempt < max_retries - 1:
329
+ wait_time = 2 ** attempt
330
+ print(f"[翻译API] 等待 {wait_time} 秒后重试...")
331
+ time.sleep(wait_time)
332
+ else:
333
+ return text_content
334
+ except Exception as e:
335
+ print(f"[翻译API] 翻译过程出错: {e}")
336
+ if attempt < max_retries - 1:
337
+ time.sleep(1)
338
+ continue
339
+ return text_content
340
+
341
+ print("[翻译API] 翻译超时,返回原文")
342
+ return text_content
343
+
344
+ class AudioResampler:
345
+ """音频重采样器"""
346
+ def __init__(self, target_sr=16000):
347
+ self.target_sr = target_sr
348
+
349
+ def resample_audio(self, audio_data, original_sr):
350
+ """重采样音频到目标采样率,asr统一输入16000Hz"""
351
+ if original_sr == self.target_sr:
352
+ return audio_data
353
+
354
+ print(f"[重采样] {original_sr}Hz -> {self.target_sr}Hz")
355
+ return librosa.resample(y=audio_data, orig_sr=original_sr, target_sr=self.target_sr)
356
+
357
+ def resample_chunk(self, audio_chunk, original_sr):
358
+ """重采样音频块:长音频进行过冲采样后,音频块可以不做重采样"""
359
+ if original_sr == self.target_sr:
360
+ return audio_chunk
361
+
362
+ if len(audio_chunk) < 1000:
363
+ return self._linear_resample(audio_chunk, original_sr, self.target_sr)
364
+ else:
365
+ return librosa.resample(y=audio_chunk, orig_sr=original_sr, target_sr=self.target_sr)
366
+
367
+ def _linear_resample(self, audio_chunk, original_sr, target_sr):
368
+ """线性插值重采样"""
369
+ ratio = target_sr / original_sr
370
+ old_length = len(audio_chunk)
371
+ new_length = int(old_length * ratio)
372
+
373
+ old_indices = np.arange(old_length)
374
+ new_indices = np.linspace(0, old_length - 1, new_length)
375
+
376
+ resampled = np.interp(new_indices, old_indices, audio_chunk)
377
+ return resampled
378
+
379
+ class StreamProcessor:
380
+ """流式处理"""
381
+ def __init__(self, pipeline, chunk_duration=7.0, overlap_duration=0.01, target_sr=16000):
382
+ self.pipeline = pipeline
383
+ self.chunk_duration = chunk_duration # 增加4->7秒
384
+ self.overlap_duration = overlap_duration # 减少到0.1->0.01秒
385
+ self.target_sr = target_sr
386
+ self.chunk_samples = int(chunk_duration * target_sr)
387
+ self.overlap_samples = int(overlap_duration * target_sr)
388
+ self.audio_buffer = deque()
389
+ self.result_queue = queue.Queue()
390
+ self.is_running = False
391
+ self.processing_thread = None
392
+ self.resampler = AudioResampler(target_sr=target_sr)
393
+ self.segment_counter = 0 # 音频段计数器
394
+ self.processed_texts = set() # 记录已处理的文本,避免重复
395
+
396
+ def start_processing(self):
397
+ """开始流式处理"""
398
+ self.is_running = True
399
+ self.processing_thread = threading.Thread(target=self._process_loop)
400
+ self.processing_thread.daemon = True
401
+ self.processing_thread.start()
402
+
403
+ def stop_processing(self):
404
+ """停止流式处理"""
405
+ self.is_running = False
406
+ if self.processing_thread:
407
+ self.processing_thread.join(timeout=5)
408
+
409
+ def add_audio_chunk(self, audio_chunk, original_sr=None):
410
+ """添加音频块到缓冲区"""
411
+ if original_sr and original_sr != self.target_sr:
412
+ audio_chunk = self.resampler.resample_chunk(audio_chunk, original_sr)
413
+
414
+ self.audio_buffer.append(audio_chunk)
415
+
416
+ def get_next_result(self, timeout=1.0):
417
+ """获取下一个处理结果"""
418
+ try:
419
+ return self.result_queue.get(timeout=timeout)
420
+ except queue.Empty:
421
+ return None
422
+
423
+ def _process_loop(self):
424
+ """处理循环"""
425
+ accumulated_audio = np.array([], dtype=np.float32)
426
+ last_asr_result = "" # 记录上一次的ASR结果,防止重复处理
427
+
428
+ while self.is_running:
429
+ if len(self.audio_buffer) > 0:
430
+ audio_chunk = self.audio_buffer.popleft()
431
+ accumulated_audio = np.concatenate([accumulated_audio, audio_chunk])
432
+
433
+ # 当积累的音频足够处理时
434
+ if len(accumulated_audio) >= self.chunk_samples:
435
+ # 提取处理块(减少重叠)
436
+ process_chunk = accumulated_audio[:self.chunk_samples]
437
+ accumulated_audio = accumulated_audio[self.chunk_samples - self.overlap_samples:]
438
+
439
+ try:
440
+ # 实时ASR识别
441
+ asr_result = self._stream_asr(process_chunk)
442
+
443
+ # 过滤条件:
444
+ # # 1. 文本有效且足够长
445
+ # 2. 与上次结果不同(避免重复)
446
+ # 3. 不是已处理过的文本
447
+ if (asr_result and asr_result.strip() and
448
+ # len(asr_result.strip()) >= 5 and
449
+ asr_result != last_asr_result and
450
+ asr_result not in self.processed_texts):
451
+
452
+ print(f"[实时ASR] {asr_result}")
453
+ last_asr_result = asr_result
454
+ self.processed_texts.add(asr_result)
455
+
456
+ # 实时翻译
457
+ try:
458
+ translation_result = self.pipeline.run_translation(asr_result)
459
+
460
+ # 检查翻译结果是否有效
461
+ if (translation_result and
462
+ translation_result != asr_result and
463
+ "翻译失败" not in translation_result and
464
+ "error:" not in translation_result.lower() and
465
+ "输入文本为空" not in translation_result):
466
+
467
+ print(f"[实时翻译] {translation_result}")
468
+
469
+ # TTS合成
470
+ try:
471
+ self.segment_counter += 1
472
+ tts_filename = f"stream_segment_{self.segment_counter:04d}.wav"
473
+ tts_start_time = time.time()
474
+
475
+ tts_path = self.pipeline.run_tts(
476
+ translation_result,
477
+ self.pipeline.output_dir,
478
+ tts_filename
479
+ )
480
+
481
+ tts_time = time.time() - tts_start_time
482
+ print(f"[实时TTS] 音频已保存: {tts_path} (耗时: {tts_time:.2f}秒)")
483
+
484
+ # 将完整结果放入队列
485
+ self.result_queue.put({
486
+ 'type': 'complete',
487
+ 'original': asr_result,
488
+ 'translated': translation_result,
489
+ 'audio_path': tts_path,
490
+ 'timestamp': time.time(),
491
+ 'segment_id': self.segment_counter
492
+ })
493
+
494
+ except Exception as tts_error:
495
+ print(f"[实时TTS错误] {tts_error}")
496
+ import traceback
497
+ traceback.print_exc()
498
+ else:
499
+ print(f"[实时翻译] 翻译结果无效,已跳过")
500
+
501
+ except Exception as translation_error:
502
+ print(f"[实时翻译错误] {translation_error}")
503
+ else:
504
+ if asr_result == last_asr_result:
505
+ print(f"[实时ASR] 重复内容已跳过: {asr_result}")
506
+
507
+ except Exception as e:
508
+ print(f"[流式处理错误] {e}")
509
+ import traceback
510
+ traceback.print_exc()
511
+
512
+ time.sleep(0.01)
513
+
514
+ def _stream_asr(self, audio_chunk):
515
+ """流式ASR识别(带VAD)"""
516
+ try:
517
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
518
+ # 步骤1: VAD检测 - 过滤静音段
519
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
520
+ res_vad = self.pipeline.model_vad(audio_chunk)[0]
521
+ vad_segments = merge_vad(res_vad, 15 * 1000)
522
+
523
+ # 如果没有检测到语音段,直接返回空
524
+ if not vad_segments or len(vad_segments) == 0:
525
+ print(f"[VAD] 未检测到语音活动,跳过此音频块")
526
+ return ""
527
+
528
+ print(f"[VAD] 检测到 {len(vad_segments)} 个语音段")
529
+
530
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
531
+ # 步骤2: 对检测到的语音段进行ASR识别
532
+ # ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
533
+ all_results = ""
534
+
535
+ for i, segment in enumerate(vad_segments):
536
+ segment_start, segment_end = segment
537
+ start_sample = int(segment_start / 1000 * self.target_sr)
538
+ end_sample = min(int(segment_end / 1000 * self.target_sr), len(audio_chunk))
539
+ segment_audio = audio_chunk[start_sample:end_sample]
540
+
541
+ # 跳过太短的片段,减少误识别(小于0.3秒)
542
+ if len(segment_audio) < int(0.3 * self.target_sr):
543
+ continue
544
+
545
+ # 写入临时文件
546
+ with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
547
+ sf.write(temp_file.name, segment_audio, self.target_sr)
548
+ temp_filename = temp_file.name
549
+
550
+ try:
551
+ # ASR识别
552
+ segment_result = self.pipeline.model_bin(
553
+ temp_filename,
554
+ "auto",
555
+ True,
556
+ self.pipeline.position_encoding,
557
+ tokenizer=self.pipeline.tokenizer,
558
+ )
559
+
560
+ if segment_result and segment_result.strip():
561
+ all_results += segment_result + " "
562
+
563
+ # 清理临时文件
564
+ os.unlink(temp_filename)
565
+
566
+ except Exception as e:
567
+ print(f"[ASR错误] 处理VAD段 {i} 时出错: {e}")
568
+ if os.path.exists(temp_filename):
569
+ os.unlink(temp_filename)
570
+ continue
571
+
572
+ return all_results.strip()
573
+
574
+ except Exception as e:
575
+ print(f"[ASR错误] {e}")
576
+ return ""
577
+
578
+ class SpeechTranslationPipeline:
579
+ def __init__(self,
580
+ tts_model_dir, tts_model_files,
581
+ asr_model_dir="ax_model", seq_len=132,
582
+ tts_dec_len=128, sample_rate=44100, tts_speed=0.8,
583
+ qwen_api_url=QWEN_API_URL, target_sr=16000,
584
+ output_dir="./output"):
585
+ self.tts_model_dir = tts_model_dir
586
+ self.tts_model_files = tts_model_files
587
+ self.asr_model_dir = asr_model_dir
588
+ self.seq_len = seq_len
589
+ self.tts_dec_len = tts_dec_len
590
+ self.sample_rate = sample_rate
591
+ self.tts_speed = tts_speed
592
+ self.qwen_api_url = qwen_api_url
593
+ self.target_sr = target_sr
594
+ self.output_dir = output_dir
595
+
596
+ # 输出目录
597
+ os.makedirs(self.output_dir, exist_ok=True)
598
+
599
+ # 初始化音频重采样器
600
+ self.resampler = AudioResampler(target_sr=target_sr)
601
+
602
+ # 初始化ASR模型
603
+ self._init_asr_models()
604
+
605
+ # 初始化TTS模型
606
+ self._init_tts_models()
607
+
608
+ # 初始化翻译API
609
+ self.translator = QwenTranslationAPI(api_url=qwen_api_url)
610
+
611
+ # 初始化流式处理器
612
+ self.stream_processor = StreamProcessor(self, target_sr=target_sr)
613
+
614
+ # 验证所有必需文件存在
615
+ self._validate_files()
616
+
617
+ # 初始化时重置API上下文
618
+ print("[初始化] 重置API上下文...")
619
+ self.translator.reset_context()
620
+
621
+ def _init_asr_models(self):
622
+ """初始化语音识别相关模型"""
623
+ print("Initializing SenseVoice models...")
624
+
625
+ self.model_vad = AX_Fsmn_vad(self.asr_model_dir)
626
+
627
+ self.embed = SinusoidalPositionEncoder()
628
+ self.position_encoding = self.embed.get_position_encoding(
629
+ torch.randn(1, self.seq_len, 560)).numpy()
630
+
631
+ self.model_bin = AX_SenseVoiceSmall(self.asr_model_dir, seq_len=self.seq_len)
632
+
633
+ tokenizer_path = os.path.join(self.asr_model_dir, "chn_jpn_yue_eng_ko_spectok.bpe.model")
634
+ self.tokenizer = SentencepiecesTokenizer(bpemodel=tokenizer_path)
635
+
636
+ print("SenseVoice models initialized successfully.")
637
+
638
+ def _init_tts_models(self):
639
+ """初始化TTS相关模型"""
640
+ print("Initializing MeloTTS models...")
641
+ init_start = time.time()
642
+
643
+ enc_model = os.path.join(self.tts_model_dir, self.tts_model_files["encoder"])
644
+ dec_model = os.path.join(self.tts_model_dir, self.tts_model_files["decoder"])
645
+
646
+ model_load_start = time.time()
647
+ self.sess_enc = ort.InferenceSession(enc_model, providers=["CPUExecutionProvider"], sess_options=ort.SessionOptions())
648
+ self.sess_dec = axe.InferenceSession(dec_model)
649
+ print(f" Load encoder/decoder models: {(time.time() - model_load_start)*1000:.2f}ms")
650
+
651
+ g_file = os.path.join(self.tts_model_dir, self.tts_model_files["g"])
652
+ self.tts_g = np.fromfile(g_file, dtype=np.float32).reshape(1, 256, 1)
653
+
654
+ self.tts_language = "ZH_MIX_EN"
655
+ self.symbol_to_id = {s: i for i, s in enumerate(LANG_TO_SYMBOL_MAP[self.tts_language])}
656
+
657
+ print(" Warming up TTS modules...")
658
+ warmup_start = time.time()
659
+
660
+ try:
661
+ warmup_text_mix = "这是一个test测试。"
662
+ _, _, _, _, _ = get_text_for_tts_infer(warmup_text_mix, self.tts_language, symbol_to_id=self.symbol_to_id)
663
+ print(f" Mixed ZH-EN warm-up: {(time.time() - warmup_start)*1000:.2f}ms")
664
+ except Exception as e:
665
+ print(f" Warning: Mixed warm-up failed: {e}")
666
+
667
+ total_init_time = (time.time() - init_start) * 1000
668
+ print(f"MeloTTS models initialized successfully. Total init time: {total_init_time:.2f}ms")
669
+
670
+ def _validate_files(self):
671
+ """验证所有必需的文件都存在"""
672
+ for key, filename in self.tts_model_files.items():
673
+ filepath = os.path.join(self.tts_model_dir, filename)
674
+ if not os.path.exists(filepath):
675
+ raise FileNotFoundError(f"TTS模型文件不存在: {filepath}")
676
+
677
+ try:
678
+ response = requests.get(f"{self.qwen_api_url}/api/generate_provider", timeout=5)
679
+ print("[API检查] 千问API服务连接正常")
680
+ except:
681
+ print("[API警告] 无法连接到千问API服务,请确保已启动API服务")
682
+
683
+ def start_stream_processing(self):
684
+ """开始流式处理"""
685
+ self.stream_processor.start_processing()
686
+ print("[流式处理] 已启动")
687
+
688
+ def stop_stream_processing(self):
689
+ """停止流式处理"""
690
+ self.stream_processor.stop_processing()
691
+ print("[流式处理] 已停止")
692
+
693
+ def process_audio_stream(self, audio_chunk, original_sr=None):
694
+ """处理音频流数据"""
695
+ self.stream_processor.add_audio_chunk(audio_chunk, original_sr)
696
+
697
+ def get_stream_results(self):
698
+ """获取流式处理结果"""
699
+ return self.stream_processor.get_next_result()
700
+
701
+ def load_and_resample_audio(self, audio_file):
702
+ """加载音频并重采样到目标��样率"""
703
+ print(f"加载音频文件: {audio_file}")
704
+ speech, original_sr = librosa.load(audio_file, sr=None)
705
+
706
+ audio_duration = len(speech) / original_sr
707
+ print(f"原始音频: {original_sr}Hz, 时长: {audio_duration:.2f}秒")
708
+
709
+ if original_sr != self.target_sr:
710
+ speech = self.resampler.resample_audio(speech, original_sr)
711
+ print(f"重采样后: {self.target_sr}Hz, 时长: {len(speech)/self.target_sr:.2f}秒")
712
+
713
+ return speech, self.target_sr
714
+
715
+ def run_translation(self, text_content):
716
+ """调用Qwen大模型API中英互译"""
717
+ print("Starting translation via API...")
718
+ translation_start_time = time.time()
719
+
720
+ translate_content = self.translator.translate(text_content)
721
+
722
+ translation_time_cost = time.time() - translation_start_time
723
+ print(f"Translation processing time: {translation_time_cost:.2f} seconds")
724
+ print(f"Translation Result: {translate_content}")
725
+
726
+ return translate_content
727
+
728
+ def run_tts(self, translate_content, output_dir, output_wav=None):
729
+ """使用TTS模型合成语音"""
730
+ output_path = os.path.join(output_dir, output_wav)
731
+
732
+ try:
733
+ if lang_detect_with_regex(translate_content) == "chinese":
734
+ translate_content = cn2an.transform(translate_content, "an2cn")
735
+
736
+ print(f"TTS synthesis for text: {translate_content}")
737
+
738
+ sens = split_sentence(translate_content, language_str=self.tts_language)
739
+ print(f"Text split into {len(sens)} sentences")
740
+
741
+ audio_list = []
742
+
743
+ for n, se in enumerate(sens):
744
+ if self.tts_language in ['EN', 'ZH_MIX_EN']:
745
+ se = re.sub(r'([a-z])([A-Z])', r'\1 \2', se)
746
+
747
+ print(f"Processing sentence[{n}]: {se}")
748
+
749
+ phones, tones, lang_ids, norm_text, word2ph = get_text_for_tts_infer(
750
+ se, self.tts_language, symbol_to_id=self.symbol_to_id)
751
+
752
+ encoder_start = time.time()
753
+ z_p, pronoun_lens, audio_len = self.sess_enc.run(None, input_feed={
754
+ 'phone': phones, 'g': self.tts_g,
755
+ 'tone': tones, 'language': lang_ids,
756
+ 'noise_scale': np.array([0], dtype=np.float32),
757
+ 'length_scale': np.array([1.0 / self.tts_speed], dtype=np.float32),
758
+ 'noise_scale_w': np.array([0], dtype=np.float32),
759
+ 'sdp_ratio': np.array([0], dtype=np.float32)})
760
+ print(f"Encoder run time: {1000 * (time.time() - encoder_start):.2f}ms")
761
+
762
+ word2pronoun = calc_word2pronoun(word2ph, pronoun_lens)
763
+ pn_slices, zp_slices = generate_slices(word2pronoun, self.tts_dec_len)
764
+
765
+ audio_len = audio_len[0]
766
+ sub_audio_list = []
767
+
768
+ for i, (ps, zs) in enumerate(zip(pn_slices, zp_slices)):
769
+ zp_slice = z_p[..., zs]
770
+
771
+ sub_dec_len = zp_slice.shape[-1]
772
+ sub_audio_len = 512 * sub_dec_len
773
+
774
+ if zp_slice.shape[-1] < self.tts_dec_len:
775
+ zp_slice = np.concatenate((zp_slice, np.zeros((*zp_slice.shape[:-1], self.tts_dec_len - zp_slice.shape[-1]), dtype=np.float32)), axis=-1)
776
+
777
+ decoder_start = time.time()
778
+ audio = self.sess_dec.run(None, input_feed={"z_p": zp_slice, "g": self.tts_g})[0].flatten()
779
+
780
+ audio_start = 0
781
+ if len(sub_audio_list) > 0:
782
+ if pn_slices[i - 1].stop > ps.start:
783
+ audio_start = 512 * word2pronoun[ps.start]
784
+
785
+ audio_end = sub_audio_len
786
+ if i < len(pn_slices) - 1:
787
+ if ps.stop > pn_slices[i + 1].start:
788
+ audio_end = sub_audio_len - 512 * word2pronoun[ps.stop - 1]
789
+
790
+ audio = audio[audio_start:audio_end]
791
+ print(f"Decode slice[{i}]: decoder run time {1000 * (time.time() - decoder_start):.2f}ms")
792
+ sub_audio_list.append(audio)
793
+
794
+ sub_audio = merge_sub_audio(sub_audio_list, 0, audio_len)
795
+ audio_list.append(sub_audio)
796
+
797
+ audio = audio_numpy_concat(audio_list, sr=self.sample_rate, speed=self.tts_speed)
798
+
799
+ sf.write(output_path, audio, self.sample_rate)
800
+ print(f"TTS audio saved to {output_path}")
801
+
802
+ return output_path
803
+
804
+ except Exception as e:
805
+ print(f"TTS synthesis failed: {e}")
806
+ import traceback
807
+ traceback.print_exc()
808
+ raise e
809
+
810
+ def process_long_audio_stream(self, audio_file, chunk_size=64000):
811
+ """
812
+ 处理长音频文件的流式模拟
813
+ chunk_size增加到64000(4秒 * 16000Hz),与StreamProcessor的chunk_duration匹配
814
+ 4秒有点短,改到7秒感觉更好点
815
+ """
816
+ print(f"[流式处理] 开始处理长音频: {audio_file}")
817
+
818
+ # 加载并重采样音频
819
+ speech, fs = self.load_and_resample_audio(audio_file)
820
+
821
+ # 启动流式处理
822
+ self.start_stream_processing()
823
+
824
+ total_chunks = (len(speech) + chunk_size - 1) // chunk_size
825
+ print(f"[流式处理] 音频总长度: {len(speech)/fs:.2f}秒, 分块数: {total_chunks}")
826
+
827
+ # 收集所有结果
828
+ all_results = []
829
+
830
+ # 模拟流式输入
831
+ chunk_count = 0
832
+ for i in range(0, len(speech), chunk_size):
833
+ chunk = speech[i:i+chunk_size]
834
+ chunk_count += 1
835
+
836
+ # 处理最后一块:如果不足chunk_size,填零补齐
837
+ if len(chunk) < chunk_size:
838
+ padding_size = chunk_size - len(chunk)
839
+ chunk = np.concatenate([chunk, np.zeros(padding_size, dtype=np.float32)])
840
+ print(f"\n[流式处理] 处理音频块 {chunk_count}/{total_chunks} (最后一块,已填零 {padding_size} 样本)")
841
+ else:
842
+ print(f"\n[流式处理] 处理音频块 {chunk_count}/{total_chunks}")
843
+
844
+ self.process_audio_stream(chunk, fs)
845
+
846
+ # 获取并显示实时结果
847
+ result = self.get_stream_results()
848
+ while result:
849
+ print(f"\n{'='*70}")
850
+ print(f"[实时结果 #{len(all_results) + 1}]")
851
+ print(f"段落ID: {result['segment_id']}")
852
+ print(f"原文: {result['original']}")
853
+ print(f"翻译: {result['translated']}")
854
+ print(f"音频: {result['audio_path']}")
855
+ print(f"{'='*70}")
856
+ all_results.append(result)
857
+ result = self.get_stream_results()
858
+
859
+ time.sleep(0.1)
860
+
861
+ # 输出结果
862
+ # print(f"\n[流式处理] 等待处理剩余音频块...")
863
+ max_wait_time = 20 # 增加等待时间到20秒
864
+ wait_start = time.time()
865
+
866
+ while time.time() - wait_start < max_wait_time:
867
+ result = self.get_stream_results()
868
+ if result:
869
+ print(f"\n{'='*70}")
870
+ print(f"[实时结果 #{len(all_results) + 1}]")
871
+ print(f"段落ID: {result['segment_id']}")
872
+ print(f"原文: {result['original']}")
873
+ print(f"翻译: {result['translated']}")
874
+ print(f"音频: {result['audio_path']}")
875
+ print(f"{'='*70}")
876
+ all_results.append(result)
877
+ wait_start = time.time() # 重置等待时间
878
+ else:
879
+ time.sleep(0.2)
880
+
881
+ # 停止流式处理
882
+ self.stop_stream_processing()
883
+
884
+ print(f"\n[流式处理] 完成!共处理 {len(all_results)} 个有效结果")
885
+ return all_results
886
+
887
+ def main():
888
+ parser = argparse.ArgumentParser(description="实时语音翻译pipeline")
889
+ parser.add_argument("--audio_file", type=str, required=True, help="输入音频文件路径")
890
+ parser.add_argument("--output_dir", type=str, default="./output", help="输出目录")
891
+ parser.add_argument("--api_url", type=str, default=QWEN_API_URL, help="Qwen API服务器URL")
892
+ parser.add_argument("--target_sr", type=int, default=16000, help="ASR目标采样率 (默认: 16000)")
893
+ parser.add_argument("--chunk_duration", type=float, default=7.0, help="音频块时长(秒) (默认: 7.0)")
894
+ parser.add_argument("--overlap_duration", type=float, default=0.01, help="重叠时长(秒) (默认: 0.1)")
895
+
896
+ args = parser.parse_args()
897
+ print("-------------------实时语音翻译pipeline-------------------\n")
898
+ os.makedirs(args.output_dir, exist_ok=True)
899
+
900
+ print(f"处理音频文件: {args.audio_file}")
901
+ print(f"输出目录: {args.output_dir}")
902
+ print(f"音频块时长: {args.chunk_duration}秒")
903
+ print(f"重叠时长: {args.overlap_duration}秒\n")
904
+
905
+ # 初始化Pipeline
906
+ pipeline = SpeechTranslationPipeline(
907
+ tts_model_dir=TTS_MODEL_DIR,
908
+ tts_model_files=TTS_MODEL_FILES,
909
+ asr_model_dir="ax_model",
910
+ seq_len=132,
911
+ tts_dec_len=128,
912
+ sample_rate=44100,
913
+ tts_speed=0.8,
914
+ qwen_api_url=args.api_url,
915
+ target_sr=args.target_sr,
916
+ output_dir=args.output_dir
917
+ )
918
+
919
+ # # 可选:调整流式处理参数
920
+ # if args.chunk_duration != 7.0 or args.overlap_duration != 0.01:
921
+ # pipeline.stream_processor.chunk_duration = args.chunk_duration
922
+ # pipeline.stream_processor.overlap_duration = args.overlap_duration
923
+ # pipeline.stream_processor.chunk_samples = int(args.chunk_duration * args.target_sr)
924
+ # pipeline.stream_processor.overlap_samples = int(args.overlap_duration * args.target_sr)
925
+ # print(f"[配置] 已更新流式处理参数: chunk_duration={args.chunk_duration}s, overlap_duration={args.overlap_duration}s\n")
926
+
927
+ start_time = time.time()
928
+ try:
929
+ # 流式处理模式
930
+ print("使用流式处理模式(包含TTS)...")
931
+ print("="*70 + "\n")
932
+
933
+ # 计算chunk_size以匹配chunk_duration
934
+ chunk_size = int(args.chunk_duration * args.target_sr)
935
+ results = pipeline.process_long_audio_stream(args.audio_file, chunk_size=chunk_size)
936
+
937
+ print("\n" + "="*70)
938
+ print(" 处理完成")
939
+ print("="*70)
940
+ print(f"\n 成功处理 {len(results)} 个有效翻译段落\n")
941
+
942
+ # 显示所有结果
943
+ if results:
944
+ print("所有翻译结果:")
945
+ print("-" * 70)
946
+ for idx, result in enumerate(results, 1):
947
+ print(f"\n【段落 {idx}】(ID: {result['segment_id']})")
948
+ print(f" 原文: {result['original']}")
949
+ print(f" 译文: {result['translated']}")
950
+ print(f" 音频: {result['audio_path']}")
951
+ print(f" 时间: {time.strftime('%H:%M:%S', time.localtime(result['timestamp']))}")
952
+ print("-" * 70)
953
+
954
+ # 保存结果到文件
955
+ result_file = os.path.join(args.output_dir, "stream_results.txt")
956
+ with open(result_file, 'w', encoding='utf-8') as f:
957
+ f.write(f"流式翻译+TTS结果 - {args.audio_file}\n")
958
+ f.write(f"处理时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
959
+ f.write(f"音频块时长: {args.chunk_duration}秒, 重叠时长: {args.overlap_duration}秒\n")
960
+ f.write("="*70 + "\n\n")
961
+ for idx, result in enumerate(results, 1):
962
+ f.write(f"【段落 {idx}】(ID: {result['segment_id']})\n")
963
+ f.write(f"原文: {result['original']}\n")
964
+ f.write(f"译文: {result['translated']}\n")
965
+ f.write(f"音频: {result['audio_path']}\n")
966
+ f.write(f"时间: {time.strftime('%H:%M:%S', time.localtime(result['timestamp']))}\n")
967
+ f.write("\n" + "-"*70 + "\n\n")
968
+ print(f"\n✓ 结果已保存到: {result_file}")
969
+
970
+ # 统计音频文件
971
+ audio_files = [r['audio_path'] for r in results]
972
+ print(f"\n 生成 {len(audio_files)} 个TTS音频文件:")
973
+ for audio_file in audio_files:
974
+ print(f" - {audio_file}")
975
+ else:
976
+ print("\n 未获取到有效的翻译结果")
977
+
978
+ print("="*70)
979
+
980
+ # 总耗时
981
+ total_time = time.time() - start_time
982
+ print(f"\n总处理时间: {total_time:.2f} 秒")
983
+
984
+ except Exception as e:
985
+ print(f"Pipeline执行失败: {e}")
986
+ import traceback
987
+ traceback.print_exc()
988
+
989
+ if __name__ == "__main__":
990
+ main()
991
+