liumaolin
commited on
Commit
·
84faf7d
1
Parent(s):
d08a15b
Refactor `main.py`: remove redundant code, modularize functionality, and set multiprocessing to `spawn` for PyInstaller compatibility.
Browse files
main.py
CHANGED
@@ -1,311 +1,56 @@
|
|
1 |
-
import
|
|
|
2 |
import sys
|
3 |
-
import time
|
4 |
import typing
|
5 |
from pathlib import Path
|
6 |
-
import multiprocessing
|
7 |
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
HERE = Path(__file__).parent
|
11 |
lib_path = HERE / "src"
|
12 |
if lib_path.exists() and lib_path.as_posix() not in sys.path:
|
13 |
sys.path.insert(0, lib_path.as_posix())
|
14 |
|
15 |
-
from voice_dialogue.core.
|
16 |
-
|
17 |
-
|
18 |
-
transcribed_text_queue,
|
19 |
-
text_input_queue,
|
20 |
-
audio_output_queue
|
21 |
-
)
|
22 |
-
from voice_dialogue.services.audio.capture import EchoCancellingAudioCapture
|
23 |
-
from voice_dialogue.services.audio.generator import TTSAudioGenerator
|
24 |
-
from voice_dialogue.services.audio.generators.models import tts_config_registry
|
25 |
-
from voice_dialogue.services.audio.player import AudioStreamPlayer
|
26 |
-
from voice_dialogue.services.speech.monitor import SpeechStateMonitor
|
27 |
-
from voice_dialogue.services.speech.recognizer import ASRWorker
|
28 |
-
from voice_dialogue.services.text.generator import LLMResponseGenerator
|
29 |
|
30 |
language: typing.Literal['zh', 'en'] = 'en'
|
31 |
|
32 |
|
33 |
-
def launch_system(
|
34 |
-
user_language: str,
|
35 |
-
speaker: str
|
36 |
-
) -> None:
|
37 |
-
"""
|
38 |
-
启动完整的语音对话系统
|
39 |
-
|
40 |
-
该函数负责启动并协调语音对话系统的所有组件,包括音频采集、语音识别、
|
41 |
-
文本生成、语音合成和音频播放等功能模块。系统采用多线程架构,各组件
|
42 |
-
通过队列进行数据传递和通信。
|
43 |
-
|
44 |
-
系统工作流程:
|
45 |
-
1. 音频采集:EchoCancellingAudioCapture 采集用户语音并进行回声消除
|
46 |
-
2. 语音监测:SpeechStateMonitor 检测用户是否在说话
|
47 |
-
3. 语音识别:ASRWorker 将用户语音转换为文本
|
48 |
-
4. 文本生成:LLMResponseGenerator 基于用户问题生成AI回答
|
49 |
-
5. 语音合成:TTSAudioGenerator 将AI回答转换为语音
|
50 |
-
6. 音频播放:AudioStreamPlayer 播放生成的语音
|
51 |
-
|
52 |
-
Args:
|
53 |
-
user_language (str): 用户语言,支持 'zh'(中文)和 'en'(英文)
|
54 |
-
speaker (str): 语音合成使用的说话人,支持:
|
55 |
-
'罗翔', '马保国', '沈逸', '杨幂', '周杰伦', '马云'
|
56 |
-
|
57 |
-
Raises:
|
58 |
-
ValueError: 当指定的说话人不在支持列表中时抛出异常
|
59 |
-
|
60 |
-
Returns:
|
61 |
-
None: 函数会一直运行直到所有线程结束
|
62 |
-
|
63 |
-
Note:
|
64 |
-
该函数会阻塞运行,直到系统被外部停止或发生异常
|
65 |
-
"""
|
66 |
-
|
67 |
-
threads = []
|
68 |
-
#
|
69 |
-
audio_frame_probe = EchoCancellingAudioCapture(audio_frames_queue=audio_frames_queue)
|
70 |
-
audio_frame_probe.start()
|
71 |
-
threads.append(audio_frame_probe)
|
72 |
-
|
73 |
-
#
|
74 |
-
user_voice_checker = SpeechStateMonitor(
|
75 |
-
audio_frame_queue=audio_frames_queue,
|
76 |
-
user_voice_queue=user_voice_queue,
|
77 |
-
)
|
78 |
-
user_voice_checker.start()
|
79 |
-
threads.append(user_voice_checker)
|
80 |
-
|
81 |
-
#
|
82 |
-
whisper_worker = ASRWorker(
|
83 |
-
user_voice_queue=user_voice_queue, transcribed_text_queue=transcribed_text_queue,
|
84 |
-
language=user_language
|
85 |
-
)
|
86 |
-
whisper_worker.start()
|
87 |
-
threads.append(whisper_worker)
|
88 |
-
|
89 |
-
answer_generator_worker = LLMResponseGenerator(
|
90 |
-
user_question_queue=transcribed_text_queue,
|
91 |
-
generated_answer_queue=text_input_queue
|
92 |
-
)
|
93 |
-
answer_generator_worker.start()
|
94 |
-
threads.append(answer_generator_worker)
|
95 |
-
|
96 |
-
# 动态获取TTS配置,而不是使用固定映射
|
97 |
-
tts_speaker_config = _get_tts_config_by_speaker_name(speaker)
|
98 |
-
if tts_speaker_config is None:
|
99 |
-
# 如果找不到指定说话人,列出所有可用说话人并抛出异常
|
100 |
-
available_speakers = _get_available_speaker_names()
|
101 |
-
raise ValueError(f"不支持的TTS说话人: {speaker}。可用说话人: {', '.join(available_speakers)}")
|
102 |
-
|
103 |
-
audio_generator_worker = TTSAudioGenerator(
|
104 |
-
text_input_queue=text_input_queue,
|
105 |
-
audio_output_queue=audio_output_queue,
|
106 |
-
tts_config=tts_speaker_config
|
107 |
-
)
|
108 |
-
audio_generator_worker.start()
|
109 |
-
threads.append(audio_generator_worker)
|
110 |
-
|
111 |
-
audio_playing_worker = AudioStreamPlayer(audio_playing_queue=audio_output_queue)
|
112 |
-
audio_playing_worker.start()
|
113 |
-
threads.append(audio_playing_worker)
|
114 |
-
|
115 |
-
while not all([thread.is_ready for thread in threads]):
|
116 |
-
time.sleep(0.1)
|
117 |
-
|
118 |
-
# audio_frame_probe.start_record()
|
119 |
-
print(f'{"=" * 80}\n服务启动成功\n{"=" * 80}')
|
120 |
-
for thread in threads:
|
121 |
-
thread.join()
|
122 |
-
|
123 |
-
|
124 |
-
def _get_tts_config_by_speaker_name(speaker_name: str):
|
125 |
-
"""
|
126 |
-
根据说话人名称获取TTS配置
|
127 |
-
|
128 |
-
支持中文名称和英文名称,优先匹配中文名称映射,
|
129 |
-
如果找不到则直接使用英文名称搜索
|
130 |
-
|
131 |
-
Args:
|
132 |
-
speaker_name (str): 说话人名称
|
133 |
-
|
134 |
-
Returns:
|
135 |
-
BaseTTSConfig: TTS配置,如果找不到则返回None
|
136 |
-
"""
|
137 |
-
# 中文名称到英文名称的映射(保持向后兼容)
|
138 |
-
chinese_to_english_mapping = {
|
139 |
-
'罗翔': 'Luo Xiang',
|
140 |
-
'马保国': 'Ma Baoguo',
|
141 |
-
'沈逸': 'Shen Yi',
|
142 |
-
'杨幂': 'Yang Mi',
|
143 |
-
'周杰伦': 'Zhou Jielun',
|
144 |
-
'马云': 'Ma Yun',
|
145 |
-
}
|
146 |
-
|
147 |
-
# 首先尝试中文名称映射
|
148 |
-
english_name = chinese_to_english_mapping.get(speaker_name, speaker_name)
|
149 |
-
|
150 |
-
# 获取所有可用配置
|
151 |
-
all_configs = tts_config_registry.get_all_configs()
|
152 |
-
|
153 |
-
# 搜索匹配的配置
|
154 |
-
for config in all_configs:
|
155 |
-
if config.character_name == english_name:
|
156 |
-
return config
|
157 |
-
|
158 |
-
# 如果通过映射找不到,尝试直接匹配输入的名称
|
159 |
-
if speaker_name != english_name:
|
160 |
-
for config in all_configs:
|
161 |
-
if config.character_name == speaker_name:
|
162 |
-
return config
|
163 |
-
|
164 |
-
return None
|
165 |
-
|
166 |
-
|
167 |
-
def _get_available_speaker_names():
|
168 |
-
"""
|
169 |
-
获取所有可用的说话人名称列表
|
170 |
-
|
171 |
-
Returns:
|
172 |
-
list[str]: 包含中文显示名称和英文原始名称的列表
|
173 |
-
"""
|
174 |
-
# 中文显示名称映射
|
175 |
-
english_to_chinese_mapping = {
|
176 |
-
'Luo Xiang': '罗翔',
|
177 |
-
'Ma Baoguo': '马保国',
|
178 |
-
'Shen Yi': '沈逸',
|
179 |
-
'Yang Mi': '杨幂',
|
180 |
-
'Zhou Jielun': '周杰伦',
|
181 |
-
'Ma Yun': '马云',
|
182 |
-
}
|
183 |
-
|
184 |
-
all_configs = tts_config_registry.get_all_configs()
|
185 |
-
speaker_names = []
|
186 |
-
|
187 |
-
for config in all_configs:
|
188 |
-
# 优先显示中文名称
|
189 |
-
chinese_name = english_to_chinese_mapping.get(config.character_name)
|
190 |
-
if chinese_name:
|
191 |
-
speaker_names.append(chinese_name)
|
192 |
-
else:
|
193 |
-
# 如果没有中文映射,使用英文原名
|
194 |
-
speaker_names.append(config.character_name)
|
195 |
-
|
196 |
-
return sorted(speaker_names)
|
197 |
-
|
198 |
-
|
199 |
-
def _update_argument_parser_speaker_choices():
|
200 |
-
"""
|
201 |
-
动态更新命令行参数解析器中的说话人选项
|
202 |
-
|
203 |
-
Returns:
|
204 |
-
list[str]: 可用的说话人选择列表
|
205 |
-
"""
|
206 |
-
return _get_available_speaker_names()
|
207 |
-
|
208 |
-
|
209 |
-
def create_argument_parser():
|
210 |
-
"""创建命令行参数解析器"""
|
211 |
-
# 动态获取可用说话人列表
|
212 |
-
available_speakers = _update_argument_parser_speaker_choices()
|
213 |
-
|
214 |
-
parser = argparse.ArgumentParser(
|
215 |
-
description="VoiceDialogue - 语音对话系统",
|
216 |
-
formatter_class=argparse.RawDescriptionHelpFormatter,
|
217 |
-
epilog=f"""
|
218 |
-
示例用法:
|
219 |
-
# 启动命令行模式(默认)
|
220 |
-
python main.py
|
221 |
-
|
222 |
-
# 启动命令行模式并指定参数
|
223 |
-
python main.py --mode cli --language zh --speaker 沈逸
|
224 |
-
|
225 |
-
# 启动API服务器
|
226 |
-
python main.py --mode api
|
227 |
-
|
228 |
-
# 启动API服务器并指定端口
|
229 |
-
python main.py --mode api --port 9000
|
230 |
-
|
231 |
-
# 启动API服务器并启用热重载(开发模式)
|
232 |
-
python main.py --mode api --port 8000 --reload
|
233 |
-
|
234 |
-
支持的说话人:
|
235 |
-
{', '.join(available_speakers)}
|
236 |
-
"""
|
237 |
-
)
|
238 |
-
|
239 |
-
# 运行模式选择
|
240 |
-
parser.add_argument(
|
241 |
-
'--mode', '-m',
|
242 |
-
choices=['cli', 'api'],
|
243 |
-
default='cli',
|
244 |
-
help='运行模式: cli=命令行模式, api=API服务器模式 (默认: cli)'
|
245 |
-
)
|
246 |
-
|
247 |
-
# 命令行模式参数
|
248 |
-
cli_group = parser.add_argument_group('命令行模式参数')
|
249 |
-
cli_group.add_argument(
|
250 |
-
'--language', '-l',
|
251 |
-
choices=['zh', 'en'],
|
252 |
-
default='zh',
|
253 |
-
help='用户语言: zh=中文, en=英文 (默认: zh)'
|
254 |
-
)
|
255 |
-
cli_group.add_argument(
|
256 |
-
'--speaker', '-s',
|
257 |
-
choices=available_speakers,
|
258 |
-
default='沈逸' if '沈逸' in available_speakers else (available_speakers[0] if available_speakers else '沈逸'),
|
259 |
-
help='TTS说话人 (默认: 沈逸)'
|
260 |
-
)
|
261 |
-
|
262 |
-
# API服务器模式参数
|
263 |
-
api_group = parser.add_argument_group('API服务器模式参数')
|
264 |
-
api_group.add_argument(
|
265 |
-
'--host',
|
266 |
-
default='0.0.0.0',
|
267 |
-
help='服务器主机地址 (默认: 0.0.0.0)'
|
268 |
-
)
|
269 |
-
api_group.add_argument(
|
270 |
-
'--port', '-p',
|
271 |
-
type=int,
|
272 |
-
default=8000,
|
273 |
-
help='服务器端口 (默认: 8000)'
|
274 |
-
)
|
275 |
-
api_group.add_argument(
|
276 |
-
'--reload',
|
277 |
-
action='store_true',
|
278 |
-
help='启用热重载(开发模式)'
|
279 |
-
)
|
280 |
-
|
281 |
-
return parser
|
282 |
-
|
283 |
-
|
284 |
-
def launch_api_server(host: str = "0.0.0.0", port: int = 8000, reload: bool = False):
|
285 |
-
"""
|
286 |
-
启动API服务器
|
287 |
-
|
288 |
-
Args:
|
289 |
-
host (str): 服务器主机地址,默认为 "0.0.0.0"
|
290 |
-
port (int): 服务器端口,默认为 8000
|
291 |
-
reload (bool): 是否启用热重载,默认为 False
|
292 |
-
"""
|
293 |
-
print(f'{"=" * 80}\n正在启动API服务器...\n{"=" * 80}')
|
294 |
-
print(f"服务器地址: http://{host}:{port}")
|
295 |
-
print(f"API文档: http://{host}:{port}/docs")
|
296 |
-
print(f"热重载: {'启用' if reload else '禁用'}")
|
297 |
-
print(f'{"=" * 80}')
|
298 |
-
|
299 |
-
# 导入并启动FastAPI应用
|
300 |
-
uvicorn.run(
|
301 |
-
"voice_dialogue.api.app:app",
|
302 |
-
host=host,
|
303 |
-
port=port,
|
304 |
-
reload=reload,
|
305 |
-
log_level="info"
|
306 |
-
)
|
307 |
-
|
308 |
-
|
309 |
def main():
|
310 |
"""
|
311 |
主程序入口函数
|
@@ -347,5 +92,4 @@ VoiceDialogue - 语音对话系统
|
|
347 |
|
348 |
|
349 |
if __name__ == '__main__':
|
350 |
-
multiprocessing.freeze_support()
|
351 |
main()
|
|
|
1 |
+
import multiprocessing
|
2 |
+
import os
|
3 |
import sys
|
|
|
4 |
import typing
|
5 |
from pathlib import Path
|
|
|
6 |
|
7 |
+
if __name__ == '__main__':
|
8 |
+
if hasattr(sys, '_voice_dialogue_started'):
|
9 |
+
sys.exit(0)
|
10 |
+
sys._voice_dialogue_started = True
|
11 |
+
|
12 |
+
# 设置multiprocessing启动方法为spawn,避免fork问题
|
13 |
+
if hasattr(multiprocessing, 'set_start_method'):
|
14 |
+
try:
|
15 |
+
multiprocessing.set_start_method('spawn', force=True)
|
16 |
+
except RuntimeError:
|
17 |
+
pass
|
18 |
+
|
19 |
+
# Pyinstaller 多进程支持
|
20 |
+
multiprocessing.freeze_support()
|
21 |
+
|
22 |
+
# 禁用各种可能导致多进程问题的并行处理
|
23 |
+
os.environ.update({
|
24 |
+
"TOKENIZERS_PARALLELISM": "false",
|
25 |
+
# "OMP_NUM_THREADS": "1",
|
26 |
+
# "MKL_NUM_THREADS": "1",
|
27 |
+
# "NUMEXPR_NUM_THREADS": "1",
|
28 |
+
# "OPENBLAS_NUM_THREADS": "1",
|
29 |
+
# "VECLIB_MAXIMUM_THREADS": "1",
|
30 |
+
# "BLIS_NUM_THREADS": "1",
|
31 |
+
# # 禁用huggingface的多进程
|
32 |
+
# "HF_HUB_DISABLE_PROGRESS_BARS": "1",
|
33 |
+
# "TRANSFORMERS_NO_ADVISORY_WARNINGS": "1",
|
34 |
+
# # 禁用torch的多进程
|
35 |
+
# "TORCH_NUM_THREADS": "1",
|
36 |
+
# "PYTORCH_JIT": "0",
|
37 |
+
# # 禁用joblib的loky后端,使用threading
|
38 |
+
# "JOBLIB_START_METHOD": "threading",
|
39 |
+
# "SKLEARN_JOBLIB_START_METHOD": "threading",
|
40 |
+
})
|
41 |
|
42 |
HERE = Path(__file__).parent
|
43 |
lib_path = HERE / "src"
|
44 |
if lib_path.exists() and lib_path.as_posix() not in sys.path:
|
45 |
sys.path.insert(0, lib_path.as_posix())
|
46 |
|
47 |
+
from voice_dialogue.core.launcher import launch_system
|
48 |
+
from voice_dialogue.cli.args import create_argument_parser
|
49 |
+
from voice_dialogue.api.server import launch_api_server
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
language: typing.Literal['zh', 'en'] = 'en'
|
52 |
|
53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
def main():
|
55 |
"""
|
56 |
主程序入口函数
|
|
|
92 |
|
93 |
|
94 |
if __name__ == '__main__':
|
|
|
95 |
main()
|