This commit is contained in:
Alireza Jahanshahlou 2025-10-17 00:12:20 +03:30
parent fe83c50d89
commit 69d722599b
5 changed files with 80 additions and 80 deletions

View file

@ -5,7 +5,7 @@ from config.manage_api_client import init_service, get_server_config, get_agent_
def get_project_dir():
"""获取项目根目录"""
"""Get the project root directory"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
@ -16,10 +16,10 @@ def read_config(config_path):
def load_config():
"""加载配置文件"""
"""Load configuration file"""
from core.utils.cache.manager import cache_manager, CacheType
# 检查缓存
# Check cache
cached_config = cache_manager.get(CacheType.CONFIG, "main_config")
if cached_config is not None:
return cached_config
@ -27,29 +27,29 @@ def load_config():
default_config_path = get_project_dir() + "config.yaml"
custom_config_path = get_project_dir() + "data/.config.yaml"
# 加载默认配置
# Load default configuration
default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path)
if custom_config.get("manager-api", {}).get("url"):
config = get_config_from_api(custom_config)
else:
# 合并配置
# Merge configuration
config = merge_configs(default_config, custom_config)
# 初始化目录
# Initialization directory
ensure_directories(config)
# 缓存配置
# Cache configuration
cache_manager.set(CacheType.CONFIG, "main_config", config)
return config
def get_config_from_api(config):
"""从Java API获取配置"""
# 初始化API客户端
"""Get configuration from Java API"""
# Initialize api client
init_service(config)
# 获取服务器配置
# Get server configuration
config_data = get_server_config()
if config_data is None:
raise Exception("Failed to fetch server config from API")
@ -59,7 +59,7 @@ def get_config_from_api(config):
"url": config["manager-api"].get("url", ""),
"secret": config["manager-api"].get("secret", ""),
}
# server的配置以本地为准
# Server configuration is subject to local
if config.get("server"):
config_data["server"] = {
"ip": config["server"].get("ip", ""),
@ -72,19 +72,19 @@ def get_config_from_api(config):
def get_private_config_from_api(config, device_id, client_id):
"""从Java API获取私有配置"""
"""Get private configuration from Java API"""
return get_agent_models(device_id, client_id, config["selected_module"])
def ensure_directories(config):
"""确保所有配置路径存在"""
"""Make sure all configuration paths exist"""
dirs_to_create = set()
project_dir = get_project_dir() # 获取项目根目录
# 日志文件目录
project_dir = get_project_dir() # Get the project root directory
# Log file directory
log_dir = config.get("log", {}).get("log_dir", "tmp")
dirs_to_create.add(os.path.join(project_dir, log_dir))
# ASR/TTS模块输出目录
# ASR/Tts module output directory
for module in ["ASR", "TTS"]:
if config.get(module) is None:
continue
@ -93,7 +93,7 @@ def ensure_directories(config):
if output_dir:
dirs_to_create.add(output_dir)
# 根据selected_module创建模型目录
# Create a model directory based on selected module
selected_modules = config.get("selected_module", {})
for module_type in ["ASR", "LLM", "TTS"]:
selected_provider = selected_modules.get(module_type)
@ -109,24 +109,24 @@ def ensure_directories(config):
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
# 统一创建目录(保留原data目录创建)
# Create a unified directory (retain the original data directory creation)
for dir_path in dirs_to_create:
try:
os.makedirs(dir_path, exist_ok=True)
except PermissionError:
print(f"警告:无法创建目录 {dir_path},请检查写入权限")
print(f"Warning: Unable to create directory {dir_path}, please check write permissions")
def merge_configs(default_config, custom_config):
"""
递归合并配置,custom_config优先级更高
Recursively merge configurations, custom_config has higher priority
Args:
default_config: 默认配置
custom_config: 用户自定义配置
default_config: default configuration
custom_config: user-defined configuration
Returns:
合并后的配置
Merged configuration
"""
if not isinstance(default_config, Mapping) or not isinstance(
custom_config, Mapping

View file

@ -10,8 +10,8 @@ _logger_initialized = False
def get_module_abbreviation(module_name, module_dict):
"""获取模块名称的缩写,如果为空则返回00
如果名称中包含下划线,则返回下划线后面的前两个字符
"""Get the abbreviation of the module name, or 00 if empty
If the name contains an underscore, returns the first two characters after the underscore
"""
module_value = module_dict.get(module_name, "")
if not module_value:
@ -23,7 +23,7 @@ def get_module_abbreviation(module_name, module_dict):
def build_module_string(selected_module):
"""构建模块字符串"""
"""Building module string"""
return (
get_module_abbreviation("VAD", selected_module)
+ get_module_abbreviation("ASR", selected_module)
@ -36,25 +36,25 @@ def build_module_string(selected_module):
def formatter(record):
"""为没有 tag 的日志添加默认值,并处理动态模块字符串"""
"""Add default values ​​for logs without tags and handle dynamic module strings"""
record["extra"].setdefault("tag", record["name"])
# 如果没有设置 selected_module,使用默认值
# If selected_module is not set, the default value is used
record["extra"].setdefault("selected_module", "00000000000000")
# 将 selected_module 从 extra 提取到顶级,以支持 {selected_module} 格式
# Extract selected_module from extra to top level to support {selected_module} format
record["selected_module"] = record["extra"]["selected_module"]
return record["message"]
def setup_logging():
check_config_file()
"""从配置文件中读取日志配置,并设置日志输出格式和级别"""
"""Read the log configuration from the configuration file and set the log output format and level"""
config = load_config()
log_config = config["log"]
global _logger_initialized
# 第一次初始化时配置日志
# Configure logs on first initialization
if not _logger_initialized:
# 使用默认的模块字符串进行初始化
# Initialize with default module string
logger.configure(
extra={
"selected_module": log_config.get("selected_module", "00000000000000"),
@ -80,35 +80,35 @@ def setup_logging():
os.makedirs(log_dir, exist_ok=True)
os.makedirs(data_dir, exist_ok=True)
# 配置日志输出
# Configure log output
logger.remove()
# 输出到控制台
# output to console
logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
# 输出到文件 - 统一目录,按大小轮转
# 日志文件完整路径
# Output to file -unified directory, rotate by size
# Log file full path
log_file_path = os.path.join(log_dir, log_file)
# 添加日志处理器
# Add log handler
logger.add(
log_file_path,
format=log_format_file,
level=log_level,
filter=formatter,
rotation="10 MB", # 每个文件最大10MB
retention="30 days", # 保留30天
rotation="10 MB", # Maximum 10 mb per file
retention="30 days", # Keep for 30 days
compression=None,
encoding="utf-8",
enqueue=True, # 异步安全
enqueue=True, # Async safety
backtrace=True,
diagnose=True,
)
_logger_initialized = True # 标记为已初始化
_logger_initialized = True # Mark as initialized
return logger
def create_connection_logger(selected_module_str):
"""为连接创建独立的日志器,绑定特定的模块字符串"""
"""Create a separate logger for the connection, binding a specific module string"""
return logger.bind(selected_module=selected_module_str)

View file

@ -15,7 +15,7 @@ class DeviceNotFoundException(Exception):
class DeviceBindException(Exception):
def __init__(self, bind_code):
self.bind_code = bind_code
super().__init__(f"设备绑定异常,绑定码: {bind_code}")
super().__init__(f"Device binding exception, binding code: {bind_code}")
class ManageApiClient:
@ -24,7 +24,7 @@ class ManageApiClient:
_secret = None
def __new__(cls, config):
"""单例模式确保全局唯一实例,并支持传入配置参数"""
"""Singleton mode ensures a globally unique instance and supports passing in configuration parameters"""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._init_client(config)
@ -32,23 +32,23 @@ class ManageApiClient:
@classmethod
def _init_client(cls, config):
"""初始化持久化连接池"""
"""Initialize the persistent connection pool"""
cls.config = config.get("manager-api")
if not cls.config:
raise Exception("manager-api配置错误")
raise Exception("Manager api configuration error")
if not cls.config.get("url") or not cls.config.get("secret"):
raise Exception("manager-api的url或secret配置错误")
raise Exception("Manager api url or secret configuration error")
if "你" in cls.config.get("secret"):
raise Exception("请先配置manager-api的secret")
raise Exception("Please configure the secret of the manager api first")
cls._secret = cls.config.get("secret")
cls.max_retries = cls.config.get("max_retries", 6) # 最大重试次数
cls.retry_delay = cls.config.get("retry_delay", 10) # 初始重试延迟(秒)
# NOTE(goody): 2025/4/16 http相关资源统一管理,后续可以增加线程池或者超时
# 后续也可以统一配置apiToken之类的走通用的Auth
cls.max_retries = cls.config.get("max_retries", 6) # Maximum number of retries
cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay (seconds)
# NOTE(goody): 2025/4/16 http-related resources are managed in a unified manner, and thread pools or timeouts can be added later.
# In the future, you can also uniformly configure api token and other common auth.
cls._client = httpx.Client(
base_url=cls.config.get("url"),
headers={
@ -56,39 +56,39 @@ class ManageApiClient:
"Accept": "application/json",
"Authorization": "Bearer " + cls._secret,
},
timeout=cls.config.get("timeout", 30), # 默认超时时间30秒
timeout=cls.config.get("timeout", 30), # Default timeout is 30 seconds
)
@classmethod
def _request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""发送单次HTTP请求并处理响应"""
"""Send a single http request and process the response"""
endpoint = endpoint.lstrip("/")
response = cls._client.request(method, endpoint, **kwargs)
response.raise_for_status()
result = response.json()
# 处理API返回的业务错误
# Handle business errors returned by api
if result.get("code") == 10041:
raise DeviceNotFoundException(result.get("msg"))
elif result.get("code") == 10042:
raise DeviceBindException(result.get("msg"))
elif result.get("code") != 0:
raise Exception(f"API返回错误: {result.get('msg', '未知错误')}")
raise Exception(f"API returns error: {result.get('msg', 'unknown error')}")
# 返回成功数据
# Return success data
return result.get("data") if result.get("code") == 0 else None
@classmethod
def _should_retry(cls, exception: Exception) -> bool:
"""判断异常是否应该重试"""
# 网络连接相关错误
"""Determine whether the exception should be retried"""
# Network connection related errors
if isinstance(
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError)
):
return True
# HTTP状态码错误
# Http status code error
if isinstance(exception, httpx.HTTPStatusError):
status_code = exception.response.status_code
return status_code in [408, 429, 500, 502, 503, 504]
@ -97,43 +97,43 @@ class ManageApiClient:
@classmethod
def _execute_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
"""带重试机制的请求执行器"""
"""Request executor with retry mechanism"""
retry_count = 0
while retry_count <= cls.max_retries:
try:
# 执行请求
# Execute request
return cls._request(method, endpoint, **kwargs)
except Exception as e:
# 判断是否应该重试
# Determine whether you should try again
if retry_count < cls.max_retries and cls._should_retry(e):
retry_count += 1
print(
f"{method} {endpoint} 请求失败,将在 {cls.retry_delay:.1f} 秒后进行第 {retry_count} 次重试"
f"{method} {endpoint} request failed, will be retried {retry_count} times after {cls.retry_delay:.1f} seconds"
)
time.sleep(cls.retry_delay)
continue
else:
# 不重试,直接抛出异常
# Without retrying, an exception is thrown directly.
raise
@classmethod
def safe_close(cls):
"""安全关闭连接池"""
"""Safely close the connection pool"""
if cls._client:
cls._client.close()
cls._instance = None
def get_server_config() -> Optional[Dict]:
"""获取服务器基础配置"""
"""Get basic server configuration"""
return ManageApiClient._instance._execute_request("POST", "/config/server-base")
def get_agent_models(
mac_address: str, client_id: str, selected_module: Dict
) -> Optional[Dict]:
"""获取代理模型配置"""
"""Get proxy model configuration"""
return ManageApiClient._instance._execute_request(
"POST",
"/config/agent-models",
@ -155,14 +155,14 @@ def save_mem_local_short(mac_address: str, short_momery: str) -> Optional[Dict]:
},
)
except Exception as e:
print(f"存储短期记忆到服务器失败: {e}")
print(f"Failed to store short-term memory to server: {e}")
return None
def report(
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]:
"""带熔断的业务方法示例"""
"""Business method example with circuit breakers"""
if not content or not ManageApiClient._instance:
return None
try:
@ -181,7 +181,7 @@ def report(
},
)
except Exception as e:
print(f"TTS上报失败: {e}")
print(f"Tts reporting failed: {e}")
return None

View file

@ -11,23 +11,23 @@ def check_config_file():
if config_file_valid:
return
"""
简化的配置检查,仅提示用户配置文件的使用情况
Simplified configuration checks that only prompt users for profile usage
"""
custom_config_file = get_project_dir() + "data/." + default_config_file
if not os.path.exists(custom_config_file):
raise FileNotFoundError(
"找不到data/.config.yaml文件,请按教程确认该配置文件是否存在"
"The data/.config.yaml file cannot be found. Please follow the tutorial to confirm whether the configuration file exists."
)
# 检查是否从API读取配置
# Check if configuration is read from api
config = load_config()
if config.get("read_config_from_api", False):
print("从API读取配置")
print("Read configuration from api")
old_config_origin = read_config(custom_config_file)
if old_config_origin.get("selected_module") is not None:
error_msg = "您的配置文件好像既包含智控台的配置又包含本地配置:\n"
error_msg += "\n建议您:\n"
error_msg += "1、将根目录的config_from_api.yaml文件复制到data下,重命名为.config.yaml\n"
error_msg += "2、按教程配置好接口地址和密钥\n"
error_msg = "Your configuration file seems to contain both the smart console configuration and the local configuration:\n"
error_msg += "\N recommends that you:\n"
error_msg += "1. Copy the config from api.yaml file in the root directory to data and rename it to .config.yaml\n"
error_msg += "2. Configure the interface address and key according to the tutorial\n"
raise ValueError(error_msg)
config_file_valid = True

View file

@ -8,7 +8,7 @@ class BaseHandler:
self.logger = setup_logging()
def _add_cors_headers(self, response):
"""添加CORS头信息"""
"""Add cors header information"""
response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id"
)