xiaozhi-esp32-server/main/xiaozhi-server/config/config_loader.py
lapy 70771b4209 chore(westernization): translate remaining Han text across code, UI and docs
Final localization pass over everything the audit covers, driven by the
local qwen3.8:instruct endpoint (thinking disabled) with placeholder-
masked, cached, resumable batches:

- Python server: comments, docstrings, log/error messages, prompt text
- manager-api Java: javadoc, exception messages, Swagger summaries,
  westernized test fixtures (locale strings, signed-URL examples)
- manager-web / manager-mobile: component comments and misc leftovers
  (functional split regexes such as /[、;;,,]/ left byte-identical)
- digital-human: HTML/UI text, JS comments, wake-word defaults aligned
  with the server canonical English wake words
- docs: device-call guide, wakeword and search integration guides

Also widens the westernization audit exception to the whole vendored
generator bundle and retires the stale per-file exception list.
2026-10-11 17:58:15 +01:00

178 lines
5.8 KiB
Python

import os
import asyncio
import yaml
from collections.abc import Mapping
from config.manage_api_client import (
init_service,
get_server_config,
get_agent_models,
get_correct_words,
DeviceNotFoundException,
DeviceBindException,
)
def get_project_dir():
"""Get project root directory"""
return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + "/"
def read_config(config_path):
with open(config_path, "r", encoding="utf-8") as file:
config = yaml.safe_load(file)
return config
async def load_config():
"""Load config 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
default_config_path = get_project_dir() + "config.yaml"
custom_config_path = get_project_dir() + "data/.config.yaml"
# Load default config
default_config = read_config(default_config_path)
custom_config = read_config(custom_config_path)
if custom_config.get("manager-api", {}).get("url"):
config = await get_config_from_api_async(custom_config)
else:
# Merge config
config = merge_configs(default_config, custom_config)
# Initialize directory
ensure_directories(config)
# Cache config
cache_manager.set(CacheType.CONFIG, "main_config", config)
return config
async def get_config_from_api_async(config):
"""Fetch config from Java API (async version)"""
# Initialize API client
init_service(config)
# Get server config
config_data = await get_server_config()
if config_data is None:
raise Exception("Failed to fetch server config from API")
config_data["read_config_from_api"] = True
config_data["manager-api"] = {
"url": config["manager-api"].get("url", ""),
"secret": config["manager-api"].get("secret", ""),
}
auth_enabled = config_data.get("server", {}).get("auth", {}).get("enabled", False)
# Server config uses local values
if config.get("server"):
config_data["server"] = {
"ip": config["server"].get("ip", ""),
"port": config["server"].get("port", ""),
"http_port": config["server"].get("http_port", ""),
"vision_explain": config["server"].get("vision_explain", ""),
"auth_key": config["server"].get("auth_key", ""),
}
config_data["server"]["auth"] = {"enabled": auth_enabled}
# If the server lacks prompt_template, read from local config
if not config_data.get("prompt_template"):
config_data["prompt_template"] = config.get("prompt_template")
return config_data
async def get_private_config_from_api(config, device_id, client_id):
"""Fetch private config from Java API"""
results = await asyncio.gather(
get_agent_models(device_id, client_id, config["selected_module"]),
get_correct_words(device_id),
return_exceptions=True,
)
agent_result = results[0]
correct_words = results[1] if not isinstance(results[1], Exception) else None
# Throw business exception
if isinstance(agent_result, DeviceNotFoundException):
raise agent_result
if isinstance(agent_result, DeviceBindException):
raise agent_result
private_config = agent_result if not isinstance(agent_result, Exception) else {}
if correct_words:
private_config["correct_words"] = correct_words
return private_config
def ensure_directories(config):
"""Ensure all config paths exist"""
dirs_to_create = set()
project_dir = get_project_dir() # Get 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 module output directory
for module in ["ASR", "TTS"]:
if config.get(module) is None:
continue
for provider in config.get(module, {}).values():
output_dir = provider.get("output_dir", "")
if output_dir:
dirs_to_create.add(output_dir)
# Create 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)
if not selected_provider:
continue
if config.get(module_type) is None:
continue
if config.get(selected_provider) is None:
continue
provider_config = config.get(module_type, {}).get(selected_provider, {})
output_dir = provider_config.get("output_dir")
if output_dir:
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
# Create directories uniformly (retain original data directory creation)
for dir_path in dirs_to_create:
try:
os.makedirs(dir_path, exist_ok=True)
except PermissionError:
print(f"Warning: Unable to create directory {dir_path}. Please check write permissions.")
def merge_configs(default_config, custom_config):
"""
Recursively merge configs; custom_config takes precedence
Args:
default_config: default config
custom_config: User-defined configuration
Returns:
Merged configuration
"""
if not isinstance(default_config, Mapping) or not isinstance(
custom_config, Mapping
):
return custom_config
merged = dict(default_config)
for key, value in custom_config.items():
if (
key in merged
and isinstance(merged[key], Mapping)
and isinstance(value, Mapping)
):
merged[key] = merge_configs(merged[key], value)
else:
merged[key] = value
return merged