From feb6edb47fe883a354a2f11f775be2712cc9eb08 Mon Sep 17 00:00:00 2001 From: lapy Date: Sun, 11 Oct 2026 13:13:07 +0100 Subject: [PATCH] fix(westernization): runtime English surface, voiceprint truth, CI gates Server runtime: - translate model-visible strings: direct_answer tool schema, web_search tool desc/errors/results, call_device tool desc/replies, hass_state desc/report strings; they were Chinese text fed to LLMs and devices - replace Chinese pconline geocoder with ip-api.com (English city names) - prompt_manager: drop dead Chinese WEEKDAY_MAP, stop forcing lang=zh_CN for weather, English fallback location - delete orphan alibl_endpoint.py (no importers after AliBL removal) and dead initialize_voiceprint() calling a nonexistent ASR hook - translate mcp_server_settings.json descriptors - test_current_time: assert English weekday/date behavior (upstream test still expected Chinese weekdays) Docs/branding: - README and docs/guides/voiceprint.md: voiceprint IS implemented via the HTTP VoiceprintProvider; document the real protocol (health/identify) and privacy notes instead of falsely claiming the feature is missing - issue templates: English Ops: - Dockerfile-server-base: drop Aliyun PyPI mirror from published image - LICENSE: keep xinnan-tech copyright notice alongside downstream (MIT) - CI: run westernization_audit as a gate; make smoke test failure fatal - westernization.md: point python verification at the real pytest layout --- .github/ISSUE_TEMPLATE/bug_report.md | 41 ++-- .github/ISSUE_TEMPLATE/code_improvement.md | 22 +-- .../documentation_improvement.md | 18 +- .github/ISSUE_TEMPLATE/feature_request.md | 22 +-- .github/workflows/test.yml | 15 +- Dockerfile-server-base | 6 +- LICENSE | 3 +- README.md | 2 +- docs/features/integrations.md | 4 +- docs/guides/voiceprint.md | 175 ++++++------------ main/xiaozhi-server/core/connection.py | 10 +- .../core/utils/alibl_endpoint.py | 48 ----- .../core/utils/modules_initialize.py | 21 --- .../core/utils/prompt_manager.py | 16 +- main/xiaozhi-server/core/utils/util.py | 9 +- main/xiaozhi-server/mcp_server_settings.json | 14 +- .../plugins_func/functions/call_device.py | 48 ++--- .../plugins_func/functions/hass_state.py | 4 +- .../plugins_func/functions/web_search.py | 86 ++++----- .../tests/core/utils/test_current_time.py | 21 ++- westernization.md | 7 +- 21 files changed, 228 insertions(+), 364 deletions(-) delete mode 100644 main/xiaozhi-server/core/utils/alibl_endpoint.py diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index deaff8304..be64cefb1 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,32 +1,27 @@ --- -name: Bug 报告(Bug Report) -about: 反馈项目中的缺陷或问题 -title: "[Bug] 简短描述问题" +name: Bug Report +about: Report a defect or problem in the project +title: "[Bug] Short description of the problem" labels: bug assignees: '' --- -## 🐛 问题描述 - +## 🐛 Problem Description + -## 🖥️ 环境信息 -- 部署方式: 全模块部署 还是 单Server部署 -- 版本号: 例如 0.3.x +## 🖥️ Environment +- Deployment mode: full modules (manager + server) or server-only +- Version: e.g. 0.9.7 -## 🔍 告诉我们,应该怎么复现这个问题 - -1. 打开 '...' -2. 点击 '...' -3. 滚动到 '...' -4. 看到错误 +## 🔍 Steps to Reproduce + +1. Go to '...' +2. Click '...' +3. Scroll to '...' +4. See error -## 🤔 你原本希望是怎么样的 - +## 🤔 Expected Behavior + -## 😯 提供一些截图 - -1. 比如日志截图,越多越好 -2. 比如界面反应 - -## 📋 其他信息 - +## 📋 Logs / Screenshots + diff --git a/.github/ISSUE_TEMPLATE/code_improvement.md b/.github/ISSUE_TEMPLATE/code_improvement.md index 0ec0b145f..fe20eed7b 100644 --- a/.github/ISSUE_TEMPLATE/code_improvement.md +++ b/.github/ISSUE_TEMPLATE/code_improvement.md @@ -1,19 +1,19 @@ --- -name: 代码优化建议(Code Improvement) -about: 提出对现有代码的优化或改进建议 -title: "[Improvement] 简短描述改进内容" +name: Code Improvement +about: Propose an optimization or improvement to existing code +title: "[Improvement] Short description of the improvement" labels: refactor assignees: '' --- -## 💡 改进描述 - +## 💡 Improvement Description + -## 🌟 改进建议 - +## 🌟 Proposed Improvement + -## 🛠️ 相关代码 - +## 🛠️ Related Code + -## 📋 其他信息 - +## 📋 Additional Context + diff --git a/.github/ISSUE_TEMPLATE/documentation_improvement.md b/.github/ISSUE_TEMPLATE/documentation_improvement.md index 9cdc10e08..72b55863c 100644 --- a/.github/ISSUE_TEMPLATE/documentation_improvement.md +++ b/.github/ISSUE_TEMPLATE/documentation_improvement.md @@ -1,16 +1,16 @@ --- -name: 文档改进建议(Documentation Improvement) -about: 提出对项目文档的改进或补充建议 -title: "[Docs] 简短描述改进内容" +name: Documentation Improvement +about: Propose improvements or additions to the project documentation +title: "[Docs] Short description of the improvement" labels: documentation assignees: '' --- -## 📚 改进描述 - +## 📚 Improvement Description + -## ✨ 改进建议 - +## ✨ Proposed Improvement + -## 📋 其他信息 - +## 📋 Additional Context + diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index df1c029d9..853f1c1a5 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,19 +1,19 @@ --- -name: 功能请求(Feature Request) -about: 提出新的功能或改进建议 -title: "[Feature] 简短描述功能" +name: Feature Request +about: Propose a new feature or improvement +title: "[Feature] Short description of the feature" labels: enhancement assignees: '' --- -## 🚀 需求描述 - +## 🚀 Feature Description + -## 🎯 解决方案 - +## 🎯 Proposed Solution + -## 📝 备选方案 - +## 📝 Alternatives Considered + -## 📋 其他信息 - +## 📋 Additional Context + diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 135cfbd65..606ea4320 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,6 +10,14 @@ concurrency: cancel-in-progress: true jobs: + westernization-audit: + name: Westernization audit + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Run westernization audit + run: bash scripts/westernization_audit.sh + python: name: Python (xiaozhi-server) runs-on: ubuntu-latest @@ -28,12 +36,7 @@ jobs: - name: Run smoke test working-directory: main/xiaozhi-server run: | - if [ -f tests/test_smoke.py ]; then - pytest tests/test_smoke.py -x -q - else - echo "::warning::Slice 2 not done yet — tests/test_smoke.py missing" - exit 0 - fi + pytest tests/test_smoke.py -x -q java: name: Java (manager-api) diff --git a/Dockerfile-server-base b/Dockerfile-server-base index cfbe35f6d..4973e2617 100644 --- a/Dockerfile-server-base +++ b/Dockerfile-server-base @@ -12,10 +12,8 @@ RUN apt-get update && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* -# Pip mirror and network resilience (same mirror family as upstream product) -RUN pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/ && \ - pip config set global.trusted-host mirrors.aliyun.com && \ - pip config set global.timeout 120 && \ +# Pip network resilience (default PyPI index) +RUN pip config set global.timeout 120 && \ pip config set install.retries 5 ENV LANG=en_US.UTF-8 \ diff --git a/LICENSE b/LICENSE index b1718cca4..e2376ad7c 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ MIT License -Copyright (c) 2025 lapy +Copyright (c) 2025 xinnan-tech (original project: xinnan-tech/xiaozhi-esp32-server) +Copyright (c) 2025 lapy (westernized adaptations) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 8cd0ff991..70d8f58e7 100644 --- a/README.md +++ b/README.md @@ -215,7 +215,7 @@ In fact, any VLLM that supports OpenAI interface calls can be integrated and use | Usage Method | Supported Platforms | Free Platforms | |:---:|:---:|:---:| -| Local use | 3D-Speaker | 3D-Speaker | +| External HTTP service | Any voiceprint API compatible with the built-in `VoiceprintProvider` protocol (see [guide](./docs/guides/voiceprint.md)) | Self-hosted services | --- diff --git a/docs/features/integrations.md b/docs/features/integrations.md index e8ba9fe22..9f91244c0 100644 --- a/docs/features/integrations.md +++ b/docs/features/integrations.md @@ -185,7 +185,6 @@ Identify users by their voice patterns. ```yaml # Voiceprint configuration voiceprint: - enabled: true url: http://192.168.1.100:8005/voiceprint/health?key=abcd speakers: - "user1,John,John is a software engineer" @@ -193,6 +192,9 @@ voiceprint: - "user3,Bob,Bob is a student" ``` +See [Voiceprint Recognition](../guides/voiceprint.md) for the service +protocol and privacy notes. + #### **Voice Commands** - "Do you know who I am?" - "Register my voice" diff --git a/docs/guides/voiceprint.md b/docs/guides/voiceprint.md index ff5db5943..898aca2e5 100644 --- a/docs/guides/voiceprint.md +++ b/docs/guides/voiceprint.md @@ -1,149 +1,78 @@ # 🎤 Voiceprint Recognition -**⚠️ Important Notice: Voiceprint recognition is not currently implemented in the English version of Xiaozhi ESP32 Server.** +Voiceprint recognition is **implemented** in this build through the built-in +`VoiceprintProvider` (`main/xiaozhi-server/core/utils/voiceprint_provider.py`). +It runs in parallel with ASR: each audio segment is sent both to ASR and to an +external voiceprint HTTP service, and the identified speaker is injected into +the LLM context for personalized responses. + +> Note: the server does **not** ship a voiceprint model. You must run any +> voiceprint service that speaks the HTTP protocol below. The community +> [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) project is +> one compatible implementation (it uses ModelScope's 3D-Speaker models), but +> any service exposing the same endpoints and key scheme works. ## 🎯 What is Voiceprint Recognition? -Voiceprint recognition is a biometric technology that identifies users by their unique voice characteristics. It allows Xiaozhi to: +Voiceprint recognition is a biometric technology that identifies users by their +unique voice characteristics. It allows Xiaozhi to: - **Identify users** by their voice patterns - **Provide personalized responses** based on who is speaking - **Enable access control** through voice authentication - **Support multi-user environments** with different user profiles -## 🚧 Current Status +## ⚙️ Configuration -The voiceprint recognition feature is **not available** in the current English version of Xiaozhi ESP32 Server. This feature was part of the original Chinese implementation but has not been ported to the Western version. +Enable it in `config.yaml` (single-module) or via the control console: -## 🔗 Original Implementation +```yaml +voiceprint: + # Voiceprint service address with your API key + url: http://192.168.1.100:8005/voiceprint/health?key=abcd + # Speakers: speaker_id,name,description + speakers: + - "test1,John,John is a programmer" + - "test2,Jane,Jane is a product manager" + # Optional: identification similarity threshold (default 0.4) + similarity_threshold: 0.4 +``` -For users who need voiceprint recognition functionality, please refer to the **original Chinese implementation**: +The service URL is parsed for a `key` query parameter, which is sent as the +service's API key. If `url` or `speakers` is missing, voiceprint recognition +stays disabled and a warning is logged. -### **Original Documentation** -- **Chinese Documentation**: [Voiceprint Integration Guide](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/voiceprint-integration.md) -- **Original Repository**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server) +## 🛠️ Service Protocol -### **Original Voiceprint Service** -- **Voiceprint API**: [xinnan-tech/voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) -- **Service Documentation**: [Voiceprint API README](https://github.com/xinnan-tech/voiceprint-api/blob/main/README.md) +The built-in provider expects an HTTP service exposing: -## 🛠️ Implementation Details (Original) +- `GET /voiceprint/health?key=` — health probe; expects + `{"status": "healthy"}` (cached after the first success). +- `POST /voiceprint/identify` — multipart form with the WAV audio and the API + key; the service replies with the best-matching speaker id and a similarity + score (scores below `similarity_threshold` are treated as unknown). -The original voiceprint recognition system includes: +Speaker voice vectors are enrolled out-of-band by the service itself; the +server only sends audio and reads back identifications. See the original +[voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) README for a +reference implementation of these endpoints. -### **Components** -- **Voiceprint API Service** - Standalone service for voice processing -- **MySQL Database** - Stores voiceprint feature vectors -- **Docker Deployment** - Containerized service deployment -- **REST API** - HTTP endpoints for voiceprint management +## ⚖️ Privacy and Compliance -### **Features** -- **Voice Registration** - Register users' voice patterns -- **Voice Recognition** - Identify users by their voice -- **Database Storage** - Persistent storage of voiceprint data -- **API Integration** - RESTful API for voiceprint operations +Voiceprints are biometric data (GDPR special category in the EU, BIPA in +Illinois, etc.). Before enabling: -### **Technical Requirements** -- **MySQL Database** - For storing voiceprint data -- **Docker** - For service deployment -- **Audio Processing** - WAV audio file handling -- **Feature Extraction** - Voice characteristic analysis - -## 🔮 Future Implementation - -Voiceprint recognition may be implemented in future versions of the English Xiaozhi ESP32 Server. This would involve: - -### **Planned Features** -- **English Voice Models** - Optimized for English speech patterns -- **Western API Integration** - Integration with Western voice recognition services -- **Privacy-Focused Design** - Local processing with privacy protection -- **Multi-language Support** - Support for multiple languages - -### **Implementation Considerations** -- **Privacy Concerns** - Voice biometric data handling -- **Accuracy Requirements** - High accuracy for user identification -- **Performance Impact** - Minimal impact on system performance -- **Legal Compliance** - Compliance with privacy regulations - -## 🎯 Alternative Solutions - -While voiceprint recognition is not available, you can achieve similar functionality through: - -### **User Identification Methods** -- **Device-based Identification** - Different devices for different users -- **Voice Commands** - Custom voice commands for user identification -- **Manual User Selection** - Manual user switching in the interface -- **Time-based Profiles** - Different profiles based on time of day - -### **Personalization Features** -- **Custom Responses** - Personalized responses based on user preferences -- **User Profiles** - Different user profiles with custom settings -- **Voice Customization** - Different TTS voices for different users -- **Command Customization** - Custom voice commands per user +- Run the voiceprint service **locally**; do not send family audio to third + parties without a processor agreement. +- Obtain explicit consent from every enrolled speaker and document retention + and deletion procedures. +- Keep `similarity_threshold` conservative; misidentification feeds the wrong + persona into the LLM context. ## 📚 Related Documentation -### **Available Features** -- **[Voice Interaction](../features/voice-interaction.md)** - Basic voice recognition and synthesis -- **[Plugin System](../features/plugins.md)** - Extensible functionality -- **[Integrations](../features/integrations.md)** - Third-party service integrations -- **[Configuration](../configuration/basic-setup.md)** - System configuration - -### **Original Features** -- **[Original Repository](https://github.com/xinnan-tech/xiaozhi-esp32-server)** - Complete original implementation -- **[Chinese Documentation](https://github.com/xinnan-tech/xiaozhi-esp32-server/tree/main/docs)** - Original documentation -- **[Voiceprint API](https://github.com/xinnan-tech/voiceprint-api)** - Original voiceprint service - -## 🆘 Support and Questions - -### **For Voiceprint Recognition** -- **Original Implementation**: Refer to [xinnan-tech repository](https://github.com/xinnan-tech/xiaozhi-esp32-server) -- **Voiceprint Service**: Check [voiceprint-api](https://github.com/xinnan-tech/voiceprint-api) -- **Chinese Documentation**: [Original voiceprint guide](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/voiceprint-integration.md) - -### **For English Version** -- **Feature Requests**: [GitHub Issues](https://github.com/lapy/xiaozhi-esp32-server/issues) -- **Community Support**: [Discord Community](https://discord.gg/xiaozhi-esp32) -- **General Questions**: [FAQ](../support/faq.md) - -## 🎯 Next Steps - -Since voiceprint recognition is not available in the English version: - -1. **[Use Available Features](../features/voice-interaction.md)** - Explore current voice capabilities -2. **[Check Original Implementation](https://github.com/xinnan-tech/xiaozhi-esp32-server)** - Refer to Chinese version if needed -3. **[Request Feature Implementation](https://github.com/lapy/xiaozhi-esp32-server/issues)** - Submit feature request -4. **[Explore Alternatives](#alternative-solutions)** - Use alternative user identification methods - -## 🆘 Need Help? - -- **Voiceprint Questions?** Check [Original Implementation](https://github.com/xinnan-tech/xiaozhi-esp32-server) -- **English Version Questions?** Browse [FAQ](../support/faq.md) -- **Feature Requests?** Submit [GitHub Issue](https://github.com/lapy/xiaozhi-esp32-server/issues) - ---- - -## 🎯 Quick Reference - -### **Current Status** -- ❌ **Not Available** in English version -- ✅ **Available** in original Chinese version -- 🔗 **Original Implementation**: [xinnan-tech/xiaozhi-esp32-server](https://github.com/xinnan-tech/xiaozhi-esp32-server) - -### **Alternative Solutions** -- Device-based identification -- Custom voice commands -- Manual user selection -- Time-based profiles - -### **Future Plans** -- English voice models -- Western API integration -- Privacy-focused design -- Multi-language support - ---- - -**Voiceprint recognition is not available in the English version. Please refer to the original Chinese implementation for this feature. 🎤** +- **[Voice Interaction](../features/voice-interaction.md)** — Basic voice recognition and synthesis +- **[Integrations](../features/integrations.md)** — Third-party service integrations +- **[Configuration](../configuration/basic-setup.md)** — System configuration 👉 **[Next: Available Features →](../features/voice-interaction.md)** diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 18bbc1298..c62a94a9c 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -55,19 +55,21 @@ auto_import_modules("plugins_func.functions") class TTSException(RuntimeError): pass -# direct_answer 虚拟工具定义 -# 不是真实工具,是路由机制:将"调不调工具"的二选一变为"调哪个"的多选,防止小模型误触发真实工具 +# direct_answer virtual tool definition. +# Not a real tool: it is a routing mechanism that turns the binary +# "call a tool or not" choice into a "which one" selection, which stops small +# models from misfiring real tools. DIRECT_ANSWER_TOOL = { "type": "function", "function": { "name": "direct_answer", - "description": "当用户的请求不匹配其他任何工具时,可用此选项直接回复。将回复内容写在response参数里。", + "description": "Use this option to reply directly when the user's request matches no other tool. Write your full reply in the response parameter.", "parameters": { "type": "object", "properties": { "response": { "type": "string", - "description": "你回复用户的完整内容", + "description": "The complete reply you give to the user", }, }, "required": ["response"], diff --git a/main/xiaozhi-server/core/utils/alibl_endpoint.py b/main/xiaozhi-server/core/utils/alibl_endpoint.py deleted file mode 100644 index ef13bf065..000000000 --- a/main/xiaozhi-server/core/utils/alibl_endpoint.py +++ /dev/null @@ -1,48 +0,0 @@ -import re -from urllib.parse import urlsplit - - -DEFAULT_WS_URL = "wss://dashscope.aliyuncs.com/api-ws/v1/inference/" -INFERENCE_PATH = "/api-ws/v1/inference" -HOSTNAME_PATTERN = re.compile(r"^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$") -HAPPY_EYEBALLS_DELAY = 0.25 - - -def build_ws_connect_options(open_timeout): - return { - "open_timeout": open_timeout, - "happy_eyeballs_delay": HAPPY_EYEBALLS_DELAY, - "interleave": 1, - } - - -def resolve_ws_url(value): - ws_url = str(value or DEFAULT_WS_URL).strip() - parsed = urlsplit(ws_url) - hostname = (parsed.hostname or "").lower() - is_dashscope = hostname in { - "dashscope.aliyuncs.com", - "dashscope-intl.aliyuncs.com", - } - is_workspace = hostname.endswith(".maas.aliyuncs.com") - - try: - port = parsed.port - except ValueError: - port = -1 - - if ( - parsed.scheme.lower() != "wss" - or not HOSTNAME_PATTERN.fullmatch(hostname) - or not (is_dashscope or is_workspace) - or parsed.path.rstrip("/") != INFERENCE_PATH - or parsed.query - or parsed.fragment - or parsed.username - or parsed.password - or port not in {None, 443} - ): - raise ValueError( - "ws_url must be an official Alibaba Cloud WSS inference endpoint" - ) - return ws_url diff --git a/main/xiaozhi-server/core/utils/modules_initialize.py b/main/xiaozhi-server/core/utils/modules_initialize.py index 295c5c1c6..0813136c6 100644 --- a/main/xiaozhi-server/core/utils/modules_initialize.py +++ b/main/xiaozhi-server/core/utils/modules_initialize.py @@ -129,24 +129,3 @@ def initialize_asr(config): ) logger.bind(tag=TAG).info("ASR module initialization completed") return new_asr - - -def initialize_voiceprint(asr_instance, config): - """Initialize voiceprint recognition functionality""" - voiceprint_config = config.get("voiceprint") - if not voiceprint_config: - return False - - # Apply configuration - if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"): - logger.bind(tag=TAG).warning("Voiceprint recognition configuration incomplete") - return False - - try: - asr_instance.init_voiceprint(voiceprint_config) - logger.bind(tag=TAG).info("ASR module voiceprint recognition functionality dynamically enabled") - logger.bind(tag=TAG).info(f"Configured speaker count: {len(voiceprint_config['speakers'])}") - return True - except Exception as e: - logger.bind(tag=TAG).error(f"Dynamic initialization of voiceprint recognition functionality failed: {str(e)}") - return False diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py index edae6e9a1..877bc49fd 100644 --- a/main/xiaozhi-server/core/utils/prompt_manager.py +++ b/main/xiaozhi-server/core/utils/prompt_manager.py @@ -15,16 +15,6 @@ from jinja2 import Template TAG = __name__ -WEEKDAY_MAP = { - "Monday": "星期一", - "Tuesday": "星期二", - "Wednesday": "星期三", - "Thursday": "星期四", - "Friday": "星期五", - "Saturday": "星期六", - "Sunday": "星期日", -} - EMOJI_List = [ "😶", "🙂", @@ -153,7 +143,7 @@ class PromptManager: from core.utils.util import get_ip_info ip_info = get_ip_info(client_ip, self.logger) - city = ip_info.get("city", "未知位置") + city = ip_info.get("city", "Unknown location") location = f"{city}" # 存入缓存 @@ -161,7 +151,7 @@ class PromptManager: return location except Exception as e: self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}") - return "未知位置" + return "Unknown location" def _get_weather_info(self, conn: "ConnectionHandler", location: str) -> str: """获取天气信息""" @@ -184,7 +174,7 @@ class PromptManager: async def _call(): try: result_holder.append( - await get_weather(conn, location=location, lang="zh_CN") + await get_weather(conn, location=location, lang="en_US") ) except Exception as e: exception_holder.append(e) diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index d06631a10..079df8216 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -86,9 +86,12 @@ def get_ip_info(ip_addr, logger): # Cache miss: resolve the IP through the API. if is_private_ip(ip_addr): ip_addr = "" - url = f"https://whois.pconline.com.cn/ipJson.jsp?json=true&ip={ip_addr}" - resp = requests.get(url).json() - ip_info = {"city": resp.get("city")} + # ip-api.com returns English place names worldwide; status=="fail" + # (e.g. private/loopback addresses) yields an empty city. + url = f"http://ip-api.com/json/{ip_addr}?fields=status,city&lang=en" + resp = requests.get(url, timeout=5).json() + city = resp.get("city") if resp.get("status") == "success" else None + ip_info = {"city": city or ""} # Store the result in cache. cache_manager.set(CacheType.IP_INFO, ip_addr, ip_info) diff --git a/main/xiaozhi-server/mcp_server_settings.json b/main/xiaozhi-server/mcp_server_settings.json index 966741b4f..55b355531 100644 --- a/main/xiaozhi-server/mcp_server_settings.json +++ b/main/xiaozhi-server/mcp_server_settings.json @@ -1,10 +1,10 @@ { "des": [ - "在data目录下创建.mcp_server_settings.json文件,可以选择下面的MCP服务,也可以自行添加新的MCP服务。", - "后面不断测试补充好用的mcp服务,欢迎大家一起补充。", - "记得删除注释行,des属性仅为说明,不会被解析。", - "des和link属性,仅为说明安装方式,方便大家查看原始链接,不是必须项。", - "当前支持三种传输模式:stdio(标准输入输出), sse(Server-Sent Events), streamable-http(流式HTTP)。" + "Create a .mcp_server_settings.json file in the data directory. You can pick MCP services below or add your own.", + "More useful MCP services will be added as they are tested; contributions welcome.", + "Remember to delete the comment lines: the des property is informational only and is not parsed.", + "The des and link properties only document installation and original links; they are optional.", + "Three transport modes are supported: stdio, sse (Server-Sent Events), and streamable-http." ], "mcpServers": { "Home Assistant": { @@ -42,7 +42,7 @@ "headers": { "Authorization": "Bearer YOUR TOKEN" }, - "des": "使用SSE传输模式(默认)" + "des": "Uses SSE transport mode (default)" }, "streamable-http-mcp-server": { "url": "http://localhost:8000/mcp", @@ -50,7 +50,7 @@ "headers": { "Authorization": "Bearer YOUR TOKEN" }, - "des": "使用Streamable HTTP传输模式,适用于生产环境的Web部署" + "des": "Uses Streamable HTTP transport mode, suitable for production web deployments" } } } diff --git a/main/xiaozhi-server/plugins_func/functions/call_device.py b/main/xiaozhi-server/plugins_func/functions/call_device.py index e2b08fb53..8f4d73e86 100644 --- a/main/xiaozhi-server/plugins_func/functions/call_device.py +++ b/main/xiaozhi-server/plugins_func/functions/call_device.py @@ -1,4 +1,4 @@ -"""呼叫设备工具""" +"""Device calling tool""" import httpx from config.logger import setup_logging from plugins_func.register import register_function, ToolType, ActionResponse, Action @@ -15,18 +15,24 @@ call_device_function_desc = { "function": { "name": "call_device", "description": ( - "用于设备之间建立语音通话连接。" - "当用户说出以下意图时调用此工具:\n" - "1. 主动呼叫:用户说”呼叫XX/打电话给XX/连线XX/打给XX/帮我呼叫XX”时调用,nickname取XX。" - "例如:”呼叫张三”→nickname=”张三”、”帮我连线小陈”→nickname=”小陈”;\n" - "2. 接听来电:系统刚提示”您收到来自XX的来电,是否接听?”后,用户说”接听/接通/同意接听/同意连线/同意对话”时调用," - "nickname取提示中的XX。\n" - "如果用户输入不是明确接听,也不是明确拒绝,不得调用call_device,必须先追问一次" + "Establish a voice call connection between devices. " + "Call this tool when the user expresses one of these intents:\n" + "1. Outgoing call: call it when the user says things like " + "\"call XX / phone XX / connect me to XX / dial XX / get me XX on the line\"; " + "take XX as the nickname. " + "Examples: \"call John\" -> nickname=\"John\", " + "\"connect me to Sarah\" -> nickname=\"Sarah\";\n" + "2. Answering an incoming call: right after the system announces " + "\"Incoming call from XX, do you want to answer?\", call it when the " + "user says \"answer / pick up / yes answer / yes connect / yes talk\"; " + "take XX from the announcement as the nickname.\n" + "If the user's input is neither a clear acceptance nor a clear refusal, " + "do NOT call call_device; you must ask once first." ), "parameters": { "type": "object", "properties": { - "nickname": {"type": "string", "description": "目标设备的备注名,例如:小陈、小翁"}, + "nickname": {"type": "string", "description": "Display name of the target device, e.g. John, Sarah"}, }, "required": ["nickname"], }, @@ -44,7 +50,7 @@ def _failed_reply(msg: str) -> ActionResponse: def _is_answering(conn: "ConnectionHandler") -> bool: - """检查是否为接听模式(conn.incoming_call 不为空)""" + """Whether this is answer mode (conn.incoming_call is not empty)""" return hasattr(conn, 'incoming_call') and conn.incoming_call is not None @@ -52,24 +58,24 @@ def _is_answering(conn: "ConnectionHandler") -> bool: async def call_device(conn: "ConnectionHandler", nickname: str): caller_mac = conn.headers.get("device-id") if not caller_mac: - return _failed_reply("无法获取本机MAC地址") + return _failed_reply("Unable to get this device's MAC address") api_config = conn.config.get("manager-api", {}) api_url = api_config.get("url") api_secret = api_config.get("secret") if not api_url or not api_secret: - logger.bind(tag=TAG).error("manager-api配置缺失") - return _failed_reply("配置错误,请稍后再试") + logger.bind(tag=TAG).error("manager-api configuration missing") + return _failed_reply("Configuration error, please try again later") headers = {"Authorization": f"Bearer {api_secret}"} - # 区分是主动呼叫还是接听来电 + # Distinguish outgoing call from answering an incoming call is_answer = _is_answering(conn) - params = {"callerMac": caller_mac, "nickname": nickname} + params = {"callerMac": caller_mac, "nickname": nickname} if is_answer: params["answer"] = "true" - # 查询通讯录并发起呼叫 + # Look up the address book and place the call try: resp = await _request_api( f"{api_url}/device/address-book/call", @@ -78,18 +84,18 @@ async def call_device(conn: "ConnectionHandler", nickname: str): ) result = resp.json() except httpx.HTTPError as e: - logger.bind(tag=TAG).error(f"呼叫请求失败: {e}") - return _failed_reply("呼叫失败,请稍后再试") + logger.bind(tag=TAG).error(f"Call request failed: {e}") + return _failed_reply("Call failed, please try again later") if result.get("code") != 0: - return _failed_reply(result.get("msg", "呼叫失败")) + return _failed_reply(result.get("msg", "Call failed")) data = result.get("data", {}) if data.get("status") == "error": return _failed_reply(data.get("message")) if is_answer: - return ActionResponse(action=Action.NONE, response="已成功接听") + return ActionResponse(action=Action.NONE, response="Call answered") else: conn.calling = True - return ActionResponse(action=Action.NONE, response=f"正在呼叫{nickname},请等待对方接听") + return ActionResponse(action=Action.NONE, response=f"Calling {nickname}, please wait for them to answer") diff --git a/main/xiaozhi-server/plugins_func/functions/hass_state.py b/main/xiaozhi-server/plugins_func/functions/hass_state.py index fd18fd361..15b4f5179 100644 --- a/main/xiaozhi-server/plugins_func/functions/hass_state.py +++ b/main/xiaozhi-server/plugins_func/functions/hass_state.py @@ -14,13 +14,13 @@ hass_get_state_function_desc = { "type": "function", "function": { "name": "hass_get_state", - "description": "获取homeassistant里设备的状态,包括查询灯光亮度、颜色、色温,媒体播放器的音量,设备的暂停、继续操作", + "description": "Get device state in homeassistant, including light brightness, color, color temperature, media player volume, and device pause/resume state", "parameters": { "type": "object", "properties": { "entity_id": { "type": "string", - "description": "需要操作的设备id,homeassistant里的entity_id", + "description": "Device id to query, entity_id in homeassistant", } }, "required": ["entity_id"], diff --git a/main/xiaozhi-server/plugins_func/functions/web_search.py b/main/xiaozhi-server/plugins_func/functions/web_search.py index 611733573..ff1415ee7 100644 --- a/main/xiaozhi-server/plugins_func/functions/web_search.py +++ b/main/xiaozhi-server/plugins_func/functions/web_search.py @@ -15,7 +15,8 @@ TAG = __name__ logger = setup_logging() _DEFAULT_DESCRIPTION = ( - "联网搜索工具。当用户明确需要联网搜索问题时使用此工具。" + "Web search tool. Use this tool when the user explicitly asks for " + "current information from the internet." ) WEB_SEARCH_FUNCTION_DESC = { @@ -28,7 +29,7 @@ WEB_SEARCH_FUNCTION_DESC = { "properties": { "query": { "type": "string", - "description": "搜索关键词或问题", + "description": "Search keywords or question", } }, "required": ["query"], @@ -38,7 +39,7 @@ WEB_SEARCH_FUNCTION_DESC = { async def _search_metaso(api_key: str, query: str, max_results: int) -> str: - """调用秘塔搜索API""" + """Call the Metaso search API""" url = "https://metaso.cn/api/v1/search" headers = { "Authorization": f"Bearer {api_key}", @@ -53,32 +54,32 @@ async def _search_metaso(api_key: str, query: str, max_results: int) -> str: "includeRawContent": False, "conciseSnippet": False, } - logger.bind(tag=TAG).debug(f"秘塔搜索请求 | URL: {url} | payload: {payload}") + logger.bind(tag=TAG).debug(f"Metaso search request | URL: {url} | payload: {payload}") async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client: response = await client.post(url, json=payload, headers=headers) data = response.json() - logger.bind(tag=TAG).debug(f"秘塔搜索响应 | status: {response.status_code}") + logger.bind(tag=TAG).debug(f"Metaso search response | status: {response.status_code}") webpages = data.get("webpages", []) if not webpages: - return "未找到相关搜索结果。" + return "No related search results found." - lines = ["【联网搜索结果】"] + lines = ["[Web search results]"] for i, item in enumerate(webpages, 1): - title = item.get("title", "无标题") + title = item.get("title", "Untitled") snippet = item.get("summary", "") date = item.get("date", "") - lines.append(f"{i}. 标题:{title}") + lines.append(f"{i}. Title: {title}") if date: - lines.append(f" 日期:{date}") + lines.append(f" Date: {date}") if snippet: - lines.append(f" 摘要:{snippet}") + lines.append(f" Summary: {snippet}") return "\n".join(lines) async def _search_tavily(api_key: str, query: str, max_results: int) -> str: - """调用Tavily搜索API""" + """Call the Tavily search API""" url = "https://api.tavily.com/search" headers = { "Authorization": f"Bearer {api_key}", @@ -90,81 +91,82 @@ async def _search_tavily(api_key: str, query: str, max_results: int) -> str: "search_depth": "advanced", "include_answer": "advanced", } - logger.bind(tag=TAG).debug(f"Tavily搜索请求 | URL: {url} | payload: {payload}") + logger.bind(tag=TAG).debug(f"Tavily search request | URL: {url} | payload: {payload}") async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client: response = await client.post(url, json=payload, headers=headers) data = response.json() - logger.bind(tag=TAG).debug(f"Tavily搜索响应 | status: {response.status_code} | data: {data}") + logger.bind(tag=TAG).debug(f"Tavily search response | status: {response.status_code} | data: {data}") results = data.get("results", []) if not results: - return "未找到相关搜索结果。" + return "No related search results found." answer = data.get("answer", "") - lines = [f"【联网搜索结果】\n总结:{answer}"] + lines = [f"[Web search results]\nSummary: {answer}"] # for i, item in enumerate(results, 1): - # title = item.get("title", "无标题") + # title = item.get("title", "Untitled") # summary = item.get("content", "") - # lines.append(f"{i}. 标题:{title}") + # lines.append(f"{i}. Title: {title}") # if summary: - # lines.append(f" 摘要:{summary}") + # lines.append(f" Summary: {summary}") return "\n".join(lines) async def _search_serply(api_key: str, query: str, max_results: int) -> str: - """调用Serply搜索API""" + """Call the Serply search API""" url = "https://api.serply.io/v1/search" headers = { "X-Api-Key": api_key, "User-Agent": "xiaozhi-esp32-server", } - # Serply单页最多返回10条,且返回条数可能略多于num,需要本地再截断一次 + # Serply returns at most 10 items per page and may return slightly more + # than num, so truncate locally once more. params = {"q": query, "num": min(max_results, 10)} - logger.bind(tag=TAG).debug(f"Serply搜索请求 | URL: {url} | params: {params}") + logger.bind(tag=TAG).debug(f"Serply search request | URL: {url} | params: {params}") async with httpx.AsyncClient(timeout=httpx.Timeout(15.0, connect=3.0)) as client: response = await client.get(url, params=params, headers=headers) data = response.json() - logger.bind(tag=TAG).debug(f"Serply搜索响应 | status: {response.status_code}") + logger.bind(tag=TAG).debug(f"Serply search response | status: {response.status_code}") if response.status_code != 200: detail = data.get("detail", "") if isinstance(data, dict) else "" logger.bind(tag=TAG).error( - f"Serply搜索失败 | status: {response.status_code} | detail: {detail}" + f"Serply search failed | status: {response.status_code} | detail: {detail}" ) - return "联网搜索请求失败,请检查API Key是否正确。" + return "Web search request failed. Please check that the API key is correct." results = data.get("results", []) if not results: - return "未找到相关搜索结果。" + return "No related search results found." - lines = ["【联网搜索结果】"] + lines = ["[Web search results]"] for i, item in enumerate(results[:max_results], 1): - title = item.get("title", "无标题") + title = item.get("title", "Untitled") snippet = item.get("description", "") - lines.append(f"{i}. 标题:{title}") + lines.append(f"{i}. Title: {title}") if snippet: - lines.append(f" 摘要:{snippet}") + lines.append(f" Summary: {snippet}") return "\n".join(lines) @register_function("web_search", WEB_SEARCH_FUNCTION_DESC, ToolType.SYSTEM_CTL) async def web_search(conn: "ConnectionHandler", query: str = None): - logger.bind(tag=TAG).info(f"web_search 被调用 | query={query}") + logger.bind(tag=TAG).info(f"web_search called | query={query}") if not query: - return ActionResponse(Action.REQLLM, "请提供搜索关键词。", None) + return ActionResponse(Action.REQLLM, "Please provide search keywords.", None) web_search_config = conn.config.get("plugins", {}).get("web_search", {}) provider = web_search_config.get("provider", "").lower() max_results = int(web_search_config.get("max_results", 3)) - logger.bind(tag=TAG).info(f"web_search 配置 | provider={provider} | max_results={max_results} | config_keys={list(web_search_config.keys())}") + logger.bind(tag=TAG).info(f"web_search config | provider={provider} | max_results={max_results} | config_keys={list(web_search_config.keys())}") api_key = web_search_config.get("api_key", "") if not api_key: return ActionResponse( Action.REQLLM, - "联网搜索功能未配置API Key,请在配置文件中填写。", + "Web search has no API key configured. Please fill it in the config file.", None, ) @@ -178,18 +180,18 @@ async def web_search(conn: "ConnectionHandler", query: str = None): else: return ActionResponse( Action.REQLLM, - f"联网搜索功能未配置或配置的搜索源无效(当前:{provider}),请检查配置。", + f"Web search is not configured or the search provider is invalid (current: {provider}). Please check the configuration.", None, ) - logger.bind(tag=TAG).info(f"搜索结果组装完成:\n{result_text}") + logger.bind(tag=TAG).info(f"Search results assembled:\n{result_text}") except httpx.TimeoutException: - logger.bind(tag=TAG).error("联网搜索请求超时") - result_text = "联网搜索请求超时,请稍后重试。" + logger.bind(tag=TAG).error("Web search request timed out") + result_text = "The web search request timed out. Please try again later." except httpx.HTTPStatusError as e: - logger.bind(tag=TAG).error(f"联网搜索请求失败: {e}") - result_text = "联网搜索请求失败,请稍后重试。" + logger.bind(tag=TAG).error(f"Web search request failed: {e}") + result_text = "The web search request failed. Please try again later." except Exception as e: - logger.bind(tag=TAG).error(f"联网搜索异常: {e}") - result_text = "联网搜索出现异常,请稍后重试。" + logger.bind(tag=TAG).error(f"Web search error: {e}") + result_text = "The web search hit an error. Please try again later." return ActionResponse(Action.REQLLM, result_text, None) diff --git a/main/xiaozhi-server/tests/core/utils/test_current_time.py b/main/xiaozhi-server/tests/core/utils/test_current_time.py index b92fc0133..991fa4853 100644 --- a/main/xiaozhi-server/tests/core/utils/test_current_time.py +++ b/main/xiaozhi-server/tests/core/utils/test_current_time.py @@ -1,7 +1,7 @@ """Tests for core/utils/current_time.py. Uses freezegun to control `datetime.now()` so the tests don't flake -around midnight, and to verify the weekday/lunar mapping logic. +around midnight, and to verify the weekday/date formatting logic. """ from datetime import datetime @@ -27,8 +27,8 @@ def test_get_current_date_format_is_iso(): @freeze_time("2026-09-02 10:30:00") # 2026-09-02 is a Wednesday -def test_get_current_weekday_returns_chinese_label(): - assert current_time.get_current_weekday() == "星期三" +def test_get_current_weekday_returns_english_label(): + assert current_time.get_current_weekday() == "Wednesday" def test_weekday_map_has_all_seven_days(): @@ -36,6 +36,8 @@ def test_weekday_map_has_all_seven_days(): "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", } + # Western builds map each weekday to its English name. + assert all(k == v for k, v in current_time.WEEKDAY_MAP.items()) @freeze_time("2026-09-02 10:30:00") @@ -43,15 +45,14 @@ def test_get_current_time_info_returns_four_tuple(): info = current_time.get_current_time_info() assert isinstance(info, tuple) assert len(info) == 4 - time_str, date_str, weekday, lunar = info + time_str, date_str, weekday, formatted_date = info assert time_str == "10:30" assert date_str == "2026-09-02" - assert weekday == "星期三" - assert "年" in lunar # lunar output contains "年" + assert weekday == "Wednesday" + assert formatted_date == "September 02, 2026" @freeze_time("2026-09-02 10:30:00") -def test_get_current_lunar_date_contains_year(): - """cnlunar should produce a string containing 年 character.""" - lunar = current_time.get_current_lunar_date() - assert "年" in lunar \ No newline at end of file +def test_get_current_lunar_date_is_gregorian_alias(): + """Western builds return the formatted Gregorian date.""" + assert current_time.get_current_lunar_date() == "September 02, 2026" diff --git a/westernization.md b/westernization.md index abd3d8470..392e65bdc 100644 --- a/westernization.md +++ b/westernization.md @@ -190,13 +190,14 @@ Run the owning subsystem checks after each slice when possible. ### Python server ```bash -python3 main/xiaozhi-server/test/test_runner.py +cd main/xiaozhi-server +PYTHONPATH=. pytest tests/ -q ``` -Or project venv if needed: +Or the interactive harness: ```bash -./.venv-xiaozhi/bin/python main/xiaozhi-server/test/test_runner.py +cd main/xiaozhi-server && PYTHONPATH=. python3 ../digital-human/test_runner.py ``` ### Manager API