config_util.py
8.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AIfeng/2025-01-02 10:27:06
配置管理模块
提供系统配置的读取和管理功能
"""
import os
import json
from typing import Dict, Any, Optional
# 默认配置
DEFAULT_CONFIG = {
'source': {
'wake_word_enabled': False,
'wake_word': '小助手,你好',
'wake_word_type': 'common' # common 或 front
},
'audio': {
'sample_rate': 16000,
'channels': 1,
'chunk_size': 1024,
'device_index': None
},
'asr': {
'mode': 'funasr',
'timeout': 30,
'reconnect_delay': 1,
'max_reconnect_attempts': 5
},
'server': {
'host': '0.0.0.0',
'port': 5050,
'debug': False
},
'logging': {
'level': 'INFO',
'file': 'logs/system.log',
'max_size': 10485760, # 10MB
'backup_count': 5
}
}
# 配置文件路径
CONFIG_FILE = 'config.json'
# 全局配置对象
config = {}
# ASR相关配置
ASR_mode = "funasr" # 默认使用FunASR
local_asr_ip = "127.0.0.1"
local_asr_port = 10197
asr_timeout = 30
asr_reconnect_delay = 1
asr_max_reconnect_attempts = 5
# 服务器配置
fay_url = "http://localhost:5050"
def load_config(config_file: str = CONFIG_FILE) -> Dict[str, Any]:
"""
加载配置文件
Args:
config_file: 配置文件路径
Returns:
配置字典
"""
global config
try:
if os.path.exists(config_file):
with open(config_file, 'r', encoding='utf-8') as f:
loaded_config = json.load(f)
# 合并默认配置和加载的配置
config = merge_config(DEFAULT_CONFIG, loaded_config)
print(f"配置文件已加载: {config_file}")
else:
# 使用默认配置
config = DEFAULT_CONFIG.copy()
print(f"配置文件不存在,使用默认配置: {config_file}")
# 保存默认配置到文件
save_config(config_file)
except Exception as e:
print(f"加载配置文件时出错: {e}")
config = DEFAULT_CONFIG.copy()
# 更新全局变量
update_global_vars()
return config
def save_config(config_file: str = CONFIG_FILE, config_data: Optional[Dict[str, Any]] = None) -> bool:
"""
保存配置到文件
Args:
config_file: 配置文件路径
config_data: 要保存的配置数据,如果为None则使用全局config
Returns:
是否保存成功
"""
try:
data_to_save = config_data if config_data is not None else config
with open(config_file, 'w', encoding='utf-8') as f:
json.dump(data_to_save, f, ensure_ascii=False, indent=2)
print(f"配置已保存到: {config_file}")
return True
except Exception as e:
print(f"保存配置文件时出错: {e}")
return False
def merge_config(default: Dict[str, Any], loaded: Dict[str, Any]) -> Dict[str, Any]:
"""
合并配置字典
Args:
default: 默认配置
loaded: 加载的配置
Returns:
合并后的配置
"""
result = default.copy()
for key, value in loaded.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key] = merge_config(result[key], value)
else:
result[key] = value
return result
def update_global_vars():
"""
更新全局变量
"""
global ASR_mode, local_asr_ip, local_asr_port
global asr_timeout, asr_reconnect_delay, asr_max_reconnect_attempts
global fay_url
# ASR配置
asr_config = config.get('asr', {})
ASR_mode = asr_config.get('mode', 'funasr')
asr_timeout = asr_config.get('timeout', 30)
asr_reconnect_delay = asr_config.get('reconnect_delay', 1)
asr_max_reconnect_attempts = asr_config.get('max_reconnect_attempts', 5)
# 服务器配置
server_config = config.get('server', {})
server_port = server_config.get('port', 5050)
fay_url = f"http://localhost:{server_port}"
def get_config(key_path: str, default_value: Any = None) -> Any:
"""
获取配置值
Args:
key_path: 配置键路径,使用点号分隔,如 'audio.sample_rate'
default_value: 默认值
Returns:
配置值
"""
keys = key_path.split('.')
value = config
try:
for key in keys:
value = value[key]
return value
except (KeyError, TypeError):
return default_value
def set_config(key_path: str, value: Any) -> bool:
"""
设置配置值
Args:
key_path: 配置键路径,使用点号分隔
value: 要设置的值
Returns:
是否设置成功
"""
keys = key_path.split('.')
try:
current = config
for key in keys[:-1]:
if key not in current:
current[key] = {}
current = current[key]
current[keys[-1]] = value
# 更新全局变量
update_global_vars()
return True
except Exception as e:
print(f"设置配置值时出错: {e}")
return False
def get_audio_config() -> Dict[str, Any]:
"""
获取音频配置
Returns:
音频配置字典
"""
return config.get('audio', DEFAULT_CONFIG['audio'])
def get_asr_config() -> Dict[str, Any]:
"""
获取ASR配置
Returns:
ASR配置字典
"""
return config.get('asr', DEFAULT_CONFIG['asr'])
def get_server_config() -> Dict[str, Any]:
"""
获取服务器配置
Returns:
服务器配置字典
"""
return config.get('server', DEFAULT_CONFIG['server'])
def is_wake_word_enabled() -> bool:
"""
检查是否启用唤醒词
Returns:
是否启用唤醒词
"""
return config.get('source', {}).get('wake_word_enabled', False)
def get_wake_words() -> list:
"""
获取唤醒词列表
Returns:
唤醒词列表
"""
wake_word = config.get('source', {}).get('wake_word', '小助手,你好')
return [word.strip() for word in wake_word.split(',') if word.strip()]
def get_wake_word_type() -> str:
"""
获取唤醒词类型
Returns:
唤醒词类型 ('common' 或 'front')
"""
return config.get('source', {}).get('wake_word_type', 'common')
def validate_config() -> list:
"""
验证配置的有效性
Returns:
错误信息列表
"""
errors = []
# 验证音频配置
audio_config = get_audio_config()
if audio_config.get('sample_rate', 0) <= 0:
errors.append("音频采样率必须大于0")
if audio_config.get('channels', 0) <= 0:
errors.append("音频声道数必须大于0")
if audio_config.get('chunk_size', 0) <= 0:
errors.append("音频块大小必须大于0")
# 验证ASR配置
asr_config = get_asr_config()
if asr_config.get('timeout', 0) <= 0:
errors.append("ASR超时时间必须大于0")
# 验证服务器配置
server_config = get_server_config()
port = server_config.get('port', 0)
if not (1 <= port <= 65535):
errors.append("服务器端口必须在1-65535范围内")
return errors
def print_config():
"""
打印当前配置
"""
print("当前配置:")
print(json.dumps(config, ensure_ascii=False, indent=2))
print("\n全局变量:")
print(f"ASR_mode: {ASR_mode}")
print(f"local_asr_ip: {local_asr_ip}")
print(f"local_asr_port: {local_asr_port}")
print(f"asr_timeout: {asr_timeout}")
print(f"fay_url: {fay_url}")
# 初始化配置
load_config()
if __name__ == "__main__":
# 测试配置功能
print("配置模块测试")
print_config()
# 验证配置
errors = validate_config()
if errors:
print("\n配置验证错误:")
for error in errors:
print(f" - {error}")
else:
print("\n配置验证通过")