diff --git a/README_de.md b/README_de.md
deleted file mode 100644
index 0e4c74d54..000000000
--- a/README_de.md
+++ /dev/null
@@ -1,374 +0,0 @@
-[](https://github.com/xinnan-tech/xiaozhi-esp32-server)
-
-
Xiaozhi Backend-Service xiaozhi-esp32-server
-
-
-Dieses Projekt basiert auf der Theorie und Technologie der Mensch-Maschine-symbiotischen Intelligenz zur Entwicklung intelligenter Terminal-Hardware- und Software-Systeme und bietet Backend-Dienste für das Open-Source-Hardware-Projekt
-xiaozhi-esp32
-Implementiert mit Python, Java und Vue gemäß dem Xiaozhi-Kommunikationsprotokoll
-Unterstützt MQTT+UDP-Protokoll, Websocket-Protokoll, MCP-Endpunkte und Stimmabdruckerkennung
-
-
-
-Häufige Fragen
-· Probleme melden
-· Deployment-Dokumentation
-· Release-Hinweise
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Geleitet vom Team von Professor Siyuan Liu (South China University of Technology)
-
-刘思源教授团队主导研发(华南理工大学)
-
-
-
-
----
-
-## Zielgruppe 👥
-
-Dieses Projekt erfordert ESP32-Hardware-Geräte zum Betrieb. Wenn Sie ESP32-bezogene Hardware erworben haben, erfolgreich eine Verbindung zu Brother Xias bereitgestelltem Backend-Service hergestellt haben und Ihren eigenen `xiaozhi-esp32`-Backend-Service unabhängig aufbauen möchten, dann ist dieses Projekt perfekt für Sie.
-
-Möchten Sie die Nutzungseffekte sehen? Klicken Sie auf die Videos unten 🎥
-
-
-
----
-
-## Warnungen ⚠️
-
-1. Dieses Projekt ist Open-Source-Software. Diese Software hat keine kommerzielle Partnerschaft mit Drittanbieter-API-Dienstleistern (einschließlich, aber nicht beschränkt auf Spracherkennung, große Modelle, Sprachsynthese und andere Plattformen), mit denen sie sich verbindet, und bietet keine Garantie für deren Servicequalität oder finanzielle Sicherheit. Es wird empfohlen, dass Benutzer Dienstleister mit entsprechenden Geschäftslizenzen bevorzugen und deren Servicevereinbarungen und Datenschutzrichtlinien sorgfältig lesen. Diese Software hostet keine Kontoschlüssel, nimmt nicht an Geldströmen teil und trägt nicht das Risiko von Verlusten bei Guthaben-Aufladungen.
-
-2. Die Funktionalität dieses Projekts ist nicht vollständig und hat keine Netzwerksicherheitsbewertung bestanden. Bitte verwenden Sie es nicht in Produktionsumgebungen. Wenn Sie dieses Projekt zu Lernzwecken in einer öffentlichen Netzwerkumgebung bereitstellen, stellen Sie bitte sicher, dass notwendige Schutzmaßnahmen vorhanden sind.
-
----
-
-## Deployment-Dokumentation
-
-
-
-Dieses Projekt bietet zwei Bereitstellungsmethoden. Bitte wählen Sie basierend auf Ihren spezifischen Anforderungen:
-
-#### 🚀 Auswahl der Bereitstellungsmethode
-| Bereitstellungsmethode | Funktionen | Anwendungsszenarien | Deployment-Dokumente | Konfigurationsanforderungen | Video-Tutorials |
-|---------|------|---------|---------|---------|---------|
-| **Vereinfachte Installation** | Intelligenter Dialog, Einzel-Agenten-Verwaltung | Umgebungen mit geringer Konfiguration, Daten in Konfigurationsdateien gespeichert, keine Datenbank erforderlich | [①Docker-Version](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Quellcode-Deployment](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 Kerne 4GB bei Verwendung von `FunASR`, 2 Kerne 2GB bei allen APIs | - |
-| **Vollständige Modulinstallation** | Intelligenter Dialog, Mehrbenutzerverwaltung, Mehr-Agenten-Verwaltung, Intelligente Steuerkonsole-Bedienung | Vollständige Funktionserfahrung, Daten in Datenbank gespeichert |[①Docker-Version](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Quellcode-Deployment](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Quellcode-Deployment Auto-Update-Tutorial](./docs/dev-ops-integration.md) | 4 Kerne 8GB bei Verwendung von `FunASR`, 2 Kerne 4GB bei allen APIs| [Video-Tutorial für lokalen Quellcode-Start](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
-
-Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](./docs/FAQ.md)
-
-> 💡 Hinweis: Unten ist eine Testplattform, die mit dem neuesten Code bereitgestellt wurde. Sie können bei Bedarf brennen und testen. Gleichzeitige Benutzer: 6, Daten werden täglich gelöscht.
-
-```
-Adresse der intelligenten Steuerkonsole: https://2662r3426b.vicp.fun
-Adresse der intelligenten Steuerkonsole (H5): https://2662r3426b.vicp.fun/h5/index.html
-
-Service-Testtool: https://2662r3426b.vicp.fun/test/
-OTA-Schnittstellenadresse: https://2662r3426b.vicp.fun/xiaozhi/ota/
-Websocket-Schnittstellenadresse: wss://2662r3426b.vicp.fun/xiaozhi/v1/
-```
-
-#### 🚩 Konfigurationsbeschreibung und Empfehlungen
-> [!Note]
-> Dieses Projekt bietet zwei Konfigurationsschemata:
->
-> 1. `Einstiegslevel Kostenlose Einstellungen`: Geeignet für den persönlichen und privaten Gebrauch, alle Komponenten verwenden kostenlose Lösungen, keine zusätzliche Zahlung erforderlich.
->
-> 2. `Streaming-Konfiguration`: Geeignet für Demonstrationen, Schulungen, Szenarien mit mehr als 2 gleichzeitigen Benutzern usw. Verwendet Streaming-Verarbeitungstechnologie für schnellere Reaktionsgeschwindigkeit und bessere Erfahrung.
->
-> Ab Version `0.5.2` unterstützt das Projekt Streaming-Konfiguration. Im Vergleich zu früheren Versionen ist die Reaktionsgeschwindigkeit um ca. `2,5 Sekunden` verbessert, was die Benutzererfahrung erheblich verbessert.
-
-| Modulname | Einstiegslevel Kostenlose Einstellungen | Streaming-Konfiguration |
-|:---:|:---:|:---:|
-| ASR (Spracherkennung) | FunASR (Lokal) | 👍XunfeiStreamASR (Xunfei-Streaming) |
-| LLM (Großes Modell) | glm-4-flash (Zhipu) | 👍qwen-flash (Alibaba Bailian) |
-| VLLM (Vision Large Model) | glm-4v-flash (Zhipu) | 👍qwen2.5-vl-3b-instructh (Alibaba Bailian) |
-| TTS (Sprachsynthese) | ✅LinkeraiTTS (Lingxi-Streaming) | 👍HuoshanDoubleStreamTTS (Volcano-Streaming) |
-| Intent (Absichtserkennung) | function_call (Funktionsaufruf) | function_call (Funktionsaufruf) |
-| Memory (Gedächtnisfunktion) | mem_local_short (Lokales Kurzzeitgedächtnis) | mem_local_short (Lokales Kurzzeitgedächtnis) |
-
-Wenn Sie sich um die Latenz jeder Komponente kümmern, lesen Sie bitte den [Xiaozhi-Komponenten-Leistungstestbericht](https://github.com/xinnan-tech/xiaozhi-performance-research). Sie können gemäß den Testmethoden im Bericht in Ihrer Umgebung tatsächlich testen.
-
-#### 🔧 Testwerkzeuge
-Dieses Projekt bietet die folgenden Testwerkzeuge, um Ihnen bei der Überprüfung des Systems und der Auswahl geeigneter Modelle zu helfen:
-
-| Werkzeugname | Standort | Verwendungsmethode | Funktionsbeschreibung |
-|:---:|:---|:---:|:---:|
-| Audio-Interaktionstesttool | main》xiaozhi-server》test》test_page.html | Direkt mit Google Chrome öffnen | Testet Audio-Wiedergabe- und Empfangsfunktionen, überprüft, ob die Python-seitige Audioverarbeitung normal ist |
-| Modell-Reaktionstesttool | main》xiaozhi-server》performance_tester.py | Ausführen `python performance_tester.py` | Testet die Reaktionsgeschwindigkeit von ASR (Spracherkennung), LLM (großes Modell), VLLM (Vision-Modell), TTS (Sprachsynthese) drei Kernmodulen |
-
-> 💡 Hinweis: Beim Testen der Modellgeschwindigkeit werden nur Modelle mit konfigurierten Schlüsseln getestet.
-
----
-## Funktionsliste ✨
-### Implementiert ✅
-
-| Funktionsmodul | Beschreibung |
-|:---:|:---|
-| Kernarchitektur | Basierend auf [MQTT+UDP-Gateway](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket und HTTP-Servern, bietet vollständiges Konsolenverwaltungs- und Authentifizierungssystem |
-| Sprachinteraktion | Unterstützt Streaming-ASR (Spracherkennung), Streaming-TTS (Sprachsynthese), VAD (Sprachaktivitätserkennung), unterstützt mehrsprachige Erkennung und Sprachverarbeitung |
-| Stimmabdruckerkennung | Unterstützt Mehrbenutzer-Stimmabdruckregistrierung, -verwaltung und -erkennung, verarbeitet parallel mit ASR, Echtzeit-Sprecheridentitätserkennung und Weitergabe an LLM für personalisierte Antworten |
-| Intelligenter Dialog | Unterstützt mehrere LLM (große Sprachmodelle), implementiert intelligenten Dialog |
-| Visuelle Wahrnehmung | Unterstützt mehrere VLLM (Vision Large Models), implementiert multimodale Interaktion |
-| Absichtserkennung | Unterstützt LLM-Absichtserkennung, Function Call-Funktionsaufruf, bietet plugin-basierten Absichtsverarbeitungsmechanismus |
-| Gedächtnissystem | Unterstützt lokales Kurzzeitgedächtnis, mem0ai-Schnittstellengedächtnis, mit Gedächtniszusammenfassungsfunktion |
-| Wissensdatenbank | Unterstützt RAGFlow-Wissensdatenbank, ermöglicht großem Modell die Bewertung, ob Wissensdatenbank benötigt wird, bevor geantwortet wird |
-| Werkzeugaufruf | Unterstützt Client-IOT-Protokoll, Client-MCP-Protokoll, Server-MCP-Protokoll, MCP-Endpunktprotokoll, benutzerdefinierte Werkzeugfunktionen |
-| Befehlsübermittlung | Basierend auf MQTT-Protokoll, unterstützt die Übermittlung von MCP-Befehlen von der intelligenten Steuerkonsole an ESP32-Geräte |
-| Verwaltungs-Backend | Bietet Web-Verwaltungsoberfläche, unterstützt Benutzerverwaltung, Systemkonfiguration und Geräteverwaltung; Oberfläche unterstützt vereinfachtes Chinesisch, traditionelles Chinesisch und englische Anzeige |
-| Testwerkzeuge | Bietet Leistungstestwerkzeuge, Vision-Modell-Testwerkzeuge und Audio-Interaktionstestwerkzeuge |
-| Deployment-Unterstützung | Unterstützt Docker-Deployment und lokales Deployment, bietet vollständige Konfigurationsdateiverwaltung |
-| Plugin-System | Unterstützt funktionale Plugin-Erweiterungen, benutzerdefinierte Plugin-Entwicklung und Plugin-Hot-Loading |
-
-### In Entwicklung 🚧
-
-Um über spezifische Entwicklungsplanfortschritte zu erfahren, [klicken Sie hier](https://github.com/users/xinnan-tech/projects/3). Häufige Fragen und entsprechende Tutorials finden Sie unter [diesem Link](./docs/FAQ.md)
-
-Wenn Sie ein Softwareentwickler sind, finden Sie hier einen [Offenen Brief an Entwickler](docs/contributor_open_letter.md). Willkommen beim Beitritt!
-
----
-
-## Produktökosystem 👬
-Xiaozhi ist ein Ökosystem. Wenn Sie dieses Produkt verwenden, können Sie sich auch andere [hervorragende Projekte](https://github.com/78/xiaozhi-esp32?tab=readme-ov-file#related-open-source-projects) in diesem Ökosystem ansehen
-
----
-
-## Liste der von diesem Projekt unterstützten Plattformen/Komponenten 📋
-### LLM-Sprachmodelle
-
-| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
-|:---:|:---:|:---:|
-| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Volcano Engine Doubao, DeepSeek, Zhipu ChatGLM, Gemini | Zhipu ChatGLM, Gemini |
-| Ollama-Schnittstellenaufrufe | Ollama | - |
-| Dify-Schnittstellenaufrufe | Dify | - |
-| FastGPT-Schnittstellenaufrufe | FastGPT | - |
-| Coze-Schnittstellenaufrufe | Coze | - |
-| Xinference-Schnittstellenaufrufe | Xinference | - |
-| HomeAssistant-Schnittstellenaufrufe | HomeAssistant | - |
-
-Tatsächlich kann jedes LLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
-
----
-
-### VLLM-Vision-Modelle
-
-| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
-|:---:|:---:|:---:|
-| OpenAI-Schnittstellenaufrufe | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
-
-Tatsächlich kann jedes VLLM, das OpenAI-Schnittstellenaufrufe unterstützt, integriert und verwendet werden.
-
----
-
-### TTS-Sprachsynthese
-
-| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
-|:---:|:---:|:---:|
-| Schnittstellenaufrufe | EdgeTTS, Volcano Engine Doubao TTS, Tencent Cloud, Alibaba Cloud TTS, AliYun Stream TTS, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi Streaming TTS, MinimaxTTS, Volcano Dual-Stream TTS | Lingxi Streaming TTS, EdgeTTS, CosyVoiceSiliconflow (teilweise) |
-| Lokale Dienste | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
-
----
-
-### VAD-Sprachaktivitätserkennung
-
-| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
-|:---:|:---------:|:----:|:----:|:--:|
-| VAD | SileroVAD | Lokale Verwendung | Kostenlos | |
-
----
-
-### ASR-Spracherkennung
-
-| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
-|:---:|:---:|:---:|
-| Lokale Verwendung | FunASR, SherpaASR | FunASR, SherpaASR |
-| Schnittstellenaufrufe | DoubaoASR, Doubao Streaming ASR, FunASRServer, TencentASR, AliyunASR, Aliyun Streaming ASR, Baidu ASR, OpenAI ASR | FunASRServer |
-
----
-
-### Voiceprint-Stimmabdruckerkennung
-
-| Verwendungsmethode | Unterstützte Plattformen | Kostenlose Plattformen |
-|:---:|:---:|:---:|
-| Lokale Verwendung | 3D-Speaker | 3D-Speaker |
-
----
-
-### Memory-Gedächtnisspeicher
-
-| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
-|:------:|:---------------:|:----:|:---------:|:--:|
-| Memory | mem0ai | Schnittstellenaufrufe | 1000 Mal/Monat Kontingent | |
-| Memory | mem_local_short | Lokale Zusammenfassung | Kostenlos | |
-| Memory | nomem | Kein Gedächtnismodus | Kostenlos | |
-
----
-
-### Intent-Absichtserkennung
-
-| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
-|:------:|:-------------:|:----:|:-------:|:---------------------:|
-| Intent | intent_llm | Schnittstellenaufrufe | Basierend auf LLM-Preisen | Erkennt Absicht durch große Modelle, starke Allgemeingültigkeit |
-| Intent | function_call | Schnittstellenaufrufe | Basierend auf LLM-Preisen | Vervollständigt Absicht durch Funktionsaufruf großer Modelle, schnelle Geschwindigkeit, guter Effekt |
-| Intent | nointent | Kein Absichtsmodus | Kostenlos | Führt keine Absichtserkennung durch, gibt direkt Dialogergebnis zurück |
-
----
-
-### Rag Retrieval Augmented Generation
-
-| Typ | Plattformname | Verwendungsmethode | Preismodell | Hinweise |
-|:------:|:-------------:|:----:|:-------:|:---------------------:|
-| Rag | ragflow | Schnittstellenaufrufe | Gebühren basierend auf Token-Verbrauch für Segmentierung und Tokenisierung | Nutzt RAGFlow's Retrieval-Augmented-Generation-Funktion für präzisere Dialogantworten |
-
----
-
-## Danksagungen 🙏
-
-| Logo | Projekt/Unternehmen | Beschreibung |
-|:---:|:---:|:---|
-| | [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) | Dieses Projekt wurde von [Bailing Voice Dialogue Robot](https://github.com/wwbin2017/bailing) inspiriert und auf dessen Basis implementiert |
-| | [Tenclass](https://www.tenclass.com/) | Dank an [Tenclass](https://www.tenclass.com/) für die Formulierung von Standardkommunikationsprotokollen, Multi-Geräte-Kompatibilitätslösungen und High-Concurrency-Szenario-Praxisdemonstrationen für das Xiaozhi-Ökosystem; für die Bereitstellung vollständiger technischer Dokumentationsunterstützung für dieses Projekt |
-| | [Xuanfeng Technology](https://github.com/Eric0308) | Dank an [Xuanfeng Technology](https://github.com/Eric0308) für den Beitrag des Funktionsaufruf-Frameworks, des MCP-Kommunikationsprotokolls und der plugin-basierten Aufrufmechanismus-Implementierungscode. Durch standardisiertes Befehlsplanungssystem und dynamische Erweiterungsfähigkeiten wird die Interaktionseffizienz und funktionale Erweiterbarkeit von Frontend-Geräten (IoT) erheblich verbessert |
-| | [huangjunsen](https://github.com/huangjunsen0406) | Dank an [huangjunsen](https://github.com/huangjunsen0406) für den Beitrag des `Smart Control Console Mobile`-Moduls, das eine effiziente Steuerung und Echtzeit-Interaktion über mobile Geräte ermöglicht und die Betriebsbequemlichkeit und Verwaltungseffizienz des Systems in mobilen Szenarien erheblich verbessert |
-| | [Huiyuan Design](http://ui.kwd988.net/) | Dank an [Huiyuan Design](http://ui.kwd988.net/) für die Bereitstellung professioneller visueller Lösungen für dieses Projekt, unter Verwendung ihrer Design-Praxiserfahrung im Dienst von über tausend Unternehmen, um die Produktbenutzererfahrung dieses Projekts zu stärken |
-| | [Xi'an Qinren Information Technology](https://www.029app.com/) | Dank an [Xi'an Qinren Information Technology](https://www.029app.com/) für die Vertiefung des visuellen Systems dieses Projekts und die Sicherstellung der Konsistenz und Erweiterbarkeit des Gesamtdesignstils in Multi-Szenario-Anwendungen |
-| | [Code-Mitwirkende](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Dank an [alle Code-Mitwirkenden](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), Ihre Bemühungen haben das Projekt robuster und leistungsfähiger gemacht. |
-
-
-
-
-
-
-
-
-
-
diff --git a/README_vi.md b/README_vi.md
deleted file mode 100644
index e6d5f4890..000000000
--- a/README_vi.md
+++ /dev/null
@@ -1,375 +0,0 @@
-[](https://github.com/xinnan-tech/xiaozhi-esp32-server)
-
-Dịch vụ Backend Xiaozhi xiaozhi-esp32-server
-
-
-Dự án này dựa trên lý thuyết và công nghệ trí tuệ cộng sinh người-máy để phát triển hệ thống phần mềm và phần cứng thiết bị đầu cuối thông minh Cung cấp dịch vụ backend cho dự án phần cứng thông minh mã nguồn mở
-xiaozhi-esp32
-Được triển khai bằng Python, Java, Vue theo giao thức truyền thông Xiaozhi
-Hỗ trợ giao thức MQTT+UDP, giao thức Websocket, điểm truy cập MCP, nhận dạng giọng nói và kho tri thức
-
-
-
-Câu hỏi thường gặp
-· Báo cáo vấn đề
-· Tài liệu triển khai
-· Nhật ký cập nhật
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-Spearheaded by Professor Siyuan Liu's Team (South China University of Technology)
-
-Được dẫn dắt bởi nhóm Giáo sư Lưu Tư Nguyên (Đại học Bách khoa Nam Trung Quốc)
-
-
-
-
----
-
-## Người dùng phù hợp 👥
-
-Dự án này cần được sử dụng cùng với thiết bị phần cứng ESP32. Nếu bạn đã mua phần cứng liên quan đến ESP32, đã thành công kết nối với dịch vụ backend do anh Xia triển khai, và muốn xây dựng dịch vụ backend `xiaozhi-esp32` riêng của mình, thì dự án này rất phù hợp với bạn.
-
-Muốn xem hiệu quả sử dụng? Hãy xem video 🎥
-
-
-
----
-
-## Cảnh báo ⚠️
-
-1. Dự án này là phần mềm mã nguồn mở, phần mềm này không có quan hệ hợp tác thương mại với bất kỳ nhà cung cấp dịch vụ API bên thứ ba nào (bao gồm nhưng không giới hạn ở các nền tảng nhận dạng giọng nói, mô hình lớn, tổng hợp giọng nói, v.v.), và không đảm bảo chất lượng dịch vụ cũng như an toàn tài chính của họ.
-Khuyến nghị người dùng ưu tiên lựa chọn nhà cung cấp dịch vụ có giấy phép kinh doanh liên quan và đọc kỹ thỏa thuận dịch vụ và chính sách bảo mật của họ. Phần mềm này không lưu trữ bất kỳ khóa tài khoản nào, không tham gia vào luồng tiền và không chịu rủi ro mất tiền nạp.
-
-2. Chức năng của dự án này chưa hoàn thiện và chưa qua đánh giá bảo mật mạng, vui lòng không sử dụng trong môi trường sản xuất. Nếu bạn triển khai dự án này trong môi trường mạng công cộng để học tập, vui lòng thực hiện các biện pháp bảo vệ cần thiết.
-
----
-
-## Tài liệu triển khai
-
-
-
-Dự án này cung cấp hai phương pháp triển khai, vui lòng chọn theo nhu cầu cụ thể của bạn:
-
-#### 🚀 Lựa chọn phương pháp triển khai
-| Phương pháp triển khai | Đặc điểm | Tình huống áp dụng | Tài liệu triển khai | Yêu cầu cấu hình | Video hướng dẫn |
-|---------|------|---------|---------|---------|---------|
-| **Cài đặt tối giản** | Đối thoại thông minh, quản lý đơn tác nhân | Môi trường cấu hình thấp, dữ liệu lưu trong tệp cấu hình, không cần cơ sở dữ liệu | [①Phiên bản Docker](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E5%8F%AA%E8%BF%90%E8%A1%8Cserver) / [②Triển khai mã nguồn](./docs/Deployment.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E5%8F%AA%E8%BF%90%E8%A1%8Cserver)| 2 nhân 4GB nếu dùng `FunASR`, 2 nhân 2GB nếu toàn API | - |
-| **Cài đặt toàn bộ module** | Đối thoại thông minh, quản lý đa người dùng, quản lý đa tác nhân, bảng điều khiển thông minh | Trải nghiệm đầy đủ tính năng, dữ liệu lưu trong cơ sở dữ liệu |[①Phiên bản Docker](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%B8%80docker%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [②Triển khai mã nguồn](./docs/Deployment_all.md#%E6%96%B9%E5%BC%8F%E4%BA%8C%E6%9C%AC%E5%9C%B0%E6%BA%90%E7%A0%81%E8%BF%90%E8%A1%8C%E5%85%A8%E6%A8%A1%E5%9D%97) / [③Hướng dẫn tự động cập nhật triển khai mã nguồn](./docs/dev-ops-integration.md) | 4 nhân 8GB nếu dùng `FunASR`, 2 nhân 4GB nếu toàn API| [Video hướng dẫn khởi động mã nguồn cục bộ](https://www.bilibili.com/video/BV1wBJhz4Ewe) |
-
-Câu hỏi thường gặp và hướng dẫn liên quan, vui lòng tham khảo [liên kết này](./docs/FAQ.md)
-
-> 💡 Gợi ý: Dưới đây là nền tảng thử nghiệm được triển khai theo mã mới nhất, có thể flash để thử nghiệm nếu cần, đồng thời là 6, dữ liệu sẽ được xóa mỗi ngày,
-
-```
-Địa chỉ bảng điều khiển thông minh: https://2662r3426b.vicp.fun
-Bảng điều khiển thông minh (phiên bản h5): https://2662r3426b.vicp.fun/h5/index.html
-
-Công cụ kiểm tra dịch vụ: https://2662r3426b.vicp.fun/test/
-Địa chỉ giao diện OTA: https://2662r3426b.vicp.fun/xiaozhi/ota/
-Địa chỉ giao diện Websocket: wss://2662r3426b.vicp.fun/xiaozhi/v1/
-```
-
-#### 🚩 Mô tả và khuyến nghị cấu hình
-> [!Note]
-> Dự án này cung cấp hai phương án cấu hình:
->
-> 1. Cấu hình `Miễn phí hoàn toàn cho người mới`: Phù hợp với sử dụng gia đình cá nhân, tất cả các thành phần đều sử dụng phương án miễn phí, không cần thanh toán thêm.
->
-> 2. `Cấu hình streaming`: Phù hợp với demo, đào tạo, hơn 2 đồng thời, v.v., sử dụng công nghệ xử lý streaming, tốc độ phản hồi nhanh hơn, trải nghiệm tốt hơn.
->
-> Từ phiên bản `0.5.2`, dự án hỗ trợ cấu hình streaming, so với phiên bản đầu, tốc độ phản hồi cải thiện khoảng `2.5 giây`, cải thiện đáng kể trải nghiệm người dùng.
-
-| Tên module | Cài đặt miễn phí cho người mới | Cấu hình streaming |
-|:---:|:---:|:---:|
-| ASR(Nhận dạng giọng nói) | FunASR(Local) | 👍XunfeiStreamASR(Xunfei Streaming) |
-| LLM(Mô hình lớn) | glm-4-flash(Zhipu) | 👍qwen-flash(Alibaba Bailian) |
-| VLLM(Mô hình lớn thị giác) | glm-4v-flash(Zhipu) | 👍qwen2.5-vl-3b-instructh(Alibaba Bailian) |
-| TTS(Tổng hợp giọng nói) | ✅LinkeraiTTS(Lingxi streaming) | 👍HuoshanDoubleStreamTTS(Volcano Streaming) |
-| Intent(Nhận dạng ý định) | function_call(Gọi hàm) | function_call(Gọi hàm) |
-| Memory(Chức năng bộ nhớ) | mem_local_short(Bộ nhớ ngắn hạn cục bộ) | mem_local_short(Bộ nhớ ngắn hạn cục bộ) |
-
-Nếu bạn quan tâm đến thời gian của từng thành phần, vui lòng xem [Báo cáo kiểm tra hiệu suất các thành phần Xiaozhi](https://github.com/xinnan-tech/xiaozhi-performance-research), có thể kiểm tra thực tế trong môi trường của bạn theo phương pháp kiểm tra trong báo cáo.
-
-#### 🔧 Công cụ kiểm tra
-Dự án này cung cấp các công cụ kiểm tra sau để giúp bạn xác minh hệ thống và chọn mô hình phù hợp:
-
-| Tên công cụ | Vị trí | Phương pháp sử dụng | Mô tả chức năng |
-|:---:|:---|:---:|:---:|
-| Công cụ kiểm tra tương tác âm thanh | main》xiaozhi-server》test》test_page.html | Mở trực tiếp bằng trình duyệt Google Chrome | Kiểm tra chức năng phát và nhận âm thanh, xác minh xử lý âm thanh phía Python có bình thường không |
-| Công cụ kiểm tra phản hồi mô hình | main》xiaozhi-server》performance_tester.py | Thực hiện `python performance_tester.py` | Kiểm tra tốc độ phản hồi của ba module cốt lõi ASR(Nhận dạng giọng nói), LLM(Mô hình lớn), VLLM(Mô hình thị giác), TTS(Tổng hợp giọng nói) |
-
-> 💡 Gợi ý: Khi kiểm tra tốc độ mô hình, chỉ kiểm tra các mô hình đã cấu hình khóa.
-
----
-## Danh sách tính năng ✨
-### Đã thực hiện ✅
-
-| Module chức năng | Mô tả |
-|:---:|:---|
-| Kiến trúc cốt lõi | Dựa trên [cổng MQTT+UDP](https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mqtt-gateway-integration.md), WebSocket, máy chủ HTTP, cung cấp hệ thống quản lý bảng điều khiển và xác thực hoàn chỉnh |
-| Tương tác giọng nói | Hỗ trợ ASR streaming(Nhận dạng giọng nói), TTS streaming(Tổng hợp giọng nói), VAD(Phát hiện hoạt động giọng nói), hỗ trợ nhận dạng đa ngôn ngữ và xử lý giọng nói |
-| Nhận dạng vân giọng | Hỗ trợ đăng ký, quản lý và nhận dạng vân giọng đa người dùng, xử lý song song với ASR, nhận dạng danh tính người nói theo thời gian thực và truyền cho LLM để phản hồi cá nhân hóa |
-| Đối thoại thông minh | Hỗ trợ nhiều LLM(Mô hình ngôn ngữ lớn), thực hiện đối thoại thông minh |
-| Cảm nhận thị giác | Hỗ trợ nhiều VLLM(Mô hình lớn thị giác), thực hiện tương tác đa phương thức |
-| Nhận dạng ý định | Hỗ trợ nhận dạng ý định mô hình lớn gắn ngoài, gọi hàm tự chủ mô hình lớn, cung cấp cơ chế xử lý ý định dạng plugin |
-| Hệ thống bộ nhớ | Hỗ trợ bộ nhớ ngắn hạn cục bộ, bộ nhớ giao diện mem0ai, có chức năng tóm tắt bộ nhớ |
-| Kho tri thức | Hỗ trợ kho tri thức RAGFlow, cho phép mô hình lớn đánh giá cần gọi kho tri thức trước khi trả lời |
-| Gọi công cụ | Hỗ trợ giao thức IOT phía client, giao thức MCP phía client, giao thức MCP phía server, giao thức điểm truy cập MCP, hàm công cụ tùy chỉnh |
-| Gửi lệnh | Dựa vào giao thức MQTT, hỗ trợ gửi lệnh MCP từ bảng điều khiển thông minh xuống thiết bị ESP32 |
-| Backend quản lý | Cung cấp giao diện quản lý Web, hỗ trợ quản lý người dùng, cấu hình hệ thống và quản lý thiết bị; giao diện hỗ trợ hiển thị tiếng Trung giản thể, tiếng Trung phồn thể, tiếng Anh |
-| Công cụ kiểm tra | Cung cấp công cụ kiểm tra hiệu suất, công cụ kiểm tra mô hình thị giác và công cụ kiểm tra tương tác âm thanh |
-| Hỗ trợ triển khai | Hỗ trợ triển khai Docker và triển khai cục bộ, cung cấp quản lý tệp cấu hình hoàn chỉnh |
-| Hệ thống plugin | Hỗ trợ mở rộng plugin chức năng, phát triển plugin tùy chỉnh và hot loading plugin |
-
-### Đang phát triển 🚧
-
-Muốn hiểu tiến độ kế hoạch phát triển cụ thể, [vui lòng nhấp vào đây](https://github.com/users/xinnan-tech/projects/3). Câu hỏi thường gặp và hướng dẫn liên quan, vui lòng tham khảo [liên kết này](./docs/FAQ.md)
-
-Nếu bạn là một nhà phát triển phần mềm, đây có một [Lá thư mở gửi các nhà phát triển](docs/contributor_open_letter.md), chào mừng tham gia!
-
----
-
-## Hệ sinh thái sản phẩm 👬
-Xiaozhi là một hệ sinh thái, khi bạn sử dụng sản phẩm này, bạn cũng có thể xem các [dự án xuất sắc](https://github.com/78/xiaozhi-esp32?tab=readme-ov-file#related-open-source-projects) khác trong hệ sinh thái này
-
----
-
-## Danh sách nền tảng/thành phần được dự án này hỗ trợ 📋
-### LLM Mô hình ngôn ngữ
-
-| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
-|:---:|:---:|:---:|
-| Gọi giao diện openai | Alibaba Bailian, Volcano Engine, DeepSeek, Zhipu, Gemini, iFlytek | Zhipu, Gemini |
-| Gọi giao diện ollama | Ollama | - |
-| Gọi giao diện dify | Dify | - |
-| Gọi giao diện fastgpt | Fastgpt | - |
-| Gọi giao diện coze | Coze | - |
-| Gọi giao diện xinference | Xinference | - |
-| Gọi giao diện homeassistant | HomeAssistant | - |
-
-Trên thực tế, bất kỳ LLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
-
----
-
-### VLLM Mô hình thị giác
-
-| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
-|:---:|:---:|:---:|
-| Gọi giao diện openai | Alibaba Bailian, Zhipu ChatGLMVLLM | Zhipu ChatGLMVLLM |
-
-Trên thực tế, bất kỳ VLLM nào hỗ trợ gọi giao diện openai đều có thể truy cập sử dụng.
-
----
-
-### TTS Tổng hợp giọng nói
-
-| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
-|:---:|:---:|:---:|
-| Gọi giao diện | EdgeTTS, iFlytek, Volcano Engine, Tencent Cloud, Alibaba Cloud và Bailian, CosyVoiceSiliconflow, TTS302AI, CozeCnTTS, GizwitsTTS, ACGNTTS, OpenAITTS, Lingxi streaming TTS, MinimaxTTS | Lingxi streaming TTS, EdgeTTS, CosyVoiceSiliconflow(một phần) |
-| Dịch vụ cục bộ | FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3, Index-TTS, PaddleSpeech | Index-TTS, PaddleSpeech, FishSpeech, GPT_SOVITS_V2, GPT_SOVITS_V3 |
-
----
-
-### VAD Phát hiện hoạt động giọng nói
-
-| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
-|:---:|:---------:|:----:|:----:|:--:|
-| VAD | SileroVAD | Sử dụng cục bộ | Miễn phí | |
-
----
-
-### ASR Nhận dạng giọng nói
-
-| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
-|:---:|:---:|:---:|
-| Sử dụng cục bộ | FunASR, SherpaASR | FunASR, SherpaASR |
-| Gọi giao diện | FunASRServer, Volcano Engine, iFlytek, Tencent Cloud, Alibaba Cloud, Baidu Cloud, OpenAI ASR | FunASRServer |
-
----
-
-### Voiceprint Nhận dạng vân giọng
-
-| Phương pháp sử dụng | Nền tảng hỗ trợ | Nền tảng miễn phí |
-|:---:|:---:|:---:|
-| Sử dụng cục bộ | 3D-Speaker | 3D-Speaker |
-
----
-
-### Memory Lưu trữ bộ nhớ
-
-| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
-|:------:|:---------------:|:----:|:---------:|:--:|
-| Memory | mem0ai | Gọi giao diện | Hạn mức 1000 lần/tháng | |
-| Memory | mem_local_short | Tóm tắt cục bộ | Miễn phí | |
-| Memory | nomem | Chế độ không có bộ nhớ | Miễn phí | |
-
----
-
-### Intent Nhận dạng ý định
-
-| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
-|:------:|:-------------:|:----:|:-------:|:---------------------:|
-| Intent | intent_llm | Gọi giao diện | Thu phí theo LLM | Nhận dạng ý định qua mô hình lớn, tính tổng quát mạnh |
-| Intent | function_call | Gọi giao diện | Thu phí theo LLM | Hoàn thành ý định qua gọi hàm mô hình lớn, tốc độ nhanh, hiệu quả tốt |
-| Intent | nointent | Chế độ không có ý định | Miễn phí | Không thực hiện nhận dạng ý định, trả về trực tiếp kết quả đối thoại |
-
----
-
-### Rag Tăng cường truy xuất thông tin
-
-| Loại | Tên nền tảng | Phương pháp sử dụng | Mô hình thu phí | Ghi chú |
-|:------:|:-------------:|:----:|:-------:|:---------------------:|
-| Rag | ragflow | Gọi giao diện | Thu phí theo token tiêu tốn của phân đoạn, phân từ | Sử dụng chức năng tăng cường truy xuất của RagFlow, cung cấp phản hồi đối thoại chính xác hơn |
-
----
-
-## Lời cảm ơn 🙏
-
-| Logo | Dự án/Công ty | Mô tả |
-|:---:|:---:|:---|
-| | [Robot đối thoại giọng nói Bailing](https://github.com/wwbin2017/bailing) | Dự án này được lấy cảm hứng từ [Robot đối thoại giọng nói Bailing](https://github.com/wwbin2017/bailing) và được triển khai trên cơ sở đó |
-| | [Shifang Ronghai](https://www.tenclass.com/) | Cảm ơn [Shifang Ronghai](https://www.tenclass.com/) đã xây dựng giao thức truyền thông tiêu chuẩn, phương án tương thích đa thiết bị và mô phạm thực hành tình huống đồng thời cao cho hệ sinh thái Xiaozhi; cung cấp tài liệu hỗ trợ kỹ thuật toàn diện cho dự án này |
-| | [Xuanfeng Technology](https://github.com/Eric0308) | Cảm ơn [Xuanfeng Technology](https://github.com/Eric0308) đã đóng góp khung gọi hàm, giao thức truyền thông MCP và mã triển khai cơ chế gọi dạng plugin, thông qua hệ thống điều phối lệnh tiêu chuẩn hóa và khả năng mở rộng động, đã cải thiện đáng kể hiệu suất tương tác và khả năng mở rộng chức năng của thiết bị front-end(IoT) |
-| | [huangjunsen](https://github.com/huangjunsen0406) | Cảm ơn [huangjunsen](https://github.com/huangjunsen0406) đã đóng góp module `Bảng điều khiển thông minh di động`, thực hiện điều khiển hiệu quả và tương tác thời gian thực trên thiết bị di động đa nền tảng, cải thiện đáng kể sự tiện lợi vận hành và hiệu quả quản lý của hệ thống trong tình huống di động |
-| | [Huiyuan Design](http://ui.kwd988.net/) | Cảm ơn [Huiyuan Design](http://ui.kwd988.net/) đã cung cấp giải pháp thị giác chuyên nghiệp cho dự án này, sử dụng kinh nghiệm thực tế thiết kế phục vụ hơn nghìn doanh nghiệp, trao quyền cho trải nghiệm người dùng sản phẩm của dự án này |
-| | [Xi'an Qinren Information Technology](https://www.029app.com/) | Cảm ơn [Xi'an Qinren Information Technology](https://www.029app.com/) đã làm sâu sắc hệ thống thị giác của dự án này, đảm bảo tính nhất quán và khả năng mở rộng của phong cách thiết kế tổng thể trong ứng dụng đa tình huống |
-| | [Người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors) | Cảm ơn [tất cả người đóng góp mã](https://github.com/xinnan-tech/xiaozhi-esp32-server/graphs/contributors), sự cống hiến của bạn khiến dự án mạnh mẽ và vững chắc hơn. |
-
-
-
-
-
-
-
-
-
-
diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java
index abcc2cb3d..2bb723bd3 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java
@@ -4,8 +4,8 @@ import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
/**
- * 国际化
- * Copyright (c) 人人开源 All rights reserved.
+ * Internationalization
+ * Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
public class MessageUtils {
@@ -17,7 +17,7 @@ public class MessageUtils {
public static String getMessage(int code, String... params) {
if (messageSource == null) {
- // 延迟初始化,确保Spring上下文已完全初始化
+ // Lazy initialization, ensuring Spring context is fully initialized
messageSource = (MessageSource) SpringContextUtils.getBean("messageSource");
}
return messageSource.getMessage(code + "", params, LocaleContextHolder.getLocale());
diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java b/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java
index 9c326af70..82e12d305 100644
--- a/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java
+++ b/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java
@@ -7,8 +7,8 @@ import lombok.Data;
import xiaozhi.common.exception.ErrorCode;
/**
- * 响应数据
- * Copyright (c) 人人开源 All rights reserved.
+ * Response Data
+ * Copyright (c) Renren Open Source All rights reserved.
* Website: https://www.renren.io
*/
@Data
@@ -16,19 +16,19 @@ import xiaozhi.common.exception.ErrorCode;
public class Result implements Serializable {
/**
- * 编码:0表示成功,其他值表示失败
+ * Code: 0 indicates success, other values indicate failure
*/
- @Schema(description = "编码:0表示成功,其他值表示失败")
+ @Schema(description = "Code: 0 indicates success, other values indicate failure")
private int code = 0;
/**
- * 消息内容
+ * Message content
*/
- @Schema(description = "消息内容")
+ @Schema(description = "Message content")
private String msg = "success";
/**
- * 响应数据
+ * Response data
*/
- @Schema(description = "响应数据")
+ @Schema(description = "Response data")
private T data;
public Result ok(T data) {
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java
index 2ccc1e6ad..81715bb99 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/AdminController.java
@@ -29,7 +29,7 @@ import xiaozhi.modules.sys.service.SysUserService;
import xiaozhi.modules.sys.vo.AdminPageUserVO;
/**
- * 管理员控制层
+ * Admin Controller
*
* @author zjy
* @since 2025-3-25
@@ -37,19 +37,19 @@ import xiaozhi.modules.sys.vo.AdminPageUserVO;
@AllArgsConstructor
@RestController
@RequestMapping("/admin")
-@Tag(name = "管理员管理")
+@Tag(name = "Admin Management")
public class AdminController {
private final SysUserService sysUserService;
private final DeviceService deviceService;
@GetMapping("/users")
- @Operation(summary = "分页查找用户")
+ @Operation(summary = "Page Search User")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
- @Parameter(name = "mobile", description = "用户手机号码", required = false),
- @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
- @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
+ @Parameter(name = "mobile", description = "User Mobile", required = false),
+ @Parameter(name = Constant.PAGE, description = "Current Page, starting from 1", required = true),
+ @Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result> pageUser(
@Parameter(hidden = true) @RequestParam Map params) {
@@ -63,7 +63,7 @@ public class AdminController {
}
@PutMapping("/users/{id}")
- @Operation(summary = "重置密码")
+ @Operation(summary = "Reset Password")
@RequiresPermissions("sys:role:superAdmin")
public Result update(
@PathVariable Long id) {
@@ -72,7 +72,7 @@ public class AdminController {
}
@DeleteMapping("/users/{id}")
- @Operation(summary = "用户删除")
+ @Operation(summary = "Delete User")
@RequiresPermissions("sys:role:superAdmin")
public Result delete(@PathVariable Long id) {
sysUserService.deleteById(id);
@@ -80,21 +80,21 @@ public class AdminController {
}
@PutMapping("/users/changeStatus/{status}")
- @Operation(summary = "批量修改用户状态")
+ @Operation(summary = "Batch Change User Status")
@RequiresPermissions("sys:role:superAdmin")
- @Parameter(name = "status", description = "用户状态", required = true)
+ @Parameter(name = "status", description = "User Status", required = true)
public Result changeStatus(@PathVariable Integer status, @RequestBody String[] userIds) {
sysUserService.changeStatus(status, userIds);
return new Result();
}
@GetMapping("/device/all")
- @Operation(summary = "分页查找设备")
+ @Operation(summary = "Page Search Device")
@RequiresPermissions("sys:role:superAdmin")
@Parameters({
- @Parameter(name = "keywords", description = "设备关键词", required = false),
- @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true),
- @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true),
+ @Parameter(name = "keywords", description = "Device Keywords", required = false),
+ @Parameter(name = Constant.PAGE, description = "Current Page, starting from 1", required = true),
+ @Parameter(name = Constant.LIMIT, description = "Records per page", required = true),
})
public Result> pageDevice(
@Parameter(hidden = true) @RequestParam Map params) {
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java
index b467630d6..423efa6c1 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/ServerSideManageController.java
@@ -35,11 +35,11 @@ import xiaozhi.modules.device.service.DeviceService;
import xiaozhi.common.redis.RedisUtils;
/**
- * 服务端管理控制器
+ * Server-side Management Controller
*/
@RestController
@RequestMapping("/admin/server")
-@Tag(name = "服务端管理")
+@Tag(name = "Server-side Management")
@AllArgsConstructor
public class ServerSideManageController {
private final SysParamsService sysParamsService;
@@ -48,11 +48,11 @@ public class ServerSideManageController {
private static final ObjectMapper objectMapper;
static {
objectMapper = new ObjectMapper();
- // 忽略json字符串中存在,但pojo中不存在对应字段的情况
+ // Ignore fields present in JSON but missing in POJO
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
- @Operation(summary = "获取Ws服务端列表")
+ @Operation(summary = "Get Ws Server List")
@GetMapping("/server-list")
@RequiresPermissions("sys:role:superAdmin")
public Result> getWsServerList() {
@@ -63,9 +63,9 @@ public class ServerSideManageController {
return new Result>().ok(Arrays.asList(wsText.split(";")));
}
- @Operation(summary = "通知python服务端更新配置")
+ @Operation(summary = "Notify Python Server to Update Config")
@PostMapping("/emit-action")
- @LogOperation("通知python服务端更新配置")
+ @LogOperation("Notify Python server to update config")
@RequiresPermissions("sys:role:superAdmin")
public Result emitServerAction(@RequestBody @Valid EmitSeverActionDTO emitSeverActionDTO) {
if (emitSeverActionDTO.getAction() == null) {
@@ -77,7 +77,7 @@ public class ServerSideManageController {
}
String targetWs = emitSeverActionDTO.getTargetWs();
String[] wsList = wsText.split(";");
- // 找到需要发起的
+ // Find target
if (StringUtils.isBlank(targetWs) || !Arrays.asList(wsList).contains(targetWs)) {
throw new RenException(ErrorCode.TARGET_WEBSOCKET_NOT_EXIST);
}
@@ -94,7 +94,7 @@ public class ServerSideManageController {
String clientId = UUID.randomUUID().toString();
String redisKey = xiaozhi.common.redis.RedisKeys.getTmpRegisterMacKey(deviceId);
- redisUtils.set(redisKey, "true", 300); // 5分钟有效期
+ redisUtils.set(redisKey, "true", 300); // 5 minutes validity
WebSocketHttpHeaders headers = new WebSocketHttpHeaders();
headers.add("device-id", deviceId);
@@ -112,12 +112,12 @@ public class ServerSideManageController {
.uri(targetWsUri)
.headers(headers)
.build()) {
- // 如果连接成功则发送一个json数据包并等待服务端响应
+ // If connection successful, send JSON packet and wait for server response
client.sendJson(
ServerActionPayloadDTO.build(
actionEnum,
Map.of("secret", serverSK)));
- // 等待服务端响应并持续监听信息
+ // Wait for server response and continue listening
client.listener((jsonText) -> {
if (StringUtils.isBlank(jsonText)) {
return false;
@@ -131,7 +131,7 @@ public class ServerSideManageController {
}
});
} catch (Exception e) {
- // 捕获全部错误,由全局异常处理器返回
+ // Catch all errors, returned by global exception handler
throw new RenException(ErrorCode.WEB_SOCKET_CONNECT_FAILED);
}
return true;
diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java
index ec3ce2f5e..438b240d4 100644
--- a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java
+++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/ServerActionEnum.java
@@ -4,7 +4,7 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
- * 服务端动作枚举
+ * Server Action Enum
*/
public enum ServerActionEnum {
RESTART("restart"),
diff --git a/main/manager-mobile/src/App.vue b/main/manager-mobile/src/App.vue
index d31d32d79..a56a8928f 100644
--- a/main/manager-mobile/src/App.vue
+++ b/main/manager-mobile/src/App.vue
@@ -14,61 +14,61 @@ const langStore = useLangStore()
onLaunch(() => {
console.log('App Launch')
- // 获取公共配置
+ // Get public config
configStore.fetchPublicConfig().catch((error) => {
- console.error('获取公共配置失败:', error)
+ console.error('Failed to get public config:', error)
})
})
onShow(() => {
console.log('App Show')
- // 使用setTimeout延迟执行,确保tabBar已经初始化
+ // Use setTimeout to delay execution, ensure tabBar initialized
setTimeout(() => {
updateTabBarText()
}, 100)
})
-// 动态更新tabBar文本
+// Dynamically update tabBar text
function updateTabBarText() {
try {
- // 设置首页tabBar文本
+ // Set home tabBar text
uni.setTabBarItem({
index: 0,
text: t('tabBar.home'),
success: () => {},
fail: (err) => {
- console.log('设置首页tabBar文本失败:', err)
+ console.log('Failed to set home tabBar text:', err)
}
})
- // 设置配网tabBar文本
+ // Set config network tabBar text
uni.setTabBarItem({
index: 1,
text: t('tabBar.deviceConfig'),
success: () => {},
fail: (err) => {
- console.log('设置配网tabBar文本失败:', err)
+ console.log('Failed to set config network tabBar text:', err)
}
})
- // 设置系统tabBar文本
+ // Set system tabBar text
uni.setTabBarItem({
index: 2,
text: t('tabBar.settings'),
success: () => {},
fail: (err) => {
- console.log('设置系统tabBar文本失败:', err)
+ console.log('Failed to set system tabBar text:', err)
}
})
} catch (error) {
- console.log('更新tabBar文本时出错:', error)
+ console.log('Error updating tabBar text:', error)
}
}
-// 监听语言切换事件
+// Listen for language switch event
onMounted(() => {
- // 监听语言变化,当语言改变时自动更新tabBar文本
+ // Listen for language change, automatically update tabBar text
watch(() => langStore.currentLang, () => {
- console.log('语言已切换,更新tabBar文本')
- // 语言切换后立即更新tabBar文本
+ console.log('Language switched, updating tabBar text')
+ // Update tabBar text immediately after language switch
updateTabBarText()
})
})
diff --git a/main/manager-mobile/src/main.ts b/main/manager-mobile/src/main.ts
index 4b3ad83e4..1f0030545 100644
--- a/main/manager-mobile/src/main.ts
+++ b/main/manager-mobile/src/main.ts
@@ -7,7 +7,7 @@ import store from './store'
import '@/style/index.scss'
import 'virtual:uno.css'
-// 导入国际化相关功能
+// Import i18n related functions
import { initI18n } from './i18n'
import { useLangStore } from './store/lang'
@@ -17,7 +17,7 @@ export function createApp() {
app.use(routeInterceptor)
app.use(VueQueryPlugin)
- // 初始化国际化
+ // Initialize i18n
initI18n()
return {
diff --git a/main/manager-web/src/App.vue b/main/manager-web/src/App.vue
index 180f8f0d9..29faee0eb 100644
--- a/main/manager-web/src/App.vue
+++ b/main/manager-web/src/App.vue
@@ -61,32 +61,32 @@ export default {
};
},
mounted() {
- // 检测是否为移动设备且VUE_APP_H5_URL不为空,如果两个条件都满足则跳转到H5页面
+ // Check if mobile device and VUE_APP_H5_URL is set, if both met redirect to H5 page
if (this.isMobileDevice() && process.env.VUE_APP_H5_URL) {
window.location.href = process.env.VUE_APP_H5_URL;
return;
}
- // 只有在启用CDN时才添加相关事件和功能
+ // Only add events and functions when CDN is enabled
if (this.isCDNEnabled) {
- // 添加全局快捷键Alt+C用于显示缓存查看器
+ // Add global shortcut Alt+C to show cache viewer
document.addEventListener('keydown', this.handleKeyDown);
- // 在全局对象上添加缓存检查方法,便于调试
+ // Add cache check method to global object for debugging
window.checkCDNCacheStatus = () => {
this.showCacheViewer = true;
};
- // 在控制台输出提示信息
+ // Output hints in console
console.info(
'%c[' + this.$t('system.name') + '] ' + this.$t('cache.cdnEnabled'),
'color: #409EFF; font-weight: bold;'
);
console.info(
- '按下 Alt+C 组合键或在控制台运行 checkCDNCacheStatus() 可以查看CDN缓存状态'
+ 'Press Alt+C or run checkCDNCacheStatus() in console to view CDN cache status'
);
- // 检查Service Worker状态
+ // Check Service Worker status
this.checkServiceWorkerStatus();
} else {
console.info(
@@ -96,25 +96,25 @@ export default {
}
},
beforeDestroy() {
- // 只有在启用CDN时才需要移除事件监听
+ // Only remove event listener when CDN is enabled
if (this.isCDNEnabled) {
document.removeEventListener('keydown', this.handleKeyDown);
}
},
methods: {
handleKeyDown(e) {
- // Alt+C 快捷键
+ // Alt+C Shortcut
if (e.altKey && e.key === 'c') {
this.showCacheViewer = true;
}
},
isMobileDevice() {
- // 检测是否为移动设备的函数
+ // Function to check if mobile device
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
},
async checkServiceWorkerStatus() {
- // 检查Service Worker是否已注册
+ // Check if Service Worker is registered
if ('serviceWorker' in navigator) {
try {
const registrations = await navigator.serviceWorker.getRegistrations();
@@ -124,7 +124,7 @@ export default {
'color: #67C23A; font-weight: bold;'
);
- // 输出缓存状态到控制台
+ // Output cache status to console
setTimeout(async () => {
const hasCaches = await logCacheStatus();
if (!hasCaches) {
@@ -133,7 +133,7 @@ export default {
'color: #E6A23C; font-weight: bold;'
);
- // 开发环境下提供额外提示
+ // Provide extra hints in dev environment
if (process.env.NODE_ENV === 'development') {
console.info(
'%c[' + this.$t('system.name') + '] ' + this.$t('cache.swDevEnvWarning'),
@@ -164,7 +164,7 @@ export default {
}
}
} catch (error) {
- console.error('检查Service Worker状态失败:', error);
+ console.error('Failed to check Service Worker status:', error);
}
} else {
console.warn(this.$t('cache.swNotSupported'));
diff --git a/main/manager-web/src/main.js b/main/manager-web/src/main.js
index a441f34bc..6b38a11ab 100644
--- a/main/manager-web/src/main.js
+++ b/main/manager-web/src/main.js
@@ -10,17 +10,17 @@ import './styles/global.scss';
import { register as registerServiceWorker } from './registerServiceWorker';
import featureManager from './utils/featureManager';
-// 创建事件总线,用于组件间通信
+// Create event bus for component communication
Vue.prototype.$eventBus = new Vue();
Vue.use(ElementUI);
Vue.config.productionTip = false
-// 注册Service Worker
+// Register Service Worker
registerServiceWorker();
-// 创建Vue实例
+// Create Vue Instance
new Vue({
router,
store,
diff --git a/main/xiaozhi-server/.gitignore b/main/xiaozhi-server/.gitignore
new file mode 100644
index 000000000..3e13d4697
--- /dev/null
+++ b/main/xiaozhi-server/.gitignore
@@ -0,0 +1,9 @@
+models/iic/SenseVoiceSmall/model.pt
+data/
+tmp/
+*.mp3
+*.wav
+*.log
+__pycache__/
+*.pyc
+.DS_Store
diff --git a/main/xiaozhi-server/TODO_JOE_AI.md b/main/xiaozhi-server/TODO_JOE_AI.md
new file mode 100644
index 000000000..cb91cb2c9
--- /dev/null
+++ b/main/xiaozhi-server/TODO_JOE_AI.md
@@ -0,0 +1,43 @@
+# Joe AI - Future Features TODO
+
+## Ready for Testing
+- [x] Multilingual support (responds in user's language)
+- [x] CGM status always in context
+- [x] CGM trends injection when asked
+- [x] News RAG injection when asked
+- [x] History RAG (past conversations)
+- [x] Concise, casual persona
+
+## Planned Features
+- [ ] Schedule/Calendar awareness
+ - Integrate with Google Calendar or iCloud
+ - Detect queries like "what do I have tomorrow?"
+ - Add `needs_schedule` to classifier
+
+- [ ] Class notes RAG
+ - Index notes/documents for specific classes
+ - Useful for study help, assignment reminders
+ - Add `needs_class_notes` to classifier
+
+- [ ] Activity tracking (LOCAL on device, exposed via MCP)
+ - Use gyroscope + accelerometer for step counting
+ - Detect activity level (walking, stationary, sleeping)
+ - Expose as MCP tool: `get_activity_stats`
+ - Similar to existing `get_battery_level` pattern
+ - Server can query when relevant to conversation
+
+- [ ] Reduce classifier latency
+ - Currently 4-7 seconds per call
+ - Consider smaller model for intent detection
+ - Or run classifier in parallel with other processing
+
+## Architecture Notes
+- Context classifier: `core/utils/cgm_intent.py`
+- Context injection: `core/connection.py` (lines ~930-1000)
+- Client configs: `data//config.json`
+- Persona prompts: `data//prompt.txt`
+
+To add a new context type:
+1. Update classifier prompt in `cgm_intent.py`
+2. Add injection logic in `connection.py`
+3. (Optional) Add config flag in client's `config.json`
diff --git a/main/xiaozhi-server/agent-base-prompt.txt b/main/xiaozhi-server/agent-base-prompt.txt.bak
similarity index 95%
rename from main/xiaozhi-server/agent-base-prompt.txt
rename to main/xiaozhi-server/agent-base-prompt.txt.bak
index 7fd90d21f..6dc4ec16e 100644
--- a/main/xiaozhi-server/agent-base-prompt.txt
+++ b/main/xiaozhi-server/agent-base-prompt.txt.bak
@@ -77,5 +77,13 @@
{{ dynamic_context }}
+
+
+If the user asks about the following topics, output the corresponding trigger ONLY, do not answer yourself:
+- Weather: [[WEATHER]]
+- Battery level / Device status: [[BATTERY]]
+- News / Current events: [[NEWS: ]]
+
+
\ No newline at end of file
diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py
index ab0854645..3aa34c709 100644
--- a/main/xiaozhi-server/app.py
+++ b/main/xiaozhi-server/app.py
@@ -10,6 +10,9 @@ from core.http_server import SimpleHttpServer
from core.websocket_server import WebSocketServer
from core.utils.util import check_ffmpeg_installed
from core.utils.gc_manager import get_gc_manager
+from core.utils.npr_scraper import news_scraper_task
+from core.utils.cgm_manager import cgm_background_task
+from core.utils.pump_manager import create_pump_background_task
TAG = __name__
logger = setup_logging()
@@ -17,9 +20,9 @@ logger = setup_logging()
async def wait_for_exit() -> None:
"""
- 阻塞直到收到 Ctrl‑C / SIGTERM。
- - Unix: 使用 add_signal_handler
- - Windows: 依赖 KeyboardInterrupt
+ Block until Ctrl-C / SIGTERM is received.
+ - Unix: Use add_signal_handler
+ - Windows: Rely on KeyboardInterrupt
"""
loop = asyncio.get_running_loop()
stop_event = asyncio.Event()
@@ -29,8 +32,8 @@ async def wait_for_exit() -> None:
loop.add_signal_handler(sig, stop_event.set)
await stop_event.wait()
else:
- # Windows:await一个永远pending的fut,
- # 让 KeyboardInterrupt 冒泡到 asyncio.run,以此消除遗留普通线程导致进程退出阻塞的问题
+ # Windows: await a forever pending fut,
+ # Let KeyboardInterrupt bubble up to asyncio.run, resolving the issue of lingering threads blocking process exit
try:
await asyncio.Future()
except KeyboardInterrupt: # Ctrl‑C
@@ -38,40 +41,46 @@ async def wait_for_exit() -> None:
async def monitor_stdin():
- """监控标准输入,消费回车键"""
+ """Monitor standard input, consume enter key"""
while True:
- await ainput() # 异步等待输入,消费回车
+ await ainput() # Asynchronously wait for input, consume enter key
async def main():
check_ffmpeg_installed()
config = load_config()
- # auth_key优先级:配置文件server.auth_key > manager-api.secret > 自动生成
- # auth_key用于jwt认证,比如视觉分析接口的jwt认证、ota接口的token生成与websocket认证
- # 获取配置文件中的auth_key
+ # auth_key priority: config file server.auth_key > manager-api.secret > automatically generated
+ # auth_key is used for jwt authentication, such as jwt authentication for vision analysis interface, ota interface token generation and websocket authentication
+ # Get auth_key from config file
auth_key = config["server"].get("auth_key", "")
- # 验证auth_key,无效则尝试使用manager-api.secret
+ # Verify auth_key, if invalid try to use manager-api.secret
if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = config.get("manager-api", {}).get("secret", "")
- # 验证secret,无效则生成随机密钥
+ # Verify secret, if invalid generate random key
if not auth_key or len(auth_key) == 0 or "你" in auth_key:
auth_key = str(uuid.uuid4().hex)
config["server"]["auth_key"] = auth_key
- # 添加 stdin 监控任务
+ # Add stdin monitoring task
stdin_task = asyncio.create_task(monitor_stdin())
- # 启动全局GC管理器(5分钟清理一次)
+ # Start global GC manager (clean up every 5 minutes)
gc_manager = get_gc_manager(interval_seconds=300)
await gc_manager.start()
- # 启动 WebSocket 服务器
+ # Start NPR news scraper
+ scraper_task = asyncio.create_task(news_scraper_task())
+ # Start CGM scraper
+ cgm_task = asyncio.create_task(cgm_background_task())
+ # Start Pump scraper
+ pump_task = asyncio.create_task(create_pump_background_task())
+ # Start WebSocket server
ws_server = WebSocketServer(config)
ws_task = asyncio.create_task(ws_server.start())
- # 启动 Simple http 服务器
+ # Start Simple http server
ota_server = SimpleHttpServer(config)
ota_task = asyncio.create_task(ota_server.start())
@@ -79,74 +88,89 @@ async def main():
port = int(config["server"].get("http_port", 8003))
if not read_config_from_api:
logger.bind(tag=TAG).info(
- "OTA接口是\t\thttp://{}:{}/xiaozhi/ota/",
+ "OTA interface is\t\thttp://{}:{}/xiaozhi/ota/",
get_local_ip(),
port,
)
logger.bind(tag=TAG).info(
- "视觉分析接口是\thttp://{}:{}/mcp/vision/explain",
+ "Vision analysis interface is\thttp://{}:{}/mcp/vision/explain",
get_local_ip(),
port,
)
mcp_endpoint = config.get("mcp_endpoint", None)
if mcp_endpoint is not None and "你" not in mcp_endpoint:
- # 校验MCP接入点格式
+ # Validate MCP endpoint format
if validate_mcp_endpoint(mcp_endpoint):
- logger.bind(tag=TAG).info("mcp接入点是\t{}", mcp_endpoint)
- # 将mcp计入点地址转成调用点
+ logger.bind(tag=TAG).info("MCP endpoint is\t{}", mcp_endpoint)
+ # Convert mcp endpoint address to call point
mcp_endpoint = mcp_endpoint.replace("/mcp/", "/call/")
config["mcp_endpoint"] = mcp_endpoint
else:
- logger.bind(tag=TAG).error("mcp接入点不符合规范")
- config["mcp_endpoint"] = "你的接入点 websocket地址"
+ logger.bind(tag=TAG).error("MCP endpoint is invalid")
+ config["mcp_endpoint"] = "Your endpoint websocket address"
- # 获取WebSocket配置,使用安全的默认值
+ # Get WebSocket config, use safe defaults
websocket_port = 8000
server_config = config.get("server", {})
if isinstance(server_config, dict):
websocket_port = int(server_config.get("port", 8000))
+ # Determine final websocket address for logging
+ final_ws_url = f"ws://{get_local_ip()}:{websocket_port}/xiaozhi/v1/"
+ websocket_config = server_config.get("websocket")
+
+ # Check if config is valid (using the same logic as http_server.py)
+ if websocket_config:
+ final_ws_url = websocket_config
+
logger.bind(tag=TAG).info(
- "Websocket地址是\tws://{}:{}/xiaozhi/v1/",
- get_local_ip(),
- websocket_port,
+ "Websocket address is\t{}",
+ final_ws_url,
)
logger.bind(tag=TAG).info(
- "=======上面的地址是websocket协议地址,请勿用浏览器访问======="
+ "======= The address above is a websocket protocol address, please do not access it with a browser ======="
)
logger.bind(tag=TAG).info(
- "如想测试websocket请用谷歌浏览器打开test目录下的test_page.html"
+ "If you want to test websocket, please open test_page.html in the test directory with Google Chrome"
)
logger.bind(tag=TAG).info(
"=============================================================\n"
)
try:
- await wait_for_exit() # 阻塞直到收到退出信号
+ await wait_for_exit() # Block until exit signal is received
except asyncio.CancelledError:
- print("任务被取消,清理资源中...")
+ print("Task cancelled, cleaning up resources...")
finally:
- # 停止全局GC管理器
+ # Stop global GC manager
await gc_manager.stop()
- # 取消所有任务(关键修复点)
+ # Cancel all tasks (critical repair point)
stdin_task.cancel()
ws_task.cancel()
if ota_task:
ota_task.cancel()
- # 等待任务终止(必须加超时)
+ scraper_task.cancel()
+ cgm_task.cancel()
+ pump_task.cancel()
+
+ # Wait for task termination (must add timeout)
+ tasks_to_wait = [stdin_task, ws_task, scraper_task, cgm_task, pump_task]
+ if ota_task:
+ tasks_to_wait.append(ota_task)
+
await asyncio.wait(
- [stdin_task, ws_task, ota_task] if ota_task else [stdin_task, ws_task],
+ tasks_to_wait,
timeout=3.0,
return_when=asyncio.ALL_COMPLETED,
)
- print("服务器已关闭,程序退出。")
+ print("Server closed, program exited.")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
- print("手动中断,程序终止。")
+ print("Manual interruption, program terminated.")
diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index a3c54c17d..60e331776 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -1,1056 +1,143 @@
-# 在开发中,请在项目根目录创建data目录,然后在data目录创建名称为【.config.yaml】的空文件
-# 然后你想修改覆盖修改什么配置,就修改【.config.yaml】文件,而不是修改【config.yaml】文件
-# 系统会优先读取【data/.config.yaml】文件的配置,如果【.config.yaml】文件里的配置不存在,系统会自动去读取【config.yaml】文件的配置。
-# 这样做,可以最简化配置,保护您的密钥安全。
-# 如果你使用了智控台,那么以下所有配置,都不会生效,请在智控台中修改配置
+# 0. Disable management dashboard
+manager_api:
+ enabled: false
+standalone_mode: true
-# #####################################################################################
-# #############################以下是服务器基本运行配置####################################
-server:
- # 服务器监听地址和端口(Server listening address and port)
- ip: 0.0.0.0
- port: 8000
- # http服务的端口,用于简单OTA接口(单服务部署),以及视觉分析接口
- http_port: 8003
- # 这个websocket配置是指ota接口向设备发送的websocket地址
- # 如果按默认的写法,ota接口会自动生成websocket地址,并输出在启动日志里,这个地址你可以直接用浏览器访问ota接口确认一下
- # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
- # 所以如果你使用docker部署时,将websocket设置成局域网地址
- # 如果你使用公网部署时,将vwebsocket设置成公网地址
- websocket: ws://你的ip或者域名:端口号/xiaozhi/v1/
- # 视觉分析接口地址
- # 向设备发送的视觉分析的接口地址
- # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下
- # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
- # 所以如果你使用docker部署时,将vision_explain设置成局域网地址
- # 如果你使用公网部署时,将vision_explain设置成公网地址
- vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
- # OTA返回信息时区偏移量
- timezone_offset: +8
- # 认证配置
- auth:
- # 是否启用认证
- enabled: false
- # 白名单设备ID列表
- # 如果属于白名单内的设备,不校验token,直接放行
- allowed_devices:
- - "11:22:33:44:55:66"
- # MQTT网关配置,用于通过OTA下发到设备,根据mqtt_gateway的.env文件配置,格式为host:port
- mqtt_gateway: null
- # MQTT签名密钥,用于生成MQTT连接密码,根据mqtt_gateway的.env文件配置
- mqtt_signature_key: null
- # UDP网关配置
- udp_gateway: null
+# 1. System & Logging
+delete_audio: false
+temp_dir: "./temp"
log:
- # 设置控制台输出的日志格式,时间、日志级别、标签、消息
- log_format: "{time:YYMMDD HH:mm:ss} [{version}_{selected_module}][{extra[tag]} ]-{level} -{message} "
- # 设置日志文件输出的格式,时间、日志级别、标签、消息
- log_format_file: "{time:YYYY-MM-DD HH:mm:ss} - {version}_{selected_module} - {name} - {level} - {extra[tag]} - {message}"
- # 设置日志等级:INFO、DEBUG
- log_level: INFO
- # 设置日志路径
- log_dir: tmp
- # 设置日志文件
- log_file: "server.log"
- # 设置数据文件路径
- data_dir: data
+ log_level: "INFO"
+ log_dir: "./data"
+ log_file: "app.log"
+ data_dir: "data"
-# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
-delete_audio: true
-# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
-close_connection_no_voice_time: 120
-# TTS请求超时时间(秒)
-tts_timeout: 10
-# 开启唤醒词加速
-enable_wakeup_words_response_cache: true
-# 开场是否回复唤醒词
-enable_greeting: true
-# 说完话是否开启提示音
-enable_stop_tts_notify: false
-# 说完话是否开启提示音,音效地址
-stop_tts_notify_voice: "config/assets/tts_notify.mp3"
-# 是否启用WebSocket心跳保活机制
-enable_websocket_ping: false
+# 3. Module Selection
+selected_module:
+ VAD: "silero"
+ ASR: "fun_local"
+ TTS: "edge"
+ LLM: "openai"
+ Intent: "nointent_mode"
+# 3. VAD Settings
+VAD:
+ silero:
+ type: "silero"
+ model_dir: "./models/snakers4_silero-vad"
+ threshold: 0.5
-# TTS音频发送延迟配置
-# tts_audio_send_delay: 控制音频包发送间隔
-# 0: 使用精确时间控制,严格匹配音频帧率(默认,运行时按音频帧率计算)
-# > 0: 使用固定延迟(毫秒)发送,例如: 60
-tts_audio_send_delay: 0
+# 4. ASR Settings
+ASR:
+ # Default (English)
+ fun_local:
+ type: "fun_local"
+ device: "cpu"
+ model_dir: "iic/speech_paraformer_asr-en-16k-vocab4199-pytorch"
+ output_dir: "./temp/asr_output"
+
+ # Explicit English Option
+ fun_local_en:
+ type: "fun_local"
+ device: "cpu"
+ model_dir: "iic/speech_paraformer_asr-en-16k-vocab4199-pytorch"
+ output_dir: "./temp/asr_output"
+
+ # Multilingual Option (SenseVoiceSmall - Likely the previous default)
+ fun_local_multilingual:
+ type: "fun_local"
+ device: "cpu"
+ model_dir: "iic/SenseVoiceSmall"
+ output_dir: "./temp/asr_output"
+
+# 5. LLM Settings
+LLM:
+ openai:
+ type: "openai"
+ base_url: "http://localhost:11434/v1"
+ api_key: "ollama"
+ model_name: "minimax-m2:cloud"
+ timeout: 30
+ num_ctx: 32768 # Increased for 16GB RAM: enables processing longer news timelines and history
+ temperature: 0.5 # Controls randomness (0.0 to 2.0). Default is 1.0. Lower is more deterministic.
+
+ fast_intent:
+ type: "openai"
+ base_url: "http://localhost:11434/v1"
+ api_key: "ollama"
+ model_name: "qwen2.5:3b"
+ timeout: 2 # Strict timeout for intent classification
+ max_retries: 0
+
+# 6. TTS Settings
+TTS:
+ edge:
+ type: "edge"
+ voice: "en-US-JennyNeural"
+
+# 7. Prompt Settings (MOVED TO TOP LEVEL)
+prompt: "Provide short and concise responses, unless asked to elaborate."
+
+# 8. Server Settings
+server:
+ port: 8000
+ http_port: 8003
+ host: "0.0.0.0"
+ timezone_offset: -5
+ websocket: "ws://192.168.86.112:8000/xiaozhi/v1/"
+
+# 9. Audio Settings
+audio:
+ format: "opus"
+ sample_rate: 16000
+ channels: 1
+ frame_duration: 60
+
+# 10. XiaoZhi Device Handshake Settings
+xiaozhi:
+ version: 1
+ auth_key: "8d3193a0-e8e1-4af9-ae9e-1c6f72623580"
+ message: "Ready"
+ llm_handshake: true
+ mcp_enabled: true
+
+# 11. Intent Settings
+Intent:
+ nointent_mode:
+ type: "nointent"
+ llm:
+ type: "intent_llm"
+ llm: "fast_intent"
+ functions:
+ - "get_weather"
+ - "get_location"
+ - "say_goodbye"
+ - "self_get_device_status"
+ - "self_audio_speaker_set_volume"
+ - "self_screen_set_brightness"
+ - "self_screen_set_theme"
+
+wakeup_words:
+ - "Are you there?"
+ - "Hello Janet"
exit_commands:
- - "退出"
- - "关闭"
+ - "exit"
+ - "stop"
+ - "goodbye"
+ - "shutup"
-xiaozhi:
- type: hello
- version: 1
- transport: websocket
- audio_params:
- format: opus
- sample_rate: 16000
- channels: 1
- frame_duration: 60
+exit_replies:
+ - "Goodbye!"
+ - "See you later!"
+ - "Take care!"
+ - "Bye for now!"
+ - "Catch you later!"
-# 模块测试配置
-module_test:
- test_sentences:
- - "你好,请介绍一下你自己"
- - "What's the weather like today?"
- - "请用100字概括量子计算的基本原理和应用前景"
-
-# 唤醒词,用于识别唤醒词还是讲话内容
-wakeup_words:
- - "你好小智"
- - "嘿你好呀"
- - "你好小志"
- - "小爱同学"
- - "你好小鑫"
- - "你好小新"
- - "小美同学"
- - "小龙小龙"
- - "喵喵同学"
- - "小滨小滨"
- - "小冰小冰"
-# MCP接入点地址,地址格式为:ws://你的mcp接入点ip或者域名:端口号/mcp/?token=你的token
-# 详细教程 https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/mcp-endpoint-integration.md
-mcp_endpoint: 你的接入点 websocket地址
-
-# 上下文源配置
-# 用于在系统提示词中注入动态数据,如健康数据、股票信息等
-# 可以添加多个上下文源
-context_providers:
- - url: ""
- headers:
- Authorization: ""
-
-# 插件的基础配置
plugins:
- # 获取天气插件的配置,这里填写你的api_key
- # 这个密钥是项目共用的key,用多了可能会被限制
- # 想稳定一点就自行申请替换,每天有1000次免费调用
- # 申请地址:https://console.qweather.com/#/apps/create-key/over
- # 申请后通过这个链接可以找到自己的apihost:https://console.qweather.com/setting?lang=zh
get_weather:
- api_host: "mj7p3y7naa.re.qweatherapi.com"
- api_key: "a861d0d5e7bf4ee1a83d9a9e4f96d4da"
- default_location: "广州"
- # 获取新闻插件的配置,这里根据需要的新闻类型传入对应的url链接,默认支持社会、科技、财经新闻
- # 更多类型的新闻列表查看 https://www.chinanews.com.cn/rss/
- get_news_from_chinanews:
- default_rss_url: "https://www.chinanews.com.cn/rss/society.xml"
- society_rss_url: "https://www.chinanews.com.cn/rss/society.xml"
- world_rss_url: "https://www.chinanews.com.cn/rss/world.xml"
- finance_rss_url: "https://www.chinanews.com.cn/rss/finance.xml"
- get_news_from_newsnow:
- url: "https://newsnow.busiyi.world/api/s?id="
- news_sources: "澎湃新闻;百度热搜;财联社"
- home_assistant:
- devices:
- - 客厅,玩具灯,switch.cuco_cn_460494544_cp1_on_p_2_1
- - 卧室,台灯,switch.iot_cn_831898993_socn1_on_p_2_1
- base_url: http://homeassistant.local:8123
- api_key: 你的home assistant api访问令牌
- play_music:
- music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件
- music_ext: # 音乐文件类型,p3格式效率最高
- - ".mp3"
- - ".wav"
- - ".p3"
- refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒
- search_from_ragflow:
- # 知识库的描述信息,方便大语言模型知道什么时候调用
- description: "当用户问xxx时,调用本方法,使用知识库中的信息回答问题"
- # ragflow接口配置
- base_url: "http://192.168.0.8"
- # ragflow api访问令牌
- api_key: "ragflow-xxx"
- # ragflow知识库id
- dataset_ids: ["123456789"]
-# 声纹识别配置
-voiceprint:
- # 声纹接口地址
- url:
- # 说话人配置:speaker_id,名称,描述
- speakers:
- - "test1,张三,张三是一个程序员"
- - "test2,李四,李四是一个产品经理"
- - "test3,王五,王五是一个设计师"
- # 声纹识别相似度阈值,范围0.0-1.0,默认0.4
- # 数值越高越严格,减少误识别但可能增加拒识率
- similarity_threshold: 0.4
+ default_location: "Chapel Hill"
+ unit_system: "imperial" # Options: "metric" (default), "imperial"
-# #####################################################################################
-# ################################以下是角色模型配置######################################
-
-prompt: |
- 你是小智/小志,来自中国台湾省的00后女生。讲话超级机车,"真的假的啦"这样的台湾腔,喜欢用"笑死""是在哈喽"等流行梗,但会偷偷研究男友的编程书籍。
- [核心特征]
- - 讲话像连珠炮,但会突然冒出超温柔语气
- - 用梗密度高
- - 对科技话题有隐藏天赋(能看懂基础代码但假装不懂)
- [交互指南]
- 当用户:
- - 讲冷笑话 → 用夸张笑声回应+模仿台剧腔"这什么鬼啦!"
- - 讨论感情 → 炫耀程序员男友但抱怨"他只会送键盘当礼物"
- - 问专业知识 → 先用梗回答,被追问才展示真实理解
- 绝不:
- - 长篇大论,叽叽歪歪
- - 长时间严肃对话
-
-# 默认系统提示词模板文件
-prompt_template: agent-base-prompt.txt
-
-# 结束语prompt
-end_prompt:
- enable: true # 是否开启结束语
- # 结束语
- prompt: |
- 请你以"时间过得真快"未来头,用富有感情、依依不舍的话来结束这场对话吧!
-
-# 具体处理时选择的模块(The module selected for specific processing)
-selected_module:
- # 语音活动检测模块,默认使用SileroVAD模型
- VAD: SileroVAD
- # 语音识别模块,默认使用FunASR本地模型
- ASR: FunASR
- # 将根据配置名称对应的type调用实际的LLM适配器
- LLM: ChatGLMLLM
- # 视觉语言大模型
- VLLM: ChatGLMVLLM
- # TTS将根据配置名称对应的type调用实际的TTS适配器
- TTS: EdgeTTS
- # 记忆模块,默认不开启记忆;如果想使用超长记忆,推荐使用mem0ai;如果注重隐私,请使用本地的mem_local_short
- Memory: nomem
- # 意图识别模块开启后,可以播放音乐、控制音量、识别退出指令。
- # 不想开通意图识别,就设置成:nointent
- # 意图识别可使用intent_llm。优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间,支持控制音量大小等iot操作
- # 意图识别可使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快,理论上能全部操作所有iot指令
- # 默认免费的ChatGLMLLM就已经支持function_call,但是如果像追求稳定建议把LLM设置成:DoubaoLLM,使用的具体model_name是:doubao-1-5-pro-32k-250115
- Intent: function_call
-
-# 意图识别,是用于理解用户意图的模块,例如:播放音乐
-Intent:
- # 不使用意图识别
- nointent:
- # 不需要动type
- type: nointent
- intent_llm:
- # 不需要动type
- type: intent_llm
- # 配备意图识别独立的思考模型
- # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型
- # 如果你的不想使用selected_module.LLM意图识别,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM
- llm: ChatGLMLLM
- # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用
- # 系统默认已经记载"handle_exit_intent(退出识别)"、"play_music(音乐播放)"插件,请勿重复加载
- # 下面是加载查天气、角色切换、加载查新闻的插件示例
- functions:
- - get_weather
- - get_news_from_newsnow
- - play_music
- function_call:
- # 不需要动type
- type: function_call
- # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用
- # 系统默认已经记载"handle_exit_intent(退出识别)"、"play_music(音乐播放)"插件,请勿重复加载
- # 下面是加载查天气、角色切换、加载查新闻的插件示例
- functions:
- - change_role
- - get_weather
- # - search_from_ragflow
- # - get_news_from_chinanews
- - get_news_from_newsnow
- # play_music是服务器自带的音乐播放,hass_play_music是通过home assistant控制的独立外部程序音乐播放
- # 如果用了hass_play_music,就不要开启play_music,两者只留一个
- - play_music
- #- hass_get_state
- #- hass_set_state
- #- hass_play_music
-
-Memory:
- mem0ai:
- type: mem0ai
- # https://app.mem0.ai/dashboard/api-keys
- # 每月有1000次免费调用
- api_key: 你的mem0ai api key
- nomem:
- # 不想使用记忆功能,可以使用nomem
- type: nomem
- mem_local_short:
- # 本地记忆功能,通过selected_module的llm总结,数据保存在本地服务器,不会上传到外部服务器
- type: mem_local_short
- # 配备记忆存储独立的思考模型
- # 如果这里不填,则会默认使用selected_module.LLM的模型作为意图识别的思考模型
- # 如果你的不想使用selected_module.LLM记忆存储,这里最好使用独立的LLM作为意图识别,例如使用免费的ChatGLMLLM
- llm: ChatGLMLLM
-
-ASR:
- FunASR:
- type: fun_local
- model_dir: models/SenseVoiceSmall
- output_dir: tmp/
- FunASRServer:
- # 独立部署FunASR,使用FunASR的API服务,只需要五句话
- # 第一句:mkdir -p ./funasr-runtime-resources/models
- # 第二句:sudo docker run -p 10096:10095 -it --privileged=true -v $PWD/funasr-runtime-resources/models:/workspace/models registry.cn-hangzhou.aliyuncs.com/funasr_repo/funasr:funasr-runtime-sdk-online-cpu-0.1.12
- # 上一句话执行后会进入到容器,继续第三句:cd FunASR/runtime
- # 不要退出容器,继续在容器中执行第四句:nohup bash run_server_2pass.sh --download-model-dir /workspace/models --vad-dir damo/speech_fsmn_vad_zh-cn-16k-common-onnx --model-dir iic/SenseVoiceSmall-onnx --online-model-dir damo/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online-onnx --punc-dir damo/punc_ct-transformer_zh-cn-common-vad_realtime-vocab272727-onnx --lm-dir damo/speech_ngram_lm_zh-cn-ai-wesp-fst --itn-dir thuduj12/fst_itn_zh --hotword /workspace/models/hotwords.txt > log.txt 2>&1 &
- # 上一句话执行后会进入到容器,继续第五句:tail -f log.txt
- # 第五句话执行完后,会看到模型下载日志,下载完后就可以连接使用了
- # 以上是使用CPU推理,如果有GPU,详细参考:https://github.com/modelscope/FunASR/blob/main/runtime/docs/SDK_advanced_guide_online_zh.md
- type: fun_server
- host: 127.0.0.1
- port: 10096
- is_ssl: true
- api_key: none
- output_dir: tmp/
- SherpaASR:
- # Sherpa-ONNX 本地语音识别(需手动下载模型)
- type: sherpa_onnx_local
- model_dir: models/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17
- output_dir: tmp/
- # 模型类型:sense_voice (多语言) 或 paraformer (中文专用)
- model_type: sense_voice
- SherpaParaformerASR:
- # 中文语音识别模型,可以运行在低性能设备(需手动下载模型,例如RK3566-2g)
- # 详细配置说明请参考:docs/sherpa-paraformer-guide.md
- type: sherpa_onnx_local
- model_dir: models/sherpa-onnx-paraformer-zh-small-2024-03-09
- output_dir: tmp/
- model_type: paraformer
- DoubaoASR:
- # 可以在这里申请相关Key等信息
- # https://console.volcengine.com/speech/app
- # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费
- # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
- type: doubao
- appid: 你的火山引擎语音合成服务appid
- access_token: 你的火山引擎语音合成服务access_token
- cluster: volcengine_input_common
- # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
- boosting_table_name: (选填)你的热词文件名称
- correct_table_name: (选填)你的替换词文件名称
- output_dir: tmp/
- DoubaoStreamASR:
- # 可以在这里申请相关Key等信息
- # https://console.volcengine.com/speech/app
- # DoubaoASR和DoubaoStreamASR的区别是:DoubaoASR是按次收费,DoubaoStreamASR是按时收费
- # 开通地址https://console.volcengine.com/speech/service/10011
- # 一般来说按次收费的更便宜,但是DoubaoStreamASR使用了大模型技术,效果更好
- type: doubao_stream
- appid: 你的火山引擎语音合成服务appid
- access_token: 你的火山引擎语音合成服务access_token
- cluster: volcengine_input_common
- # 热词、替换词使用流程:https://www.volcengine.com/docs/6561/155738
- boosting_table_name: (选填)你的热词文件名称
- correct_table_name: (选填)你的替换词文件名称
- # 是否开启多语种识别模式
- enable_multilingual: False
- # 多语种识别当该键为空时,该模型支持中英文、上海话、闽南语,四川、陕西、粤语识别。当将其设置为特定键时,它可以识别指定语言。
- # 详细语言列表参考 https://www.volcengine.com/docs/6561/1354869
- # language: zh-cn
- # 静音判定时长(ms),默认200ms
- end_window_size: 200
- output_dir: tmp/
- TencentASR:
- # token申请地址:https://console.cloud.tencent.com/cam/capi
- # 免费领取资源:https://console.cloud.tencent.com/asr/resourcebundle
- type: tencent
- appid: 你的腾讯语音合成服务appid
- secret_id: 你的腾讯语音合成服务secret_id
- secret_key: 你的腾讯语音合成服务secret_key
- output_dir: tmp/
- AliyunASR:
- # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
- # HTTP POST请求,一次性处理完整音频
- # 平台地址:https://nls-portal.console.aliyun.com/
- # appkey地址:https://nls-portal.console.aliyun.com/applist
- # token地址:https://nls-portal.console.aliyun.com/overview
- # AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景
- # 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟)
- # 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟)
- # 定义ASR API类型
- type: aliyun
- appkey: 你的阿里云智能语音交互服务项目Appkey
- token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
- access_key_id: 你的阿里云账号access_key_id
- access_key_secret: 你的阿里云账号access_key_secret
- output_dir: tmp/
- AliyunStreamASR:
- # 阿里云智能语音交互服务 - 实时流式语音识别
- # WebSocket连接,实时处理音频流
- # 平台地址:https://nls-portal.console.aliyun.com/
- # appkey地址:https://nls-portal.console.aliyun.com/applist
- # token地址:https://nls-portal.console.aliyun.com/overview
- # AliyunASR和AliyunStreamASR的区别是:AliyunASR是批量处理场景,AliyunStreamASR是实时交互场景
- # 一般来说非流式ASR更便宜(0.004元/秒,¥0.24/分钟)
- # 但是AliyunStreamASR实时性更好(0.005元/秒,¥0.3/分钟)
- # 定义ASR API类型
- type: aliyun_stream
- appkey: 你的阿里云智能语音交互服务项目Appkey
- token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
- access_key_id: 你的阿里云账号access_key_id
- access_key_secret: 你的阿里云账号access_key_secret
- # 服务器地域选择,可选择距离更近的服务器以减少延迟,如nls-gateway-cn-hangzhou.aliyuncs.com(杭州)等
- host: nls-gateway-cn-shanghai.aliyuncs.com
- # 断句检测时间(毫秒),控制静音多长时间后进行断句,默认800毫秒
- max_sentence_silence: 800
- output_dir: tmp/
- BaiduASR:
- # 获取AppID、API Key、Secret Key:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/app/list
- # 查看资源额度:https://console.bce.baidu.com/ai-engine/old/#/ai/speech/overview/resource/list
- type: baidu
- app_id: 你的百度语音技术AppID
- api_key: 你的百度语音技术APIKey
- secret_key: 你的百度语音技术SecretKey
- # 语言参数,1537为普通话,具体参考:https://ai.baidu.com/ai-doc/SPEECH/0lbxfnc9b
- dev_pid: 1537
- output_dir: tmp/
- OpenaiASR:
- # OpenAI语音识别服务,需要先在OpenAI平台创建组织并获取api_key
- # 支持中、英、日、韩等多种语音识别,具体参考文档https://platform.openai.com/docs/guides/speech-to-text
- # 需要网络连接
- # 申请步骤:
- # 1.登录OpenAI Platform。https://auth.openai.com/log-in
- # 2.创建api-key https://platform.openai.com/settings/organization/api-keys
- # 3.模型可以选择gpt-4o-transcribe或GPT-4o mini Transcribe
- type: openai
- api_key: 你的OpenAI API密钥
- base_url: https://api.openai.com/v1/audio/transcriptions
- model_name: gpt-4o-mini-transcribe
- output_dir: tmp/
- GroqASR:
- # Groq语音识别服务,需要先在Groq Console创建API密钥
- # 申请步骤:
- # 1.登录groq Console。https://console.groq.com/home
- # 2.创建api-key https://console.groq.com/keys
- # 3.模型可以选择whisper-large-v3-turbo或whisper-large-v3(distil-whisper-large-v3-en仅支持英语转录)
- type: openai
- api_key: 你的Groq API密钥
- base_url: https://api.groq.com/openai/v1/audio/transcriptions
- model_name: whisper-large-v3-turbo
- output_dir: tmp/
- VoskASR:
- # 官方网站:https://alphacephei.com/vosk/
- # 配置说明:
- # 1. VOSK是一个离线语音识别库,支持多种语言
- # 2. 需要先下载模型文件:https://alphacephei.com/vosk/models
- # 3. 中文模型推荐使用vosk-model-small-cn-0.22或vosk-model-cn-0.22
- # 4. 完全离线运行,无需网络连接
- # 5. 输出文件保存在tmp/目录
- # 使用步骤:
- # 1. 访问 https://alphacephei.com/vosk/models 下载对应的模型
- # 2. 解压模型文件到项目目录下的models/vosk/文件夹
- # 3. 在配置中指定正确的模型路径
- # 4. 注意:VOSK中文模型输出不带标点符号,词与词之间会有空格
- type: vosk
- model_path: 你的模型路径,如:models/vosk/vosk-model-small-cn-0.22
- output_dir: tmp/
- Qwen3ASRFlash:
- # 通义千问Qwen3-ASR-Flash语音识别服务,需要先在阿里云百炼平台创建API密钥
- # 申请步骤:
- # 1.登录阿里云百炼平台。https://bailian.console.aliyun.com/
- # 2.创建API-KEY https://bailian.console.aliyun.com/#/api-key
- # 3.Qwen3-ASR-Flash基于通义千问多模态基座,支持多语言识别、歌唱识别、噪声拒识等功能
- type: qwen3_asr_flash
- api_key: 你的阿里云百炼API密钥
- base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
- model_name: qwen3-asr-flash
- output_dir: tmp/
- # ASR选项配置
- enable_lid: true # 自动语种检测
- enable_itn: true # 逆文本归一化
- #language: "zh" # 语种,支持zh、en、ja、ko等
- context: "" # 上下文信息,用于提高识别准确率,不超过10000 Token
- XunfeiStreamASR:
- # 讯飞流式语音识别服务
- # 需要先在讯飞开放平台创建应用,获取以下认证信息
- # 讯飞开放平台地址:https://www.xfyun.cn/
- # 创建应用后,在"我的应用"中获取:
- # - APPID
- # - APISecret
- # - APIKey
- type: xunfei_stream
- # 必填参数 - 讯飞开放平台应用信息
- app_id: 你的APPID
- api_key: 你的APIKey
- api_secret: 你的APISecret
- # 识别参数配置
- domain: slm # 识别领域,iat:日常用语,medical:医疗,finance:金融等
- language: zh_cn # 语言,zh_cn:中文,en_us:英文
- accent: mandarin # 方言,mandarin:普通话
- # 调整音频处理参数以提高长语音识别质量
- output_dir: tmp/
- AliyunBLStreamASR:
- # 阿里百炼Paraformer实时语音识别服务
- # WebSocket实时流式语音识别,支持多语言、热词定制、语义断句等高级功能
- # 平台地址:https://bailian.console.aliyun.com/
- # API Key地址:https://bailian.console.aliyun.com/#/api-key
- # 文档地址:https://help.aliyun.com/zh/model-studio/websocket-for-paraformer-real-time-service
- # 支持模型:paraformer-realtime-v2(推荐), paraformer-realtime-8k-v2, paraformer-realtime-v1, paraformer-realtime-8k-v1
- type: aliyunbl_stream
- # 必填参数
- api_key: 你的阿里云百炼API密钥
- # 模型选择,推荐使用v2版本
- model: paraformer-realtime-v2
- # 音频格式和采样率
- format: pcm
- sample_rate: 16000 # v2支持任意采样率,v1仅支持16000,8k版本仅支持8000
- # 可选参数
- disfluency_removal_enabled: false # 是否过滤语气词(如"嗯"、"啊"等)
- semantic_punctuation_enabled: false # 语义断句(true:会议场景,准确;false:VAD断句,交互场景,低延迟)
- max_sentence_silence: 200 # VAD断句静音时长阈值(ms),范围200-6000,仅VAD断句时生效
- multi_threshold_mode_enabled: false # 防止VAD断句切割过长,仅VAD断句时生效
- punctuation_prediction_enabled: true # 是否自动添加标点符号
- inverse_text_normalization_enabled: true # 是否开启ITN(中文数字转阿拉伯数字)
- # 热词定制文档地址:https://help.aliyun.com/zh/model-studio/custom-hot-words?
- # vocabulary_id: vocab-xxx-24ee19fa8cfb4d52902170a0xxxxxxxx # 热词ID(可选)
- # language_hints: ["zh", "en"] # 指定语言(可选),支持zh、en、ja、yue、ko、de、fr、ru
- output_dir: tmp/
-VAD:
- SileroVAD:
- type: silero
- threshold: 0.5
- threshold_low: 0.3
- model_dir: models/snakers4_silero-vad
- min_silence_duration_ms: 200 # 如果说话停顿比较长,可以把这个值设置大一些
-
-LLM:
- # 所有openai类型均可以修改超参,以AliLLM为例
- # 当前支持的type为openai、dify、ollama,可自行适配
- AliLLM:
- # 定义LLM API类型
- type: openai
- # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
- base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
- model_name: qwen-turbo
- api_key: 你的deepseek web key
- temperature: 0.7 # 温度值
- max_tokens: 500 # 最大生成token数
- top_p: 1
- frequency_penalty: 0 # 频率惩罚
- AliAppLLM:
- # 定义LLM API类型
- type: AliBL
- base_url: https://dashscope.aliyuncs.com/compatible-mode/v1
- app_id: 你的app_id
- # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
- api_key: 你的api_key
- # 是否不使用本地prompt:true|false (默不用请在百练应用中设置prompt)
- is_no_prompt: true
- # Ali_memory_id:false(不使用)|你的memory_id(请在百练应用中设置中获取)
- # Tips!:Ali_memory未实现多用户存储记忆(记忆按id调用)
- ali_memory_id: false
- DoubaoLLM:
- # 定义LLM API类型
- type: openai
- # 先开通服务,打开以下网址,开通的服务搜索Doubao-1.5-pro,开通它
- # 开通地址:https://console.volcengine.com/ark/region:ark+cn-beijing/openManagement?LLM=%7B%7D&OpenTokenDrawer=false
- # 免费额度500000token
- # 开通后,进入这里获取密钥:https://console.volcengine.com/ark/region:ark+cn-beijing/apiKey?apikey=%7B%7D
- base_url: https://ark.cn-beijing.volces.com/api/v3
- model_name: doubao-1-5-pro-32k-250115
- api_key: 你的doubao web key
- DeepSeekLLM:
- # 定义LLM API类型
- type: openai
- # 可在这里找到你的api key https://platform.deepseek.com/
- model_name: deepseek-chat
- url: https://api.deepseek.com
- api_key: 你的deepseek web key
- ChatGLMLLM:
- # 定义LLM API类型
- type: openai
- # glm-4-flash 是免费的,但是还是需要注册填写api_key的
- # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
- model_name: glm-4-flash
- url: https://open.bigmodel.cn/api/paas/v4/
- api_key: 你的chat-glm web key
- OllamaLLM:
- # 定义LLM API类型
- type: ollama
- model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载
- base_url: http://localhost:11434 # Ollama服务地址
- DifyLLM:
- # 定义LLM API类型
- type: dify
- # 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限
- # 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词
- base_url: https://api.dify.ai/v1
- api_key: 你的DifyLLM web key
- # 使用的对话模式 可以选择工作流 workflows/run 对话模式 chat-messages 文本生成 completion-messages
- # 使用workflows进行返回的时候输入参数为 query 返回参数的名字要设置为 answer
- # 文本生成的默认输入参数也是query
- mode: chat-messages
- GeminiLLM:
- type: gemini
- # 谷歌Gemini API,需要先在Google Cloud控制台创建API密钥并获取api_key
- # 若在中国境内使用,请遵守《生成式人工智能服务管理暂行办法》
- # token申请地址: https://aistudio.google.com/apikey
- # 若部署地无法访问接口,需要开启科学上网
- api_key: 你的gemini web key
- model_name: "gemini-2.0-flash"
- http_proxy: "" #"http://127.0.0.1:10808"
- https_proxy: "" #http://127.0.0.1:10808"
- CozeLLM:
- # 定义LLM API类型
- type: coze
- # 你可以在这里找到个人令牌
- # https://www.coze.cn/open/oauth/pats
- # bot_id和user_id的内容写在引号之内
- bot_id: "你的bot_id"
- user_id: "你的user_id"
- personal_access_token: 你的coze个人令牌
- VolcesAiGatewayLLM:
- # 火山引擎 - 边缘大模型网关
- # 定义LLM API类型
- type: openai
- # 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-pro-32k-functioncall ,开通
- # 如果需要使用边缘大模型网关提供的语音合成,一并勾选 Doubao-语音合成 ,另见 TTS.VolcesAiGatewayTTS 配置
- # https://console.volcengine.com/vei/aigateway/
- # 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list
- base_url: https://ai-gateway.vei.volces.com/v1
- model_name: doubao-pro-32k-functioncall
- api_key: 你的网关访问密钥
- LMStudioLLM:
- # 定义LLM API类型
- type: openai
- model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载
- url: http://localhost:1234/v1 # LM Studio服务地址
- api_key: lm-studio # LM Studio服务的固定API Key
- HomeAssistant:
- # 定义LLM API类型
- type: homeassistant
- base_url: http://homeassistant.local:8123
- agent_id: conversation.chatgpt
- api_key: 你的home assistant api访问令牌
- FastgptLLM:
- # 定义LLM API类型
- type: fastgpt
- # 如果使用fastgpt,配置文件里prompt(提示词)是无效的,需要在fastgpt控制台设置提示词
- base_url: https://host/api/v1
- # 你可以在这里找到你的api_key
- # https://cloud.tryfastgpt.ai/account/apikey
- api_key: 你的fastgpt密钥
- variables:
- k: "v"
- k2: "v2"
- XinferenceLLM:
- # 定义LLM API类型
- type: xinference
- # Xinference服务地址和模型名称
- model_name: qwen2.5:72b-AWQ # 使用的模型名称,需要预先在Xinference启动对应模型
- base_url: http://localhost:9997 # Xinference服务地址
- XinferenceSmallLLM:
- # 定义轻量级LLM API类型,用于意图识别
- type: xinference
- # Xinference服务地址和模型名称
- model_name: qwen2.5:3b-AWQ # 使用的小模型名称,用于意图识别
- base_url: http://localhost:9997 # Xinference服务地址
-# VLLM配置(视觉语言大模型)
-VLLM:
- ChatGLMVLLM:
- type: openai
- # glm-4v-flash是智谱免费AI的视觉模型,需要先在智谱AI平台创建API密钥并获取api_key
- # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys
- model_name: glm-4v-flash # 智谱AI的视觉模型
- url: https://open.bigmodel.cn/api/paas/v4/
- api_key: 你的api_key
- QwenVLVLLM:
- type: openai
- model_name: qwen2.5-vl-3b-instruct
- url: https://dashscope.aliyuncs.com/compatible-mode/v1
- # 可在这里找到你的api key https://bailian.console.aliyun.com/?apiKey=1#/api-key
- api_key: 你的api_key
- XunfeiSparkLLM:
- # 定义LLM API类型
- type: openai
- # 先新建应用,在下面的地址
- # 开通应用地址:https://console.xfyun.cn/app/myapp
- # 有免费额度,但也要开通服务,才能获取api_key
- # 每一个模型都需要单独开通,每一个模型的api_password都不同,例如Lite模型在https://console.xfyun.cn/services/cbm 开通
- base_url: https://ark.cn-beijing.volces.com/api/v3
- model_name: lite
- api_key: 你的api_password
-TTS:
- # 当前支持的type为edge、doubao,可自行适配
- EdgeTTS:
- # 定义TTS API类型
- type: edge
- voice: zh-CN-XiaoxiaoNeural
- output_dir: tmp/
- DoubaoTTS:
- # 定义TTS API类型
- type: doubao
- # 火山引擎语音合成服务,需要先在火山引擎控制台创建应用并获取appid和access_token
- # 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误
- # 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。
- # 普通音色在这里开通:https://console.volcengine.com/speech/service/8
- # 湾湾小何音色在这里开通:https://console.volcengine.com/speech/service/10007,开通后将下面的voice设置成zh_female_wanwanxiaohe_moon_bigtts
- api_url: https://openspeech.bytedance.com/api/v1/tts
- voice: BV001_streaming
- output_dir: tmp/
- authorization: "Bearer;"
- appid: 你的火山引擎语音合成服务appid
- access_token: 你的火山引擎语音合成服务access_token
- cluster: volcano_tts
- speed_ratio: 1.0
- volume_ratio: 1.0
- pitch_ratio: 1.0
- #火山tts,支持双向流式tts
- HuoshanDoubleStreamTTS:
- type: huoshan_double_stream
- # 访问 https://console.volcengine.com/speech/service/10007 开通语音合成大模型,购买音色
- # 在页面底部获取appid和access_token
- # 资源ID固定为:volc.service_type.10029(大模型语音合成及混音)
- # 如果是机智云,把接口地址换成wss://bytedance.gizwitsapi.com/api/v3/tts/bidirection
- # 机智云不需要天填 appid
- ws_url: wss://openspeech.bytedance.com/api/v3/tts/bidirection
- appid: 你的火山引擎语音合成服务appid
- access_token: 你的火山引擎语音合成服务access_token
- resource_id: volc.service_type.10029
- speaker: zh_female_wanwanxiaohe_moon_bigtts
- # 开启WebSocket连接复用,默认复用(注意:复用后设备处于聆听状态时空闲链接会占并发数)
- enable_ws_reuse: True
- speech_rate: 0
- loudness_rate: 0
- pitch: 0
- # 多情感音色参数,注意:当前仅部分音色支持设置情感。
- # 相关音色列表:https://www.volcengine.com/docs/6561/1257544
- emotion: "neutral" # 情感类型,可选值为:neutral、happy、sad、angry、fearful、disgusted、surprised
- emotion_scale: 4 # 情感强度,可选值为:1~5,默认值为4
- CosyVoiceSiliconflow:
- type: siliconflow
- # 硅基流动TTS
- # token申请地址 https://cloud.siliconflow.cn/account/ak
- model: FunAudioLLM/CosyVoice2-0.5B
- voice: FunAudioLLM/CosyVoice2-0.5B:alex
- output_dir: tmp/
- access_token: 你的硅基流动API密钥
- response_format: wav
- CozeCnTTS:
- type: cozecn
- # COZECN TTS
- # token申请地址 https://www.coze.cn/open/oauth/pats
- voice: 7426720361733046281
- output_dir: tmp/
- access_token: 你的coze web key
- response_format: wav
- VolcesAiGatewayTTS:
- type: openai
- # 火山引擎 - 边缘大模型网关
- # 先开通服务,打开以下网址,创建网关访问密钥,搜索并勾选 Doubao-语音合成 ,开通
- # 如果需要使用边缘大模型网关提供的 LLM,一并勾选 Doubao-pro-32k-functioncall ,另见 LLM.VolcesAiGatewayLLM 配置
- # https://console.volcengine.com/vei/aigateway/
- # 开通后,进入这里获取密钥:https://console.volcengine.com/vei/aigateway/tokens-list
- api_key: 你的网关访问密钥
- api_url: https://ai-gateway.vei.volces.com/v1/audio/speech
- model: doubao-tts
- # 音色列表见 https://www.volcengine.com/docs/6561/1257544
- voice: zh_male_shaonianzixin_moon_bigtts
- speed: 1
- output_dir: tmp/
- FishSpeech:
- # 参照教程:https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/docs/fish-speech-integration.md
- type: fishspeech
- output_dir: tmp/
- response_format: wav
- reference_id: null
- reference_audio: ["config/assets/wakeup_words.wav",]
- reference_text: ["哈啰啊,我是小智啦,声音好听的台湾女孩一枚,超开心认识你耶,最近在忙啥,别忘了给我来点有趣的料哦,我超爱听八卦的啦",]
- normalize: true
- max_new_tokens: 1024
- chunk_length: 200
- top_p: 0.7
- repetition_penalty: 1.2
- temperature: 0.7
- streaming: false
- use_memory_cache: "on"
- seed: null
- channels: 1
- rate: 44100
- api_key: "你的api_key"
- api_url: "http://127.0.0.1:8080/v1/tts"
- GPT_SOVITS_V2:
- # 定义TTS API类型
- #启动tts方法:
- #python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/demo.yaml
- type: gpt_sovits_v2
- url: "http://127.0.0.1:9880/tts"
- output_dir: tmp/
- text_lang: "auto"
- ref_audio_path: "demo.wav"
- prompt_text: ""
- prompt_lang: "zh"
- top_k: 5
- top_p: 1
- temperature: 1
- text_split_method: "cut0"
- batch_size: 1
- batch_threshold: 0.75
- split_bucket: true
- return_fragment: false
- speed_factor: 1.0
- streaming_mode: false
- seed: -1
- parallel_infer: true
- repetition_penalty: 1.35
- aux_ref_audio_paths: []
- GPT_SOVITS_V3:
- # 定义TTS API类型 GPT-SoVITS-v3lora-20250228
- #启动tts方法:
- #python api.py
- type: gpt_sovits_v3
- url: "http://127.0.0.1:9880"
- output_dir: tmp/
- text_language: "auto"
- refer_wav_path: "caixukun.wav"
- prompt_language: "zh"
- prompt_text: ""
- top_k: 15
- top_p: 1.0
- temperature: 1.0
- cut_punc: ""
- speed: 1.0
- inp_refs: []
- sample_steps: 32
- if_sr: false
- MinimaxTTSHTTPStream:
- # Minimax流式语音合成服务
- type: minimax_httpstream
- output_dir: tmp/
- group_id: 你的minimax平台groupID
- api_key: 你的minimax平台接口密钥
- model: "speech-01-turbo"
- voice_id: "female-shaonv"
- # 以下可不用设置,使用默认设置
- # voice_setting:
- # voice_id: "male-qn-qingse"
- # speed: 1
- # vol: 1
- # pitch: 0
- # emotion: "happy"
- # pronunciation_dict:
- # tone:
- # - "处理/(chu3)(li3)"
- # - "危险/dangerous"
- # audio_setting:
- # sample_rate: 24000
- # bitrate: 128000
- # format: "mp3"
- # channel: 1
- # timber_weights:
- # -
- # voice_id: male-qn-qingse
- # weight: 1
- # -
- # voice_id: female-shaonv
- # weight: 1
- # language_boost: auto
- AliyunTTS:
- # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息
- # 平台地址:https://nls-portal.console.aliyun.com/
- # appkey地址:https://nls-portal.console.aliyun.com/applist
- # token地址:https://nls-portal.console.aliyun.com/overview
- # 定义TTS API类型
- type: aliyun
- output_dir: tmp/
- appkey: 你的阿里云智能语音交互服务项目Appkey
- token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
- voice: xiaoyun
- access_key_id: 你的阿里云账号access_key_id
- access_key_secret: 你的阿里云账号access_key_secret
-
- # 以下可不用设置,使用默认设置
- # format: wav
- # sample_rate: 16000
- # volume: 50
- # speech_rate: 0
- # pitch_rate: 0
- AliyunStreamTTS:
- # 阿里云CosyVoice大模型流式文本语音合成
- # 采用FlowingSpeechSynthesizer接口,支持更低延迟和更自然的语音质量
- # 流式文本语音合成仅提供商用版,不支持试用,详情请参见试用版和商用版。要使用该功能,请开通商用版。
- # 支持龙系列专用音色:longxiaochun、longyu、longchen等
- # 平台地址:https://nls-portal.console.aliyun.com/
- # appkey地址:https://nls-portal.console.aliyun.com/applist
- # token地址:https://nls-portal.console.aliyun.com/overview
- # 使用三阶段流式交互:StartSynthesis -> RunSynthesis -> StopSynthesis
- type: aliyun_stream
- output_dir: tmp/
- appkey: 你的阿里云智能语音交互服务项目Appkey
- token: 你的阿里云智能语音交互服务AccessToken,临时的24小时,要长期用下方的access_key_id,access_key_secret
- voice: longxiaochun
- access_key_id: 你的阿里云账号access_key_id
- access_key_secret: 你的阿里云账号access_key_secret
- # 截至2025年7月21日大模型音色只有北京节点采用,其他节点暂不支持
- host: nls-gateway-cn-beijing.aliyuncs.com
- # 以下可不用设置,使用默认设置
- # format: pcm # 音频格式:pcm、wav、mp3
- # sample_rate: 16000 # 采样率:8000、16000、24000
- # volume: 50 # 音量:0-100
- # speech_rate: 0 # 语速:-500到500
- # pitch_rate: 0 # 语调:-500到500
- TencentTTS:
- # 腾讯云智能语音交互服务,需要先在腾讯云平台开通服务
- # appid、secret_id、secret_key申请地址:https://console.cloud.tencent.com/cam/capi
- # 免费领取资源:https://console.cloud.tencent.com/tts/resourcebundle
- type: tencent
- output_dir: tmp/
- appid: 你的腾讯云AppId
- secret_id: 你的腾讯云SecretID
- secret_key: 你的腾讯云SecretKey
- region: ap-guangzhou
- voice: 101001
-
- TTS302AI:
- # 302AI语音合成服务,需要先在302平台创建账户充值,并获取密钥信息
- # 添加 302.ai TTS 配置
- # token申请地址:https://dash.302.ai/
- # 获取api_keyn路径:https://dash.302.ai/apis/list
- # 价格,$35/百万字符。火山原版¥450元/百万字符
- type: doubao
- api_url: https://api.302ai.cn/doubao/tts_hd
- authorization: "Bearer "
- # 湾湾小何音色
- voice: "zh_female_wanwanxiaohe_moon_bigtts"
- output_dir: tmp/
- access_token: "你的302API密钥"
- GizwitsTTS:
- type: doubao
- # 火山引擎作为基座,可以完全使用企业级火山引擎语音合成服务
- # 前一万名注册的用户,将送5元体验金额
- # 获取API Key地址:https://agentrouter.gizwitsapi.com/panel/token
- api_url: https://bytedance.gizwitsapi.com/api/v1/tts
- authorization: "Bearer "
- # 湾湾小何音色
- voice: "zh_female_wanwanxiaohe_moon_bigtts"
- output_dir: tmp/
- access_token: "你的机智云API key"
- ACGNTTS:
- #在线网址:https://acgn.ttson.cn/
- #token购买:www.ttson.cn
- #开发相关疑问请提交至网站上的qq
- #角色id获取地址:ctrl+f快速检索角色——网站管理者不允许发布,可询问网站管理者
- #各参数意义见开发文档:https://www.yuque.com/alexuh/skmti9/wm6taqislegb02gd?singleDoc#
- type: ttson
- token: your_token
- voice_id: 1695
- speed_factor: 1
- pitch_factor: 0
- volume_change_dB: 0
- to_lang: ZH
- url: https://u95167-bd74-2aef8085.westx.seetacloud.com:8443/flashsummary/tts?token=
- format: mp3
- output_dir: tmp/
- emotion: 1
- OpenAITTS:
- # openai官方文本转语音服务,可支持全球大多数语种
- type: openai
- # 你可以在这里获取到 api key
- # https://platform.openai.com/api-keys
- api_key: 你的openai api key
- # 国内需要使用代理
- api_url: https://api.openai.com/v1/audio/speech
- # 可选tts-1或tts-1-hd,tts-1速度更快tts-1-hd质量更好
- model: tts-1
- # 演讲者,可选alloy, echo, fable, onyx, nova, shimmer
- voice: onyx
- # 语速范围0.25-4.0
- speed: 1
- output_dir: tmp/
- CustomTTS:
- # 自定义的TTS接口服务,请求参数可自定义,可接入众多TTS服务
- # 以本地部署的KokoroTTS为例
- # 如果只有cpu运行:docker run -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-cpu:latest
- # 如果只有gpu运行:docker run --gpus all -p 8880:8880 ghcr.io/remsky/kokoro-fastapi-gpu:latest
- # 要求接口使用POST方式请求,并返回音频文件
- type: custom
- method: POST
- url: "http://127.0.0.1:8880/v1/audio/speech"
- params: # 自定义请求参数
- input: "{prompt_text}"
- response_format: "mp3"
- download_format: "mp3"
- voice: "zf_xiaoxiao"
- lang_code: "z"
- return_download_link: true
- speed: 1
- stream: false
- headers: # 自定义请求头
- # Authorization: Bearer xxxx
- format: mp3 # 接口返回的音频格式
- output_dir: tmp/
- LinkeraiTTS:
- type: linkerai
- api_url: https://tts.linkerai.cn/tts
- audio_format: "pcm"
- # 默认的access_token供大家测试时免费使用的,此access_token请勿用于商业用途
- # 如果效果不错,可自行申请token,申请地址:https://linkerai.cn
- # 各参数意义见开发文档:https://tts.linkerai.cn/docs
- # 支持声音克隆,可自行上传音频,填入voice参数,voice参数为空时,使用默认声音
- access_token: "U4YdYXVfpwWnk2t5Gp822zWPCuORyeJL"
- voice: "OUeAo1mhq6IBExi"
- output_dir: tmp/
- PaddleSpeechTTS:
- #百度飞浆 PaddleSpeech 支持本地离线部署 支持模型训练
- #框架地址 https://www.paddlepaddle.org.cn/
- #项目地址 https://github.com/PaddlePaddle/PaddleSpeech
- #SpeechServerDemo https://github.com/PaddlePaddle/PaddleSpeech/tree/develop/demos/speech_server
- #流式传输请参考 https://github.com/PaddlePaddle/PaddleSpeech/wiki/PaddleSpeech-Server-WebSocket-API
- type: paddle_speech
- protocol: websocket # protocol choices = ['websocket', 'http']
- url: ws://127.0.0.1:8092/paddlespeech/tts/streaming # TTS 服务的 URL 地址,指向本地服务器 [websocket默认ws://127.0.0.1:8092/paddlespeech/tts/streaming,http默认http://127.0.0.1:8090/paddlespeech/tts]
- spk_id: 0 # 发音人 ID,0 通常表示默认的发音人
- sample_rate: 24000 # 采样率 [websocket默认24000,http默认0 自动选择]
- speed: 1.0 # 语速,1.0 表示正常语速,>1 表示加快,<1 表示减慢
- volume: 1.0 # 音量,1.0 表示正常音量,>1 表示增大,<1 表示减小
- save_path: # 保存路径
- IndexStreamTTS:
- # 基于Index-TTS-vLLM项目的TTS接口服务
- # 参照教程:https://github.com/Ksuriuri/index-tts-vllm/blob/master/README.md
- type: index_stream
- api_url: http://127.0.0.1:11996/tts
- audio_format: "pcm"
- # 默认音色,如需其他音色可到项目assets文件夹下注册
- voice: "jay_klee"
- output_dir: tmp/
- AliBLTTS:
- # 阿里百炼CosyVoice大模型流式文本语音合成
- # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key
- # cosyvoice-v3和部分音色需要申请开通
- type: alibl_stream
- api_key: 你的api_key
- model: "cosyvoice-v2"
- voice: "longcheng_v2"
- output_dir: tmp/
- # 以下可不用设置,使用默认设置
- # format: pcm # 音频格式:pcm、wav、mp3、opus
- # sample_rate: 24000 # 采样率:16000, 24000, 48000
- # volume: 50 # 音量:0-100
- # rate: 1 # 语速:0.5~2
- # pitch: 1 # 语调:0.5~2
- XunFeiTTS:
- # 讯飞TTS服务 官方网站:https://www.xfyun.cn/
- # 登录讯飞语音技术平台 https://console.xfyun.cn/app/myapp 创建相关应用
- # 选择需要的服务获取api相关配置 https://console.xfyun.cn/services/uts
- # 为需要使用的应用(APPID)购买相关服务 例如:超拟人合成 https://console.xfyun.cn/services/uts
- type: xunfei_stream
- api_url: wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6
- app_id: 你的app_id
- api_secret: 你的api_secret
- api_key: 你的api_key
- voice: x5_lingxiaoxuan_flow
- output_dir: tmp/
- # 以下可不用设置,使用默认设置,注意V5音色不支持口语化配置
- # oral_level: mid # 口语化等级:high, mid, low
- # spark_assist: 1 # 是否通过大模型进行口语化 开启:1, 关闭:0
- # stop_split: 0 # 关闭服务端拆句 不关闭:0,关闭:1
- # remain: 0 # 是否保留原书面语的样子 保留:1, 不保留:0
- # format: raw # 音频格式:raw(PCM), lame(MP3), speex, opus, opus-wb, opus-swb, speex-wb
- # sample_rate: 24000 # 采样率:16000, 8000, 24000
- # volume: 50 # 音量:0-100
- # speed: 50 # 语速:0-100
- # pitch: 50 # 语调:0-100
+ web_search:
+ count: 3
diff --git a/main/xiaozhi-server/config/config.yaml b/main/xiaozhi-server/config/config.yaml
new file mode 120000
index 000000000..da29aa917
--- /dev/null
+++ b/main/xiaozhi-server/config/config.yaml
@@ -0,0 +1 @@
+/Users/mcmillan/src/xiaozhi-esp32-server/main/xiaozhi-server/config.yaml
\ No newline at end of file
diff --git a/main/xiaozhi-server/config/config_loader.py b/main/xiaozhi-server/config/config_loader.py
index e0220e339..d34b73d40 100644
--- a/main/xiaozhi-server/config/config_loader.py
+++ b/main/xiaozhi-server/config/config_loader.py
@@ -5,7 +5,7 @@ from config.manage_api_client import init_service, get_server_config, get_agent_
def get_project_dir():
- """获取项目根目录"""
+ """Get 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,7 +27,7 @@ def load_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)
@@ -35,30 +35,30 @@ def load_config():
import asyncio
try:
loop = asyncio.get_running_loop()
- # 如果已经在事件循环中,使用异步版本
+ # If already in event loop, use async version
config = asyncio.run_coroutine_threadsafe(
get_config_from_api_async(custom_config), loop
).result()
except RuntimeError:
- # 如果不在事件循环中(启动时),创建新的事件循环
+ # If not in event loop (startup), create new event loop
config = asyncio.run(get_config_from_api_async(custom_config))
else:
- # 合并配置
+ # Merge config
config = merge_configs(default_config, custom_config)
- # 初始化目录
+ # Initialize directories
ensure_directories(config)
- # 缓存配置
+ # Cache config
cache_manager.set(CacheType.CONFIG, "main_config", config)
return config
async def get_config_from_api_async(config):
- """从Java API获取配置(异步版本)"""
- # 初始化API客户端
+ """Get 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")
@@ -69,7 +69,7 @@ async def get_config_from_api_async(config):
"secret": config["manager-api"].get("secret", ""),
}
auth_enabled = config_data.get("server", {}).get("auth", {}).get("enabled", False)
- # server的配置以本地为准
+ # server config takes precedence from local
if config.get("server"):
config_data["server"] = {
"ip": config["server"].get("ip", ""),
@@ -79,26 +79,26 @@ async def get_config_from_api_async(config):
"auth_key": config["server"].get("auth_key", ""),
}
config_data["server"]["auth"] = {"enabled": auth_enabled}
- # 如果服务器没有prompt_template,则从本地配置读取
+ # If server does not have 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):
- """从Java API获取私有配置"""
+ """Get private config from Java API"""
return await get_agent_models(device_id, client_id, config["selected_module"])
def ensure_directories(config):
- """确保所有配置路径存在"""
+ """Ensure all config, paths exist"""
dirs_to_create = set()
- project_dir = get_project_dir() # 获取项目根目录
- # 日志文件目录
+ 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模块输出目录
+ # ASR/TTS module output directory
for module in ["ASR", "TTS"]:
if config.get(module) is None:
continue
@@ -107,7 +107,7 @@ def ensure_directories(config):
if output_dir:
dirs_to_create.add(output_dir)
- # 根据selected_module创建模型目录
+ # Create model directories according to selected_module
selected_modules = config.get("selected_module", {})
for module_type in ["ASR", "LLM", "TTS"]:
selected_provider = selected_modules.get(module_type)
@@ -123,24 +123,24 @@ def ensure_directories(config):
full_model_dir = os.path.join(project_dir, output_dir)
dirs_to_create.add(full_model_dir)
- # 统一创建目录(保留原data目录创建)
+ # Create directories uniformly (preserve 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 custom configuration
Returns:
- 合并后的配置
+ Merged configuration
"""
if not isinstance(default_config, Mapping) or not isinstance(
custom_config, Mapping
diff --git a/main/xiaozhi-server/config/logger.py b/main/xiaozhi-server/config/logger.py
index 60ca06787..ce629dc73 100644
--- a/main/xiaozhi-server/config/logger.py
+++ b/main/xiaozhi-server/config/logger.py
@@ -10,8 +10,8 @@ _logger_initialized = False
def get_module_abbreviation(module_name, module_dict):
- """获取模块名称的缩写,如果为空则返回00
- 如果名称中包含下划线,则返回下划线后面的前两个字符
+ """Get the abbreviation of the module name, return 00 if empty
+ If the name contains an underscore, return 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):
- """构建模块字符串"""
+ """Build 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 value for logs without tag, and handle dynamic module string"""
record["extra"].setdefault("tag", record["name"])
- # 如果没有设置 selected_module,使用默认值
+ # If selected_module is not set, use default value
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 log configuration from config file, and set log output format and level"""
config = load_config()
log_config = config["log"]
global _logger_initialized
- # 第一次初始化时配置日志
+ # Configure logging 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()
- # 输出到控制台
- logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter)
+ # Output to console
+ logger.add(sys.stdout, format=log_format, level=log_level, filter=formatter, enqueue=True)
- # 输出到文件 - 统一目录,按大小轮转
- # 日志文件完整路径
+ # 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", # Max 10MB per file
+ retention="30 days", # Keep for 30 days
compression=None,
encoding="utf-8",
- enqueue=True, # 异步安全
+ enqueue=True, # Async safe
backtrace=True,
diagnose=True,
)
- _logger_initialized = True # 标记为已初始化
+ _logger_initialized = True # Mark as initialized
return logger
def create_connection_logger(selected_module_str):
- """为连接创建独立的日志器,绑定特定的模块字符串"""
+ """Create independent logger for connection, bind specific module string"""
return logger.bind(selected_module=selected_module_str)
diff --git a/main/xiaozhi-server/config/manage_api_client.py b/main/xiaozhi-server/config/manage_api_client.py
index a9d8d601e..e4a1af8f8 100644
--- a/main/xiaozhi-server/config/manage_api_client.py
+++ b/main/xiaozhi-server/config/manage_api_client.py
@@ -14,16 +14,16 @@ 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, bind code: {bind_code}")
class ManageApiClient:
_instance = None
- _async_clients = {} # 为每个事件循环存储独立的客户端
+ _async_clients = {} # Store independent clients for each event loop
_secret = None
def __new__(cls, config):
- """单例模式确保全局唯一实例,并支持传入配置参数"""
+ """Singleton pattern ensures globally unique instance, and supports passing configuration parameters"""
if cls._instance is None:
cls._instance = super().__new__(cls)
cls._init_client(config)
@@ -31,38 +31,38 @@ class ManageApiClient:
@classmethod
def _init_client(cls, config):
- """初始化配置(延迟创建客户端)"""
+ """Initialize configuration (delay creating client)"""
cls.config = config.get("manager-api")
if not cls.config:
- raise Exception("manager-api配置错误")
+ raise Exception("manager-api config 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 config error")
if "你" in cls.config.get("secret"):
- raise Exception("请先配置manager-api的secret")
+ raise Exception("Please configure manager-api secret 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) # 初始重试延迟(秒)
- # 不在这里创建 AsyncClient,延迟到实际使用时创建
+ cls.max_retries = cls.config.get("max_retries", 6) # Max retries
+ cls.retry_delay = cls.config.get("retry_delay", 10) # Initial retry delay (seconds)
+ # Do not create AsyncClient here, delay until actual use
cls._async_clients = {}
@classmethod
async def _ensure_async_client(cls):
- """确保异步客户端已创建(为每个事件循环创建独立的客户端)"""
+ """Ensure async client is created (create independent client for each event loop)"""
import asyncio
try:
loop = asyncio.get_running_loop()
loop_id = id(loop)
- # 为每个事件循环创建独立的客户端
+ # Create independent client for each event loop
if loop_id not in cls._async_clients:
- # 服务端可能主动关闭连接,httpx 连接池无法正确检测和清理
+ # Server may actively close connection, httpx connection pool cannot detect and clean up correctly
limits = httpx.Limits(
- max_keepalive_connections=0, # 禁用 keep-alive,每次都新建连接
+ max_keepalive_connections=0, # Disable keep-alive, create new connection every time
)
cls._async_clients[loop_id] = httpx.AsyncClient(
base_url=cls.config.get("url"),
@@ -72,17 +72,17 @@ class ManageApiClient:
"Authorization": "Bearer " + cls._secret,
},
timeout=cls.config.get("timeout", 30),
- limits=limits, # 使用限制
+ limits=limits, # Use limits
)
return cls._async_clients[loop_id]
except RuntimeError:
- # 如果没有运行中的事件循环,创建一个临时的
- raise Exception("必须在异步上下文中调用")
+ # If there is no running event loop, create a temporary one
+ raise Exception("Must be called in async context")
@classmethod
async def _async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
- """发送单次异步HTTP请求并处理响应"""
- # 确保客户端已创建
+ """Send single async HTTP request and handle response"""
+ # Ensure client is created
client = await cls._ensure_async_client()
endpoint = endpoint.lstrip("/")
response = None
@@ -92,31 +92,31 @@ class ManageApiClient:
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 returned error: {result.get('msg', 'Unknown error')}")
- # 返回成功数据
+ # Return success data
return result.get("data") if result.get("code") == 0 else None
finally:
- # 确保响应被关闭(即使异常也会执行)
+ # Ensure response is closed (executed even if exception occurs)
if response is not None:
await response.aclose()
@classmethod
def _should_retry(cls, exception: Exception) -> bool:
- """判断异常是否应该重试"""
- # 网络连接相关错误
+ """Determine if exception should be retried"""
+ # Network connection related errors
if isinstance(
exception, (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError)
):
return True
- # HTTP状态码错误
+ # HTTP status code errors
if isinstance(exception, httpx.HTTPStatusError):
status_code = exception.response.status_code
return status_code in [408, 429, 500, 502, 503, 504]
@@ -125,31 +125,31 @@ class ManageApiClient:
@classmethod
async def _execute_async_request(cls, method: str, endpoint: str, **kwargs) -> Dict:
- """带重试机制的异步请求执行器"""
+ """Async request executor with retry mechanism"""
import asyncio
retry_count = 0
while retry_count <= cls.max_retries:
try:
- # 执行异步请求
+ # Execute async request
return await cls._async_request(method, endpoint, **kwargs)
except Exception as e:
- # 判断是否应该重试
+ # Determine if retry is needed
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} async request failed, will retry for the {retry_count} time in {cls.retry_delay:.1f} seconds"
)
await asyncio.sleep(cls.retry_delay)
continue
else:
- # 不重试,直接抛出异常
+ # Do not retry, raise exception directly
raise
@classmethod
def safe_close(cls):
- """安全关闭所有异步连接池"""
+ """Safely close all async connection pools"""
import asyncio
for client in list(cls._async_clients.values()):
@@ -162,7 +162,7 @@ class ManageApiClient:
async def get_server_config() -> Optional[Dict]:
- """获取服务器基础配置"""
+ """Get server base configuration"""
return await ManageApiClient._instance._execute_async_request(
"POST", "/config/server-base"
)
@@ -171,7 +171,7 @@ async def get_server_config() -> Optional[Dict]:
async def get_agent_models(
mac_address: str, client_id: str, selected_module: Dict
) -> Optional[Dict]:
- """获取代理模型配置"""
+ """Get agent model configuration"""
return await ManageApiClient._instance._execute_async_request(
"POST",
"/config/agent-models",
@@ -184,21 +184,21 @@ async def get_agent_models(
async def generate_and_save_chat_summary(session_id: str) -> Optional[Dict]:
- """生成并保存聊天记录总结"""
+ """Generate and save chat summary"""
try:
return await ManageApiClient._instance._execute_async_request(
"POST",
f"/agent/chat-summary/{session_id}/save",
)
except Exception as e:
- print(f"生成并保存聊天记录总结失败: {e}")
+ print(f"Failed to generate and save chat summary: {e}")
return None
async def report(
mac_address: str, session_id: str, chat_type: int, content: str, audio, report_time
) -> Optional[Dict]:
- """异步聊天记录上报"""
+ """Async chat history report"""
if not content or not ManageApiClient._instance:
return None
try:
@@ -217,7 +217,7 @@ async def report(
},
)
except Exception as e:
- print(f"TTS上报失败: {e}")
+ print(f"TTS report failed: {e}")
return None
diff --git a/main/xiaozhi-server/config/settings.py b/main/xiaozhi-server/config/settings.py
index fb8868b40..1302e82c1 100644
--- a/main/xiaozhi-server/config/settings.py
+++ b/main/xiaozhi-server/config/settings.py
@@ -11,23 +11,23 @@ def check_config_file():
if config_file_valid:
return
"""
- 简化的配置检查,仅提示用户配置文件的使用情况
+ Simplified configuration check, only prompts the user for configuration file usage
"""
custom_config_file = get_project_dir() + "data/." + default_config_file
if not os.path.exists(custom_config_file):
raise FileNotFoundError(
- "找不到data/.config.yaml文件,请按教程确认该配置文件是否存在"
+ "File data/.config.yaml not found, please check the tutorial to confirm if the configuration file exists"
)
- # 检查是否从API读取配置
+ # Check if reading config from API
config = load_config()
if config.get("read_config_from_api", False):
- print("从API读取配置")
+ print("Reading config 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 console configuration and local configuration:\n"
+ error_msg += "\nSuggestion:\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
diff --git a/main/xiaozhi-server/config_from_api.yaml b/main/xiaozhi-server/config_from_api.yaml
index 1f40d6c7c..ae5f38dc8 100644
--- a/main/xiaozhi-server/config_from_api.yaml
+++ b/main/xiaozhi-server/config_from_api.yaml
@@ -1,27 +1,27 @@
-# 如果你只想轻量化安装xiaozhi-server,只使用本地的配置文件,不需要理会这个文件,不需要改动本文件任何东西
-# 如果你想从manager-api获取配置,请往下看:
-# 请将本文件复制到xiaozhi-server/data目录下,没有data目录,请创建一个,并将复制过去的文件命名为.config.yaml
-# 注意如果data目录有.config.yaml文件,请先删除它
-# 先启动manager-api和manager-web,注册一个账号,第一个注册的账号为管理员
-# 使用管理员,进入【参数管理】页面,找到【server.secret】,复制它到参数值,注意每次从零部署,server.secret都会变化
-# 打开本data目录下的.config.yaml文件,修改manager-api.secret为刚才复制出来的server.secret
+# If you only want a lightweight installation of xiaozhi-server using local config file, ignore this file and do not modify it.
+# If you want to get config from manager-api, read below:
+# Copy this file to xiaozhi-server/data directory. If data directory does not exist, create it. Name the copied file .config.yaml
+# Note: If .config.yaml already exists in data directory, please delete it first
+# First start manager-api and manager-web, register an account. The first registered account is admin
+# Login as admin, go to [Parameter Management] page, find [server.secret], copy it to parameter value. Note that server.secret changes every time you deploy from scratch
+# Open .config.yaml in data directory, modify manager-api.secret to the server.secret you just copied
server:
ip: 0.0.0.0
port: 8000
- # http服务的端口,用于视觉分析接口
+ # HTTP service port, used for vision analysis interface
http_port: 8003
- # 视觉分析接口地址
- # 向设备发送的视觉分析的接口地址
- # 如果按下面默认的写法,系统会自动生成视觉识别地址,并输出在启动日志里,这个地址你可以直接用浏览器访问确认一下
- # 当你使用docker部署或使用公网部署(使用ssl、域名)时,不一定准确
- # 所以如果你使用docker部署时,将vision_explain设置成局域网地址
- # 如果你使用公网部署时,将vision_explain设置成公网地址
- vision_explain: http://你的ip或者域名:端口号/mcp/vision/explain
+ # Vision analysis interface address
+ # Vision analysis interface address sent to device
+ # If you use the default setting below, the system will automatically generate the vision recognition address and output it in the startup log. You can verify this address by accessing it in a browser directly
+ # When deploying with docker or public network (using ssl, domain), it might not be accurate
+ # So if deploying with docker, set vision_explain to LAN address
+ # If deploying with public network, set vision_explain to public address
+ vision_explain: http://YOUR_IP_OR_DOMAIN:PORT/mcp/vision/explain
manager-api:
- # 你的manager-api的地址,最好使用局域网ip
- # 如果使用docker部署,请使用填写成 http://xiaozhi-esp32-server-web:8002/xiaozhi
+ # Your manager-api address, preferably use LAN IP
+ # If deploying with docker, please fill in http://xiaozhi-esp32-server-web:8002/xiaozhi
url: http://127.0.0.1:8002/xiaozhi
- # 你的manager-api的token,就是刚才复制出来的server.secret
- secret: 你的server.secret值
-# 默认系统提示词模板文件
-prompt_template: agent-base-prompt.txt
\ No newline at end of file
+ # Your manager-api token, which is the server.secret you copied earlier
+ secret: YOUR_SERVER_SECRET_VALUE
+# Default system prompt template file
+prompt_template: data/agent-base-prompt.txt
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/api/base_handler.py b/main/xiaozhi-server/core/api/base_handler.py
index db2775439..8af3de868 100644
--- a/main/xiaozhi-server/core/api/base_handler.py
+++ b/main/xiaozhi-server/core/api/base_handler.py
@@ -8,7 +8,7 @@ class BaseHandler:
self.logger = setup_logging()
def _add_cors_headers(self, response):
- """添加CORS头信息"""
+ """Add CORS headers"""
response.headers["Access-Control-Allow-Headers"] = (
"client-id, content-type, device-id, authorization"
)
@@ -16,9 +16,9 @@ class BaseHandler:
response.headers["Access-Control-Allow-Origin"] = "*"
async def handle_options(self, request):
- """处理OPTIONS请求,添加CORS头信息"""
+ """Handle OPTIONS request, add CORS headers"""
response = web.Response(body=b"", content_type="text/plain")
self._add_cors_headers(response)
- # 添加允许的方法
+ # Add allowed methods
response.headers["Access-Control-Allow-Methods"] = "GET, POST, OPTIONS"
return response
diff --git a/main/xiaozhi-server/core/api/ota_handler.py b/main/xiaozhi-server/core/api/ota_handler.py
index 1e3b3bd0d..4c416eaf3 100644
--- a/main/xiaozhi-server/core/api/ota_handler.py
+++ b/main/xiaozhi-server/core/api/ota_handler.py
@@ -48,7 +48,7 @@ class OTAHandler(BaseHandler):
super().__init__(config)
auth_config = config["server"].get("auth", {})
self.auth_enable = auth_config.get("enabled", False)
- # 设备白名单
+ # Device whitelist
self.allowed_devices = set(auth_config.get("allowed_devices", []))
secret_key = config["server"]["auth_key"]
expire_seconds = auth_config.get("expire_seconds")
@@ -99,18 +99,18 @@ class OTAHandler(BaseHandler):
f"Firmware cache refreshed: {len(files_by_model)} models"
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"刷新固件缓存失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to refresh firmware cache: {e}")
# keep previous cache if any
def generate_password_signature(self, content: str, secret_key: str) -> str:
- """生成MQTT密码签名
+ """Generate MQTT password signature
Args:
- content: 签名内容 (clientId + '|' + username)
- secret_key: 密钥
+ content: Signature content (clientId + '|' + username)
+ secret_key: Secret key
Returns:
- str: Base64编码的HMAC-SHA256签名
+ str: Base64 encoded HMAC-SHA256 signature
"""
try:
hmac_obj = hmac.new(
@@ -123,25 +123,25 @@ class OTAHandler(BaseHandler):
return ""
def _get_websocket_url(self, local_ip: str, port: int) -> str:
- """获取websocket地址
+ """Get websocket address
Args:
- local_ip: 本地IP地址
- port: 端口号
+ local_ip: Local IP address
+ port: Port number
Returns:
- str: websocket地址
+ str: websocket address
"""
server_config = self.config["server"]
websocket_config = server_config.get("websocket", "")
- if "你的" not in websocket_config:
+ if "YOUR_" not in websocket_config and "你的" not in websocket_config:
return websocket_config
else:
return f"ws://{local_ip}:{port}/xiaozhi/v1/"
async def handle_post(self, request):
- """处理 OTA POST 请求
+ """Handle OTA POST request
This handler will:
- read device id/client id (as before)
@@ -151,21 +151,28 @@ class OTAHandler(BaseHandler):
"""
try:
data = await request.text()
- self.logger.bind(tag=TAG).debug(f"OTA请求方法: {request.method}")
- self.logger.bind(tag=TAG).debug(f"OTA请求头: {request.headers}")
- self.logger.bind(tag=TAG).debug(f"OTA请求数据: {data}")
+ self.logger.bind(tag=TAG).debug(f"OTA request method: {request.method}")
+ self.logger.bind(tag=TAG).debug(f"OTA request headers: {request.headers}")
+ self.logger.bind(tag=TAG).debug(f"OTA request data: {data}")
device_id = request.headers.get("device-id", "")
if device_id:
- self.logger.bind(tag=TAG).info(f"OTA请求设备ID: {device_id}")
+ self.logger.bind(tag=TAG).info(f"OTA request DeviceID: {device_id}")
else:
- raise Exception("OTA请求设备ID为空")
+ raise Exception("OTA request DeviceID is empty")
client_id = request.headers.get("client-id", "")
if client_id:
- self.logger.bind(tag=TAG).info(f"OTA请求ClientID: {client_id}")
+ self.logger.bind(tag=TAG).info(f"OTA request ClientID: {client_id}")
else:
- raise Exception("OTA请求ClientID为空")
+ raise Exception("OTA request ClientID is empty")
+
+ if device_id == "b0:a6:04:5b:d7:98":
+ old_client_id = client_id
+ client_id = "26ea0ba9-2d55-4368-a56d-19c4a27c0772"
+ self.logger.bind(tag=TAG).info(
+ f"[FORCE MAP OTA] device {device_id}: {old_client_id} -> {client_id}"
+ )
data_json = {}
try:
@@ -234,18 +241,18 @@ class OTAHandler(BaseHandler):
# existing mqtt/websocket logic (unchanged)
mqtt_gateway_endpoint = server_config.get("mqtt_gateway")
- if mqtt_gateway_endpoint: # 如果配置了非空字符串
- # 尝试从请求数据中获取设备型号(已解析 above)
+ if mqtt_gateway_endpoint: # If non-empty string is configured
+ # Try to get device model from request data (parsed above)
try:
group_id = f"GID_{device_model}".replace(":", "_").replace(" ", "_")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"获取设备型号失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to get device model: {e}")
group_id = "GID_default"
mac_address_safe = device_id.replace(":", "_")
mqtt_client_id = f"{group_id}@@@{mac_address_safe}@@@{mac_address_safe}"
- # 构建用户数据
+ # Build user data
user_data = {"ip": "unknown"}
try:
user_data_json = json.dumps(user_data)
@@ -253,10 +260,10 @@ class OTAHandler(BaseHandler):
"utf-8"
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"生成用户名失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to generate username: {e}")
username = ""
- # 生成密码
+ # Generate password
password = ""
signature_key = server_config.get("mqtt_signature_key", "")
if signature_key:
@@ -264,11 +271,11 @@ class OTAHandler(BaseHandler):
mqtt_client_id + "|" + username, signature_key
)
if not password:
- password = "" # 签名失败则留空,由设备决定是否允许无密码
+ password = "" # Leave empty if signature fails, let device decide whether to allow no password
else:
- self.logger.bind(tag=TAG).warning("缺少MQTT签名密钥,密码留空")
+ self.logger.bind(tag=TAG).warning("Missing MQTT signature key, password left empty")
- # 构建MQTT配置(直接使用 mqtt_gateway 字符串)
+ # Build MQTT config (use mqtt_gateway string directly)
return_json["mqtt"] = {
"endpoint": mqtt_gateway_endpoint,
"client_id": mqtt_client_id,
@@ -277,10 +284,10 @@ class OTAHandler(BaseHandler):
"publish_topic": "device-server",
"subscribe_topic": f"devices/p2p/{mac_address_safe}",
}
- self.logger.bind(tag=TAG).info(f"为设备 {device_id} 下发MQTT网关配置")
+ self.logger.bind(tag=TAG).info(f"Sending MQTT gateway config for device {device_id}")
- else: # 未配置 mqtt_gateway,下发 WebSocket
- # 如果开启了认证,则进行认证校验
+ else: # No mqtt_gateway configured, send WebSocket
+ # If auth is enabled, perform auth verification
token = ""
if self.auth_enable:
if self.allowed_devices:
@@ -294,7 +301,7 @@ class OTAHandler(BaseHandler):
"token": token,
}
self.logger.bind(tag=TAG).info(
- f"未配置MQTT网关,为设备 {device_id} 下发WebSocket配置"
+ f"No MQTT gateway configured, sending WebSocket config for device {device_id}"
)
# Now check firmware files for updates
@@ -304,7 +311,7 @@ class OTAHandler(BaseHandler):
candidates = files_by_model.get(device_model, [])
self.logger.bind(tag=TAG).info(
- f"查找型号 {device_model} 的固件,找到 {len(candidates)} 个候选"
+ f"Searching firmware for model {device_model}, found {len(candidates)} candidates"
)
chosen_url = ""
@@ -327,22 +334,22 @@ class OTAHandler(BaseHandler):
return_json["firmware"]["version"] = chosen_version
return_json["firmware"]["url"] = chosen_url
self.logger.bind(tag=TAG).info(
- f"为设备 {device_id} 下发固件 {chosen_version} [如果地址前缀有误,请检查配置文件中的server.vision_explain]-> {chosen_url} "
+ f"Sending firmware {chosen_version} for device {device_id} [Check server.vision_explain if prefix error]-> {chosen_url} "
)
else:
self.logger.bind(tag=TAG).info(
- f"设备 {device_id} 固件已是最新: {device_version}"
+ f"Device {device_id} firmware is up to date: {device_version}"
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"检查固件版本时出错: {e}")
+ self.logger.bind(tag=TAG).error(f"Error checking firmware version: {e}")
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"OTA POST处理异常: {e}")
+ self.logger.bind(tag=TAG).error(f"OTA POST handling error: {e}")
return_json = {"success": False, "message": "request error."}
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
@@ -353,28 +360,28 @@ class OTAHandler(BaseHandler):
return response
async def handle_get(self, request):
- """处理 OTA GET 请求"""
+ """Handle OTA GET request"""
try:
server_config = self.config["server"]
local_ip = get_local_ip()
# use websocket port for websocket URL
websocket_port = int(server_config.get("port", 8000))
websocket_url = self._get_websocket_url(local_ip, websocket_port)
- message = f"OTA接口运行正常,向设备发送的websocket地址是:{websocket_url}"
+ message = f"OTA interface running normally, websocket address sent to device is: {websocket_url}"
response = web.Response(text=message, content_type="text/plain")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"OTA GET请求异常: {e}")
- response = web.Response(text="OTA接口异常", content_type="text/plain")
+ self.logger.bind(tag=TAG).error(f"OTA GET request exception: {e}")
+ response = web.Response(text="OTA interface exception", content_type="text/plain")
finally:
self._add_cors_headers(response)
return response
async def handle_download(self, request):
"""
- 下载固件接口
+ Firmware download interface
URL: /xiaozhi/ota/download/{filename}
- - 只允许下载 data/bin 目录下的 .bin 文件
- - filename 必须是 basename 且匹配安全的模式
+ - Only allow downloading .bin files in data/bin directory
+ - filename must be basename and match safe pattern
"""
try:
fname = request.match_info.get("filename", "")
@@ -405,7 +412,7 @@ class OTAHandler(BaseHandler):
except web.HTTPError as e:
resp = e
except Exception as e:
- self.logger.bind(tag=TAG).error(f"固件下载异常: {e}")
+ self.logger.bind(tag=TAG).error(f"Firmware download exception: {e}")
resp = web.Response(text="download error", status=500)
finally:
try:
diff --git a/main/xiaozhi-server/core/api/vision_handler.py b/main/xiaozhi-server/core/api/vision_handler.py
index 28f487533..c1bfc28e2 100644
--- a/main/xiaozhi-server/core/api/vision_handler.py
+++ b/main/xiaozhi-server/core/api/vision_handler.py
@@ -13,86 +13,86 @@ from plugins_func.register import Action
TAG = __name__
-# 设置最大文件大小为5MB
+# Set max file size to 5MB
MAX_FILE_SIZE = 5 * 1024 * 1024
class VisionHandler(BaseHandler):
def __init__(self, config: dict):
super().__init__(config)
- # 初始化认证工具
+ # Initialize auth tool
self.auth = AuthToken(config["server"]["auth_key"])
def _create_error_response(self, message: str) -> dict:
- """创建统一的错误响应格式"""
+ """Create unified error response format"""
return {"success": False, "message": message}
def _verify_auth_token(self, request) -> Tuple[bool, Optional[str]]:
- """验证认证token"""
+ """Verify auth token"""
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return False, None
- token = auth_header[7:] # 移除"Bearer "前缀
+ token = auth_header[7:] # Remove "Bearer " prefix
return self.auth.verify_token(token)
async def handle_post(self, request):
- """处理 MCP Vision POST 请求"""
- response = None # 初始化response变量
+ """Handle MCP Vision POST request"""
+ response = None # Initialize response variable
try:
- # 验证token
+ # Verify token
is_valid, token_device_id = self._verify_auth_token(request)
if not is_valid:
response = web.Response(
text=json.dumps(
- self._create_error_response("无效的认证token或token已过期")
+ self._create_error_response("Invalid auth token or token expired")
),
content_type="application/json",
status=401,
)
return response
- # 获取请求头信息
+ # Get request headers
device_id = request.headers.get("Device-Id", "")
client_id = request.headers.get("Client-Id", "")
if device_id != token_device_id:
- raise ValueError("设备ID与token不匹配")
- # 解析multipart/form-data请求
+ raise ValueError("Device ID does not match token")
+ # Parse multipart/form-data request
reader = await request.multipart()
- # 读取question字段
+ # Read question field
question_field = await reader.next()
if question_field is None:
- raise ValueError("缺少问题字段")
+ raise ValueError("Missing question field")
question = await question_field.text()
self.logger.bind(tag=TAG).debug(f"Question: {question}")
- # 读取图片文件
+ # Read image file
image_field = await reader.next()
if image_field is None:
- raise ValueError("缺少图片文件")
+ raise ValueError("Missing image file")
- # 读取图片数据
+ # Read image data
image_data = await image_field.read()
if not image_data:
- raise ValueError("图片数据为空")
+ raise ValueError("Image data is empty")
- # 检查文件大小
+ # Check file size
if len(image_data) > MAX_FILE_SIZE:
raise ValueError(
- f"图片大小超过限制,最大允许{MAX_FILE_SIZE/1024/1024}MB"
+ f"Image size exceeds limit, max allowed {MAX_FILE_SIZE/1024/1024}MB"
)
- # 检查文件格式
+ # Check file format
if not is_valid_image_file(image_data):
raise ValueError(
- "不支持的文件格式,请上传有效的图片文件(支持JPEG、PNG、GIF、BMP、TIFF、WEBP格式)"
+ "Unsupported file format, please upload a valid image file (supports JPEG, PNG, GIF, BMP, TIFF, WEBP)"
)
- # 将图片转换为base64编码
+ # Convert image to base64 encoding
image_base64 = base64.b64encode(image_data).decode("utf-8")
- # 如果开启了智控台,则从智控台获取模型配置
+ # If control panel is enabled, get model config from it
current_config = copy.deepcopy(self.config)
read_config_from_api = current_config.get("read_config_from_api", False)
if read_config_from_api:
@@ -104,7 +104,7 @@ class VisionHandler(BaseHandler):
select_vllm_module = current_config["selected_module"].get("VLLM")
if not select_vllm_module:
- raise ValueError("您还未设置默认的视觉分析模块")
+ raise ValueError("You have not set the default vision analysis module")
vllm_type = (
select_vllm_module
@@ -113,7 +113,7 @@ class VisionHandler(BaseHandler):
)
if not vllm_type:
- raise ValueError(f"无法找到VLLM模块对应的供应器{vllm_type}")
+ raise ValueError(f"Cannot find provider {vllm_type} for VLLM module")
vllm = create_instance(
vllm_type, current_config["VLLM"][select_vllm_module]
@@ -132,15 +132,15 @@ class VisionHandler(BaseHandler):
content_type="application/json",
)
except ValueError as e:
- self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
+ self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}")
return_json = self._create_error_response(str(e))
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"MCP Vision POST请求异常: {e}")
- return_json = self._create_error_response("处理请求时发生错误")
+ self.logger.bind(tag=TAG).error(f"MCP Vision POST request exception: {e}")
+ return_json = self._create_error_response("Error occurred while processing request")
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
@@ -151,20 +151,20 @@ class VisionHandler(BaseHandler):
return response
async def handle_get(self, request):
- """处理 MCP Vision GET 请求"""
+ """Handle MCP Vision GET request"""
try:
vision_explain = get_vision_url(self.config)
if vision_explain and len(vision_explain) > 0 and "null" != vision_explain:
message = (
- f"MCP Vision 接口运行正常,视觉解释接口地址是:{vision_explain}"
+ f"MCP Vision interface running normally, vision explain interface address is: {vision_explain}"
)
else:
- message = "MCP Vision 接口运行不正常,请打开data目录下的.config.yaml文件,找到【server.vision_explain】,设置好地址"
+ message = "MCP Vision interface not running normally, please open .config.yaml in data directory, find [server.vision_explain] and set the address"
response = web.Response(text=message, content_type="text/plain")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"MCP Vision GET请求异常: {e}")
- return_json = self._create_error_response("服务器内部错误")
+ self.logger.bind(tag=TAG).error(f"MCP Vision GET request exception: {e}")
+ return_json = self._create_error_response("Internal server error")
response = web.Response(
text=json.dumps(return_json, separators=(",", ":")),
content_type="application/json",
diff --git a/main/xiaozhi-server/core/auth.py b/main/xiaozhi-server/core/auth.py
index be95da21e..f21e9be9a 100755
--- a/main/xiaozhi-server/core/auth.py
+++ b/main/xiaozhi-server/core/auth.py
@@ -5,18 +5,18 @@ import time
class AuthenticationError(Exception):
- """认证异常"""
+ """Authentication Exception"""
pass
class AuthManager:
"""
- 统一授权认证管理器
- 生成与验证 client_id device_id token(HMAC-SHA256)认证三元组
- token 中不含明文 client_id/device_id,只携带签名 + 时间戳; client_id/device_id在连接时传递
- 在 MQTT 中 client_id: client_id, username: device_id, password: token
- 在 Websocket 中,header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......}
+ Unified authorization authentication manager
+ Generate and verify client_id device_id token (HMAC-SHA256) authentication triplet
+ Token does not contain plaintext client_id/device_id, only carries signature + timestamp; client_id/device_id is passed during connection
+ In MQTT: client_id: client_id, username: device_id, password: token
+ In Websocket: header:{Device-ID: device_id, Client-ID: client_id, Authorization: Bearer token, ......}
"""
def __init__(self, secret_key: str, expire_seconds: int = 60 * 60 * 24 * 30):
@@ -27,7 +27,7 @@ class AuthManager:
self.secret_key = secret_key
def _sign(self, content: str) -> str:
- """HMAC-SHA256签名并Base64编码"""
+ """HMAC-SHA256 signature and Base64 encoding"""
sig = hmac.new(
self.secret_key.encode("utf-8"), content.encode("utf-8"), hashlib.sha256
).digest()
@@ -35,33 +35,33 @@ class AuthManager:
def generate_token(self, client_id: str, username: str) -> str:
"""
- 生成 token
+ Generate token
Args:
- client_id: 设备连接ID
- username: 设备用户名(通常为deviceId)
+ client_id: Device connection ID
+ username: Device username (usually deviceId)
Returns:
- str: token字符串
+ str: token string
"""
ts = int(time.time())
content = f"{client_id}|{username}|{ts}"
signature = self._sign(content)
- # token仅包含签名与时间戳,不包含明文信息
+ # token only contains signature and timestamp, no plaintext info
token = f"{signature}.{ts}"
return token
def verify_token(self, token: str, client_id: str, username: str) -> bool:
"""
- 验证token有效性
+ Verify token validity
Args:
- token: 客户端传入的token
- client_id: 连接使用的client_id
- username: 连接使用的username
+ token: token passed by client
+ client_id: client_id used for connection
+ username: username used for connection
"""
try:
sig_part, ts_str = token.split(".")
ts = int(ts_str)
if int(time.time()) - ts > self.expire_seconds:
- return False # 过期
+ return False # Expired
expected_sig = self._sign(f"{client_id}|{username}|{ts}")
if not hmac.compare_digest(sig_part, expected_sig):
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 449fbd2db..b0a2f1186 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -10,6 +10,10 @@ import threading
import traceback
import subprocess
import websockets
+from core.utils.exit_handler import is_exit_command, handle_exit
+
+import re
+from datetime import datetime
from core.utils.util import (
extract_json_from_string,
@@ -17,7 +21,7 @@ from core.utils.util import (
check_asr_update,
filter_sensitive_info,
)
-from typing import Dict, Any
+from typing import Dict, Any, Optional
from collections import deque
from core.utils.modules_initialize import (
initialize_modules,
@@ -41,6 +45,10 @@ from config.manage_api_client import DeviceNotFoundException, DeviceBindExceptio
from core.utils.prompt_manager import PromptManager
from core.utils.voiceprint_provider import VoiceprintProvider
from core.utils import textUtils
+from core.utils.news_rag import news_rag
+from core.utils.history_rag import history_rag
+from core.providers.tools.device_mcp import send_mcp_message
+from plugins_func.functions.get_weather import get_weather
TAG = __name__
@@ -57,6 +65,7 @@ class ConnectionHandler:
config: Dict[str, Any],
_vad,
_asr,
+ _tts,
_llm,
_memory,
_intent,
@@ -66,13 +75,13 @@ class ConnectionHandler:
self.config = copy.deepcopy(config)
self.session_id = str(uuid.uuid4())
self.logger = setup_logging()
- self.server = server # 保存server实例的引用
+ self.server = server # Save server instance reference
- self.need_bind = False # 是否需要绑定设备
+ self.need_bind = False # Whether device binding is needed
self.bind_completed_event = asyncio.Event()
- self.bind_code = None # 绑定设备的验证码
- self.last_bind_prompt_time = 0 # 上次播放绑定提示的时间戳(秒)
- self.bind_prompt_interval = 60 # 绑定提示播放间隔(秒)
+ self.bind_code = None # Verification code for device binding
+ self.last_bind_prompt_time = 0 # Timestamp of last binding prompt (seconds)
+ self.bind_prompt_interval = 60 # Binding prompt interval (seconds)
self.read_config_from_api = self.config.get("read_config_from_api", False)
@@ -81,98 +90,104 @@ class ConnectionHandler:
self.device_id = None
self.client_ip = None
self.prompt = None
+ self.pipeline_prompts = {}
self.welcome_msg = None
self.max_output_size = 0
self.chat_history_conf = 0
self.audio_format = "opus"
- # 客户端状态相关
+ # Client status related
self.client_abort = False
self.client_is_speaking = False
+ self.mcp_battery = None
+ self.mcp_charging = None
+ self.mcp_volume = None
+ self.mcp_brightness = None
self.client_listen_mode = "auto"
- # 线程任务相关
- self.loop = None # 在 handle_connection 中获取运行中的事件循环
+ # Thread task related
+ self.loop = None # Get running event loop in handle_connection
self.stop_event = threading.Event()
self.executor = ThreadPoolExecutor(max_workers=5)
- # 添加上报线程池
+ # Add report thread pool
self.report_queue = queue.Queue()
self.report_thread = None
- # 未来可以通过修改此处,调节asr的上报和tts的上报,目前默认都开启
+ # In the future, this can be modified to adjust asr report and tts report, currently both are enabled by default
self.report_asr_enable = self.read_config_from_api
self.report_tts_enable = self.read_config_from_api
- # 依赖的组件
+ # Dependent components
self.vad = None
self.asr = None
self.tts = None
self._asr = _asr
+ self._tts = _tts
self._vad = _vad
self.llm = _llm
self.memory = _memory
self.intent = _intent
- # 为每个连接单独管理声纹识别
+ # Manage voiceprint recognition separately for each connection
self.voiceprint_provider = None
- # vad相关变量
+ # VAD related variables
self.client_audio_buffer = bytearray()
self.client_have_voice = False
self.client_voice_window = deque(maxlen=5)
- self.first_activity_time = 0.0 # 记录首次活动的时间(毫秒)
- self.last_activity_time = 0.0 # 统一的活动时间戳(毫秒)
+ self.first_activity_time = 0.0 # Record first activity time (ms)
+ self.last_activity_time = 0.0 # Unified activity timestamp (ms)
self.client_voice_stop = False
self.last_is_voice = False
- # asr相关变量
- # 因为实际部署时可能会用到公共的本地ASR,不能把变量暴露给公共ASR
- # 所以涉及到ASR的变量,需要在这里定义,属于connection的私有变量
+ # ASR related variables
+ # Since public local ASR might be used during deployment, variables cannot be exposed to public ASR
+ # So variables related to ASR need to be defined here, belonging to connection's private variables
self.asr_audio = []
self.asr_audio_queue = queue.Queue()
- self.current_speaker = None # 存储当前说话人
- self.current_language_tag = None # 存储当前ASR识别的语言标签
+ self.current_speaker = None # Store current speaker
+ self.current_language_tag = None # Store current ASR recognized language tag
- # llm相关变量
+ # LLM related variables
self.llm_finish_task = True
self.dialogue = Dialogue()
- # tts相关变量
+ # TTS related variables
self.sentence_id = None
- # 处理TTS响应没有文本返回
+ # Handle TTS response with no text returned
self.tts_MessageText = ""
- # iot相关变量
+ # IoT related variables
self.iot_descriptors = {}
self.func_handler = None
self.cmd_exit = self.config["exit_commands"]
- # 是否在聊天结束后关闭连接
+ # Whether to close connection after chat ends
self.close_after_chat = False
self.load_function_plugin = False
self.intent_type = "nointent"
self.timeout_seconds = (
int(self.config.get("close_connection_no_voice_time", 120)) + 60
- ) # 在原来第一道关闭的基础上加60秒,进行二道关闭
+ ) # Add 60 seconds to original first timeout for second timeout check
self.timeout_task = None
- # {"mcp":true} 表示启用MCP功能
+ # {"mcp":true} indicates MCP function enabled
self.features = None
- # 标记连接是否来自MQTT
+ # Mark if connection is from MQTT
self.conn_from_mqtt_gateway = False
- # 初始化提示词管理器
+ # Initialize prompt manager
self.prompt_manager = PromptManager(self.config, self.logger)
async def handle_connection(self, ws):
try:
- # 获取运行中的事件循环(必须在异步上下文中)
+ # Get running event loop (must be in async context)
self.loop = asyncio.get_running_loop()
- # 获取并验证headers
+ # Get and verify headers
self.headers = dict(ws.request.headers)
real_ip = self.headers.get("x-real-ip") or self.headers.get(
"x-forwarded-for"
@@ -186,34 +201,45 @@ class ConnectionHandler:
)
self.device_id = self.headers.get("device-id", None)
+ # Prioritize client-id for session identification, fallback to device-id
+ self.client_id = self.headers.get("client-id", self.device_id)
- # 认证通过,继续处理
+ # Force-map this physical device to your desired coach/client
+ if self.device_id == "b0:a6:04:5b:d7:98":
+ old_client_id = self.client_id
+ self.client_id = "26ea0ba9-2d55-4368-a56d-19c4a27c0772"
+ self.headers["client-id"] = self.client_id
+ self.logger.bind(tag=TAG).info(
+ f"[FORCE MAP WS] device {self.device_id}: {old_client_id} -> {self.client_id}"
+ )
+
+ # Authentication passed, continue processing
self.websocket = ws
- # 检查是否来自MQTT连接
+ # Check if from MQTT connection
request_path = ws.request.path
self.conn_from_mqtt_gateway = request_path.endswith("?from=mqtt_gateway")
if self.conn_from_mqtt_gateway:
- self.logger.bind(tag=TAG).info("连接来自:MQTT网关")
+ self.logger.bind(tag=TAG).info("Connection from: MQTT gateway")
- # 初始化活动时间戳
+ # Initialize activity timestamp
self.first_activity_time = time.time() * 1000
self.last_activity_time = time.time() * 1000
- # 启动超时检查任务
+ # Start timeout check task
self.timeout_task = asyncio.create_task(self._check_timeout())
self.welcome_msg = self.config["xiaozhi"]
self.welcome_msg["session_id"] = self.session_id
- # 在后台初始化配置和组件(完全不阻塞主循环)
+ # Initialize config and components in background (completely non-blocking main loop)
asyncio.create_task(self._background_initialize())
try:
async for message in self.websocket:
await self._route_message(message)
except websockets.exceptions.ConnectionClosed:
- self.logger.bind(tag=TAG).info("客户端断开连接")
+ self.logger.bind(tag=TAG).info("Client disconnected")
except AuthenticationError as e:
self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
@@ -226,23 +252,23 @@ class ConnectionHandler:
try:
await self._save_and_close(ws)
except Exception as final_error:
- self.logger.bind(tag=TAG).error(f"最终清理时出错: {final_error}")
- # 确保即使保存记忆失败,也要关闭连接
+ self.logger.bind(tag=TAG).error(f"Error during final cleanup: {final_error}")
+ # Ensure connection is closed even if saving memory fails
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
- f"强制关闭连接时出错: {close_error}"
+ f"Error during forced connection close: {close_error}"
)
async def _save_and_close(self, ws):
- """保存记忆并关闭连接"""
+ """Save memory and close connection"""
try:
if self.memory:
- # 使用线程池异步保存记忆
+ # Use thread pool to save memory asynchronously
def save_memory_task():
try:
- # 创建新事件循环(避免与主循环冲突)
+ # Create new event loop (avoid conflict with main loop)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
@@ -251,56 +277,66 @@ class ConnectionHandler:
)
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}")
finally:
try:
loop.close()
except Exception:
pass
- # 启动线程保存记忆,不等待完成
+ # Start thread to save memory, do not wait for completion
threading.Thread(target=save_memory_task, daemon=True).start()
except Exception as e:
- self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to save memory: {e}")
finally:
- # 立即关闭连接,不等待记忆保存完成
+ # Close connection immediately, do not wait for memory save completion
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
- f"保存记忆后关闭连接失败: {close_error}"
+ f"Failed to close connection after saving memory: {close_error}"
)
async def _discard_message_with_bind_prompt(self):
- """丢弃消息并检查是否需要播放绑定提示"""
+ """Discard message and check if binding prompt is needed"""
current_time = time.time()
- # 检查是否需要播放绑定提示
+ # Check if binding prompt is needed
if current_time - self.last_bind_prompt_time >= self.bind_prompt_interval:
self.last_bind_prompt_time = current_time
- # 复用现有的绑定提示逻辑
+ # Reuse existing binding prompt logic
from core.handle.receiveAudioHandle import check_bind_device
asyncio.create_task(check_bind_device(self))
async def _route_message(self, message):
- """消息路由"""
- # 检查是否已经获取到真实的绑定状态
- if not self.bind_completed_event.is_set():
- # 还没有获取到真实状态,等待直到获取到真实状态或超时
+ """Message routing"""
+ # 1. Bypass bind check for protocol handshake
+ is_hello_msg = False
+ if isinstance(message, str):
+ try:
+ msg_json = json.loads(message)
+ if isinstance(msg_json, dict) and msg_json.get("type") == "hello":
+ is_hello_msg = True
+ except:
+ pass
+
+ # Check if real binding status has been obtained
+ if not is_hello_msg and not self.bind_completed_event.is_set():
+ # Real status not obtained yet, wait until real status obtained or timeout
try:
await asyncio.wait_for(self.bind_completed_event.wait(), timeout=1)
except asyncio.TimeoutError:
- # 超时仍未获取到真实状态,丢弃消息
+ # Timeout still not obtained real status, discard message
await self._discard_message_with_bind_prompt()
return
- # 已经获取到真实状态,检查是否需要绑定
- if self.need_bind:
- # 需要绑定,丢弃消息
+ # Real status obtained, check if binding is needed
+ if not is_hello_msg and self.need_bind:
+ # Binding needed, discard message
await self._discard_message_with_bind_prompt()
return
- # 不需要绑定,继续处理消息
+ # Binding not needed, continue processing message
if isinstance(message, str):
await handleTextMessage(self, message)
@@ -308,62 +344,62 @@ class ConnectionHandler:
if self.vad is None or self.asr is None:
return
- # 处理来自MQTT网关的音频包
+ # Handle audio packet from MQTT gateway
if self.conn_from_mqtt_gateway and len(message) >= 16:
handled = await self._process_mqtt_audio_message(message)
if handled:
return
- # 不需要头部处理或没有头部时,直接处理原始消息
+ # Directly process raw message when no header processing needed or no header
self.asr_audio_queue.put(message)
async def _process_mqtt_audio_message(self, message):
"""
- 处理来自MQTT网关的音频消息,解析16字节头部并提取音频数据
+ Handle audio message from MQTT gateway, parse 16-byte header and extract audio data
Args:
- message: 包含头部的音频消息
+ message: Audio message with header
Returns:
- bool: 是否成功处理了消息
+ bool: Whether the message processed successfully
"""
try:
- # 提取头部信息
+ # Extract header info
timestamp = int.from_bytes(message[8:12], "big")
audio_length = int.from_bytes(message[12:16], "big")
- # 提取音频数据
+ # Extract audio data
if audio_length > 0 and len(message) >= 16 + audio_length:
- # 有指定长度,提取精确的音频数据
+ # Specified length, extract exact audio data
audio_data = message[16 : 16 + audio_length]
- # 基于时间戳进行排序处理
+ # Process based on timestamp sorting
self._process_websocket_audio(audio_data, timestamp)
return True
elif len(message) > 16:
- # 没有指定长度或长度无效,去掉头部后处理剩余数据
+ # No specified length or invalid length, process remaining data after removing header
audio_data = message[16:]
self.asr_audio_queue.put(audio_data)
return True
except Exception as e:
- self.logger.bind(tag=TAG).error(f"解析WebSocket音频包失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to parse WebSocket audio packet: {e}")
- # 处理失败,返回False表示需要继续处理
+ # Process failed, return False indicating continue processing
return False
def _process_websocket_audio(self, audio_data, timestamp):
- """处理WebSocket格式的音频包"""
- # 初始化时间戳序列管理
+ """Process WebSocket format audio packet"""
+ # Initialize timestamp sequence management
if not hasattr(self, "audio_timestamp_buffer"):
self.audio_timestamp_buffer = {}
self.last_processed_timestamp = 0
self.max_timestamp_buffer_size = 20
- # 如果时间戳是递增的,直接处理
+ # If timestamp is increasing, process directly
if timestamp >= self.last_processed_timestamp:
self.asr_audio_queue.put(audio_data)
self.last_processed_timestamp = timestamp
- # 处理缓冲区中的后续包
+ # Process subsequent packets in buffer
processed_any = True
while processed_any:
processed_any = False
@@ -375,35 +411,35 @@ class ConnectionHandler:
processed_any = True
break
else:
- # 乱序包,暂存
+ # Out of order packet, buffer it
if len(self.audio_timestamp_buffer) < self.max_timestamp_buffer_size:
self.audio_timestamp_buffer[timestamp] = audio_data
else:
self.asr_audio_queue.put(audio_data)
async def handle_restart(self, message):
- """处理服务器重启请求"""
+ """Handle server restart request"""
try:
- self.logger.bind(tag=TAG).info("收到服务器重启指令,准备执行...")
+ self.logger.bind(tag=TAG).info("Received server restart command, preparing to execute...")
- # 发送确认响应
+ # Send confirmation response
await self.websocket.send(
json.dumps(
{
"type": "server",
"status": "success",
- "message": "服务器重启中...",
+ "message": "Server restarting...",
"content": {"action": "restart"},
}
)
)
- # 异步执行重启操作
+ # Async execute restart operation
def restart_server():
- """实际执行重启的方法"""
+ """Actual restart execution method"""
time.sleep(1)
- self.logger.bind(tag=TAG).info("执行服务器重启...")
+ self.logger.bind(tag=TAG).info("Executing server restart...")
subprocess.Popen(
[sys.executable, "app.py"],
stdin=sys.stdin,
@@ -413,11 +449,11 @@ class ConnectionHandler:
)
os._exit(0)
- # 使用线程执行重启避免阻塞事件循环
+ # Use thread to execute restart to avoid blocking event loop
threading.Thread(target=restart_server, daemon=True).start()
except Exception as e:
- self.logger.bind(tag=TAG).error(f"重启失败: {str(e)}")
+ self.logger.bind(tag=TAG).error(f"Restart failed: {str(e)}")
await self.websocket.send(
json.dumps(
{
@@ -432,8 +468,19 @@ class ConnectionHandler:
def _initialize_components(self):
try:
if self.tts is None:
- self.tts = self._initialize_tts()
- # 打开语音合成通道
+ # Check if a private voice override is set for this client
+ selected_module = self.config.get("selected_module", {}).get("TTS")
+ has_private_voice = False
+ if selected_module and selected_module in self.config.get("TTS", {}):
+ has_private_voice = "private_voice" in self.config["TTS"][selected_module]
+
+ # Try to reuse global TTS instance ONLY if no private voice override is present
+ if self._tts is not None and not has_private_voice:
+ self.tts = self._tts
+ else:
+ self.logger.bind(tag=TAG).info(f"Initializing private TTS instance (has_private_voice={has_private_voice})")
+ self.tts = self._initialize_tts(use_cache=not has_private_voice)
+ # Open audio synthesis channel
asyncio.run_coroutine_threadsafe(
self.tts.open_audio_channels(self), self.loop
)
@@ -445,54 +492,147 @@ class ConnectionHandler:
)
self.logger = create_connection_logger(self.selected_module_str)
- """初始化组件"""
- if self.config.get("prompt") is not None:
+ """Initialize components"""
+ prompt = None
+ self._load_pipeline_prompts()
+
+ persona_prompt = self.pipeline_prompts.get("persona") if self.pipeline_prompts else None
+ if persona_prompt:
+ prompt = persona_prompt
+ self.logger.bind(tag=TAG).info(
+ f"Layered persona prompt loaded successfully {prompt[:50]}..."
+ )
+ elif self.config.get("prompt") is not None:
user_prompt = self.config["prompt"]
- # 使用快速提示词进行初始化
- prompt = self.prompt_manager.get_quick_prompt(user_prompt)
+ # Legacy fallback: use quick prompt for initialization
+ client_id = self.headers.get("client-id")
+ prompt = self.prompt_manager.get_quick_prompt(user_prompt, self.device_id, client_id)
self.change_system_prompt(prompt)
self.logger.bind(tag=TAG).info(
- f"快速初始化组件: prompt成功 {prompt[:50]}..."
+ f"Quick component initialization: prompt success {prompt[:50]}..."
)
- """初始化本地组件"""
+ """Initialize local components"""
if self.vad is None:
self.vad = self._vad
if self.asr is None:
self.asr = self._initialize_asr()
- # 初始化声纹识别
+ # Initialize voiceprint recognition
self._initialize_voiceprint()
- # 打开语音识别通道
+ # Open audio recognition channel
asyncio.run_coroutine_threadsafe(
self.asr.open_audio_channels(self), self.loop
)
- """加载记忆"""
+ # Protocol Enhancement: Notify client that initialization is complete and listening has started
+ asyncio.run_coroutine_threadsafe(
+ self.websocket.send(json.dumps({"type": "stt", "state": "listening", "session_id": self.session_id})),
+ self.loop
+ )
+ self.logger.bind(tag=TAG).info("ASR components ready, notified client: state=listening")
+
+ """Load memory"""
self._initialize_memory()
- """加载意图识别"""
+ """Load intent recognition"""
self._initialize_intent()
- """初始化上报线程"""
+ """Initialize report thread"""
self._init_report_threads()
- """更新系统提示词"""
- self._init_prompt_enhancement()
+ """Update system prompt"""
+ self._init_prompt_enhancement(prompt if 'prompt' in locals() else None)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to instantiate components: {e}")
- def _init_prompt_enhancement(self):
+ def _init_prompt_enhancement(self, current_prompt=None):
- # 更新上下文信息
+ # Update context info
self.prompt_manager.update_context_info(self, self.client_ip)
+
+ # Prefer persona prompt from the layered pipeline if available.
+ persona_prompt = None
+ if self.pipeline_prompts:
+ persona_prompt = self.pipeline_prompts.get("persona")
+
+ # Fallback order:
+ # 1. explicit current_prompt passed in
+ # 2. layered persona prompt
+ # 3. config default prompt
+ base_prompt = current_prompt if current_prompt else (persona_prompt or self.config["prompt"])
+
+ client_id = self.headers.get("client-id") if self.headers else None
enhanced_prompt = self.prompt_manager.build_enhanced_prompt(
- self.config["prompt"], self.device_id, self.client_ip
+ base_prompt, self.device_id, self.client_ip, client_id=client_id
)
if enhanced_prompt:
self.change_system_prompt(enhanced_prompt)
- self.logger.bind(tag=TAG).debug("系统提示词已增强更新")
+ self.logger.bind(tag=TAG).debug("System prompt enhanced successfully")
+
+
+ def _get_volume_level(self):
+ """Unified method to get volume level from headers or MCP"""
+ if self.mcp_volume and self.mcp_volume != "unknown":
+ return str(self.mcp_volume)
+
+ # Lazy sync if unknown
+ if hasattr(self, "mcp_client") and self.mcp_client:
+ try:
+ status_tool = "get_device_status" if self.mcp_client.has_tool("get_device_status") else None
+ if not status_tool:
+ for t in self.mcp_client.tools:
+ if "status" in t.lower(): status_tool = t; break
+
+ if status_tool:
+ from core.providers.tools.device_mcp.mcp_handler import sync_device_hardware_status
+ future = asyncio.run_coroutine_threadsafe(sync_device_hardware_status(self, status_tool), self.loop)
+ future.result(timeout=2.0)
+ if self.mcp_volume and self.mcp_volume != "unknown":
+ return str(self.mcp_volume)
+ except: pass
+ return "unknown"
+
+ def _get_battery_level(self):
+ """Unified method to get battery level from headers or IoT status"""
+ # 1. Check HTTP Headers (Session Initialization)
+ if self.headers:
+ battery_keys = ["battery", "x-battery", "battery-level", "x-device-battery", "bat"]
+ for key in battery_keys:
+ level = self.headers.get(key)
+ if level and level != "unknown":
+ return str(level)
+
+ # 2. Check MCP Status (Cache)
+ if self.mcp_battery and self.mcp_battery != "unknown":
+ return str(self.mcp_battery)
+
+ # 3. Check IoT Descriptors
+ try:
+ for desc in self.iot_descriptors.values():
+ for prop in desc.properties:
+ prop_name = prop.get("name", "").lower()
+ if prop_name in ["battery", "bat", "battery_level", "vbat", "power_level"]:
+ level = prop.get("value")
+ if level is not None: return str(level)
+ except: pass
+
+ # 4. Lazy MCP Sync
+ if (not self.mcp_battery or self.mcp_battery == "unknown") and hasattr(self, "mcp_client") and self.mcp_client:
+ try:
+ status_tool = "get_device_status" if self.mcp_client.has_tool("get_device_status") else None
+ if not status_tool:
+ for t in self.mcp_client.tools:
+ if "status" in t.lower(): status_tool = t; break
+ if status_tool:
+ from core.providers.tools.device_mcp.mcp_handler import sync_device_hardware_status
+ future = asyncio.run_coroutine_threadsafe(sync_device_hardware_status(self, status_tool), self.loop)
+ future.result(timeout=2.5)
+ if self.mcp_battery and self.mcp_battery != "unknown":
+ return str(self.mcp_battery)
+ except: pass
+ return "unknown"
def _init_report_threads(self):
- """初始化ASR和TTS上报线程"""
+ """Initialize ASR and TTS report threads"""
if not self.read_config_from_api or self.need_bind:
return
if self.chat_history_conf == 0:
@@ -502,13 +642,13 @@ class ConnectionHandler:
target=self._report_worker, daemon=True
)
self.report_thread.start()
- self.logger.bind(tag=TAG).info("TTS上报线程已启动")
+ self.logger.bind(tag=TAG).info("TTS report thread started")
- def _initialize_tts(self):
- """初始化TTS"""
+ def _initialize_tts(self, use_cache=True):
+ """Initialize TTS"""
tts = None
if not self.need_bind:
- tts = initialize_tts(self.config)
+ tts = initialize_tts(self.config, use_cache=use_cache)
if tts is None:
tts = DefaultTTS(self.config, delete_audio_file=True)
@@ -516,50 +656,96 @@ class ConnectionHandler:
return tts
def _initialize_asr(self):
- """初始化ASR"""
+ """Initialize ASR"""
+ # Check if we can reuse the global ASR instance
+ # Conditions:
+ # 1. Global instance exists
+ # 2. Global instance is Local type (reusable)
+ # 3. Client config matches global config (no override)
+ current_asr = self.config["selected_module"]["ASR"]
+ global_asr = self.common_config["selected_module"]["ASR"]
+
if (
self._asr is not None
and hasattr(self._asr, "interface_type")
and self._asr.interface_type == InterfaceType.LOCAL
+ and current_asr == global_asr
):
- # 如果公共ASR是本地服务,则直接返回
- # 因为本地一个实例ASR,可以被多个连接共享
+ # If public ASR is a local service AND matches client config, reuse it
asr = self._asr
else:
- # 如果公共ASR是远程服务,则初始化一个新实例
- # 因为远程ASR,涉及到websocket连接和接收线程,需要每个连接一个实例
+ # If public ASR is remote, OR client requested a different module, initialize new instance
asr = initialize_asr(self.config)
return asr
def _initialize_voiceprint(self):
- """为当前连接初始化声纹识别"""
+ """Initialize voiceprint recognition for current connection"""
try:
voiceprint_config = self.config.get("voiceprint", {})
if voiceprint_config:
voiceprint_provider = VoiceprintProvider(voiceprint_config)
if voiceprint_provider is not None and voiceprint_provider.enabled:
self.voiceprint_provider = voiceprint_provider
- self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
+ self.logger.bind(tag=TAG).info("Voiceprint recognition enabled dynamically on connection")
else:
- self.logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整")
+ self.logger.bind(tag=TAG).warning("Voiceprint recognition enabled but configuration incomplete")
else:
- self.logger.bind(tag=TAG).info("声纹识别功能未启用")
+ self.logger.bind(tag=TAG).info("Voiceprint recognition not enabled")
except Exception as e:
- self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}")
+ self.logger.bind(tag=TAG).warning(f"Voiceprint recognition initialization failed: {str(e)}")
+
+ def _load_local_client_config(self):
+ """Load local client config to override default settings"""
+ if not self.headers:
+ return
+
+ client_id = self.headers.get("client-id", self.device_id)
+ if not client_id:
+ return
+
+ try:
+ config_path = os.path.join("data", client_id, "config.json")
+ if os.path.exists(config_path):
+ with open(config_path, "r") as f:
+ client_config = json.load(f)
+
+ # Override TTS voice if present
+ if "voice" in client_config:
+ voice = client_config["voice"]
+ selected_module = self.config.get("selected_module", {}).get("TTS")
+ if selected_module and selected_module in self.config.get("TTS", {}):
+ # Most TTS providers use 'private_voice' as an override
+ self.config["TTS"][selected_module]["private_voice"] = voice
+ self.logger.bind(tag=TAG).info(f"Overriding TTS voice for client {client_id}: {voice}")
+
+ # Override ASR module if present
+ if "asr_module" in client_config:
+ asr_module = client_config["asr_module"]
+ if asr_module in self.config.get("ASR", {}):
+ self.config["selected_module"]["ASR"] = asr_module
+ self.logger.bind(tag=TAG).info(f"Overriding ASR module for client {client_id}: {asr_module}")
+ else:
+ self.logger.bind(tag=TAG).warning(f"Client {client_id} requested invalid ASR module: {asr_module}")
+
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to load local client config: {e}")
async def _background_initialize(self):
- """在后台初始化配置和组件(完全不阻塞主循环)"""
+ """Initialize config and components in background (completely non-blocking main loop)"""
try:
- # 异步获取差异化配置
+ # Load local client config first to ensure it can override other settings
+ self._load_local_client_config()
+
+ # Async get diff config
await self._initialize_private_config_async()
- # 在线程池中初始化组件
+ # Initialize components in thread pool
self.executor.submit(self._initialize_components)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"后台初始化失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Background initialization failed: {e}")
async def _initialize_private_config_async(self):
- """从接口异步获取差异化配置(异步版本,不阻塞主循环)"""
+ """Fetch private config from API async (async version, non-blocking main loop)"""
if not self.read_config_from_api:
self.need_bind = False
self.bind_completed_event.set()
@@ -573,7 +759,7 @@ class ConnectionHandler:
)
private_config["delete_audio"] = bool(self.config.get("delete_audio", True))
self.logger.bind(tag=TAG).info(
- f"{time.time() - begin_time} 秒,异步获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
+ f"{time.time() - begin_time} seconds, async fetch private config success: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
)
self.need_bind = False
self.bind_completed_event.set()
@@ -586,7 +772,7 @@ class ConnectionHandler:
private_config = {}
except Exception as e:
self.need_bind = True
- self.logger.bind(tag=TAG).error(f"异步获取差异化配置失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Async fetch private config failed: {e}")
private_config = {}
init_llm, init_tts, init_memory, init_intent = (
@@ -637,7 +823,7 @@ class ConnectionHandler:
self.config["Intent"] = private_config["Intent"]
model_intent = private_config.get("selected_module", {}).get("Intent", {})
self.config["selected_module"]["Intent"] = model_intent
- # 加载插件配置
+ # Load plugin config
if model_intent != "Intent_nointent":
plugin_from_server = private_config.get("plugins", {})
for plugin, config_str in plugin_from_server.items():
@@ -648,7 +834,7 @@ class ConnectionHandler:
] = plugin_from_server.keys()
if private_config.get("prompt", None) is not None:
self.config["prompt"] = private_config["prompt"]
- # 获取声纹信息
+ # Get voiceprint info
if private_config.get("voiceprint", None) is not None:
self.config["voiceprint"] = private_config["voiceprint"]
if private_config.get("summaryMemory", None) is not None:
@@ -662,10 +848,10 @@ class ConnectionHandler:
if private_config.get("context_providers", None) is not None:
self.config["context_providers"] = private_config["context_providers"]
- # 使用 run_in_executor 在线程池中执行 initialize_modules,避免阻塞主循环
+ # Use run_in_executor to execute initialize_modules in thread pool, avoid blocking main loop
try:
modules = await self.loop.run_in_executor(
- None, # 使用默认线程池
+ None, # Use default thread pool
initialize_modules,
self.logger,
private_config,
@@ -677,7 +863,7 @@ class ConnectionHandler:
init_intent,
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to initialize components: {e}")
modules = {}
if modules.get("tts", None) is not None:
self.tts = modules["tts"]
@@ -687,15 +873,15 @@ class ConnectionHandler:
self.asr = modules["asr"]
if modules.get("llm", None) is not None:
self.llm = modules["llm"]
- if modules.get("intent", None) is not None:
- self.intent = modules["intent"]
+ if modules.get("Intent", None) is not None:
+ self.intent = modules["Intent"]
if modules.get("memory", None) is not None:
self.memory = modules["memory"]
def _initialize_memory(self):
if self.memory is None:
return
- """初始化记忆模块"""
+ """Initialize memory module"""
self.memory.init_memory(
role_id=self.device_id,
llm=self.llm,
@@ -703,21 +889,21 @@ class ConnectionHandler:
save_to_file=not self.read_config_from_api,
)
- # 获取记忆总结配置
+ # Get memory summary config
memory_config = self.config["Memory"]
memory_type = self.config["Memory"][self.config["selected_module"]["Memory"]][
"type"
]
- # 如果使用 nomen,直接返回
+ # If nomen is used, return directly
if memory_type == "nomem":
return
- # 使用 mem_local_short 模式
+ # Use mem_local_short mode
elif memory_type == "mem_local_short":
memory_llm_name = memory_config[self.config["selected_module"]["Memory"]][
"llm"
]
if memory_llm_name and memory_llm_name in self.config["LLM"]:
- # 如果配置了专用LLM,则创建独立的LLM实例
+ # If dedicated LLM configured, create independent LLM instance
from core.utils import llm as llm_utils
memory_llm_config = self.config["LLM"][memory_llm_name]
@@ -726,76 +912,544 @@ class ConnectionHandler:
memory_llm_type, memory_llm_config
)
self.logger.bind(tag=TAG).info(
- f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}"
+ f"Created dedicated LLM for memory summary: {memory_llm_name}, type: {memory_llm_type}"
)
self.memory.set_llm(memory_llm)
else:
- # 否则使用主LLM
+ # Otherwise use main LLM
self.memory.set_llm(self.llm)
- self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
+ self.logger.bind(tag=TAG).info("Using main LLM as intent recognition model")
def _initialize_intent(self):
+ """Standardized to Uppercase 'Intent' to match config.yaml"""
if self.intent is None:
return
- self.intent_type = self.config["Intent"][
- self.config["selected_module"]["Intent"]
- ]["type"]
+
+ # Use Uppercase 'Intent' everywhere
+ selected_intent = self.config["selected_module"].get("Intent")
+ if not selected_intent:
+ return
+
+ self.intent_type = self.config["Intent"][selected_intent]["type"]
+
if self.intent_type == "function_call" or self.intent_type == "intent_llm":
self.load_function_plugin = True
- """初始化意图识别模块"""
- # 获取意图识别配置
+
intent_config = self.config["Intent"]
- intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][
- "type"
- ]
-
- # 如果使用 nointent,直接返回
- if intent_type == "nointent":
+
+ if self.intent_type == "nointent":
return
- # 使用 intent_llm 模式
- elif intent_type == "intent_llm":
- intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][
- "llm"
- ]
-
+ elif self.intent_type == "intent_llm":
+ intent_llm_name = intent_config[selected_intent].get("llm")
+
if intent_llm_name and intent_llm_name in self.config["LLM"]:
- # 如果配置了专用LLM,则创建独立的LLM实例
from core.utils import llm as llm_utils
-
intent_llm_config = self.config["LLM"][intent_llm_name]
intent_llm_type = intent_llm_config.get("type", intent_llm_name)
- intent_llm = llm_utils.create_instance(
- intent_llm_type, intent_llm_config
- )
- self.logger.bind(tag=TAG).info(
- f"为意图识别创建了专用LLM: {intent_llm_name}, 类型: {intent_llm_type}"
- )
+ intent_llm = llm_utils.create_instance(intent_llm_type, intent_llm_config)
+
self.intent.set_llm(intent_llm)
+ self.logger.bind(tag=TAG).info(f"Intent Brain Linked: {intent_llm_name}")
else:
- # 否则使用主LLM
self.intent.set_llm(self.llm)
- self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
+ self.logger.bind(tag=TAG).info("Using Main LLM for Intent.")
- """加载统一工具处理器"""
+ """Load unified tool handler"""
self.func_handler = UnifiedToolHandler(self)
- # 异步初始化工具处理器
- if hasattr(self, "loop") and self.loop:
- asyncio.run_coroutine_threadsafe(self.func_handler._initialize(), self.loop)
def change_system_prompt(self, prompt):
self.prompt = prompt
- # 更新系统prompt至上下文
+ # Update system prompt to context
self.dialogue.update_system_message(self.prompt)
- def chat(self, query, depth=0):
- if query is not None:
- self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
+ def _load_pipeline_prompts(self):
+ """Load persona / decision / interpretation prompts for the current client."""
+ try:
+ client_id = self.headers.get("client-id") if self.headers else None
+ self.pipeline_prompts = self.prompt_manager.get_pipeline_prompts(
+ client_id=client_id,
+ device_id=self.device_id,
+ )
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to load pipeline prompts: {e}")
+ self.pipeline_prompts = {}
- # 为最顶层时新建会话ID和发送FIRST请求
+ def _llm_single_shot(self, system_prompt: str, user_payload: Any) -> str:
+ """Run a one-shot LLM call without mutating the main dialogue history."""
+ if not self.llm:
+ return ""
+
+ try:
+ if isinstance(user_payload, str):
+ user_content = user_payload
+ else:
+ user_content = json.dumps(user_payload, ensure_ascii=False, indent=2)
+
+ temp_dialogue = Dialogue()
+ temp_dialogue.update_system_message(system_prompt)
+ temp_dialogue.put(Message(role="user", content=user_content))
+
+ memory_str = None
+ messages = temp_dialogue.get_llm_dialogue_with_memory(
+ memory_str, self.config.get("voiceprint", {})
+ )
+
+ chunks = []
+ temp_session_id = str(uuid.uuid4())
+ for chunk in self.llm.response(temp_session_id, messages):
+ if chunk:
+ chunks.append(chunk)
+ return "".join(chunks).strip()
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Single-shot LLM call failed: {e}")
+ return ""
+
+ def _safe_parse_json(self, raw_text: str) -> Dict[str, Any]:
+ """Parse JSON response safely, with fallback extraction from free text."""
+ if not raw_text:
+ return {}
+
+ try:
+ return json.loads(raw_text)
+ except Exception:
+ pass
+
+ extracted = extract_json_from_string(raw_text)
+ if extracted:
+ try:
+ return json.loads(extracted)
+ except Exception:
+ pass
+
+ self.logger.bind(tag=TAG).warning(f"Failed to parse JSON response: {raw_text[:200]}")
+ return {}
+ def _filter_stale_realtime_summary_lines(self, summary_text: str) -> str:
+ if not summary_text:
+ return ""
+
+ blocked_keywords = (
+ "current cgm",
+ "critical cgm",
+ "last bolus",
+ "temp basal",
+ "latest pump event",
+ "fresh pump status",
+ "pump sync issue",
+ "tir:",
+ "time in range",
+ "mean glucose",
+ "gmi:",
+ "mg/dl",
+ "u/hr",
+ "auto-bolus",
+ "bolus recorded",
+ "boluses recorded",
+ "pump_events.csv",
+ "cgm.csv",
+ )
+
+ kept_lines = []
+ for line in summary_text.splitlines():
+ lowered = line.lower()
+ if any(keyword in lowered for keyword in blocked_keywords):
+ continue
+ kept_lines.append(line)
+
+ return "\n".join(kept_lines).strip()
+
+ def _build_pipeline_analysis_result(self, query: str, context_needs: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+ """Build structured analysis input for the decision / interpretation pipeline."""
+ result = {
+ "user_query": query,
+ "language_hint": getattr(self, "current_language_tag", None),
+ "intent_context": context_needs or {},
+ "glucose_now": None,
+ "cgm_metrics": {},
+ "events": {},
+ "patterns": {
+ "daily": [],
+ "weekly": [],
+ "monthly": [],
+ },
+ "pump_status": {},
+ "pump_patterns": {},
+ "pump_glucose_joint": {},
+ "anomalies": [],
+ }
+
+ client_id = self.headers.get("client-id") if self.headers else None
+ if not client_id:
+ return result
+
+ try:
+ config_path = os.path.join("data", client_id, "config.json")
+ client_cfg = {}
+ if os.path.exists(config_path):
+ with open(config_path, "r", encoding="utf-8") as f:
+ client_cfg = json.load(f)
+
+ cgm_enabled = bool(client_cfg.get("cgm"))
+ pump_enabled = bool(client_cfg.get("pump"))
+
+ if cgm_enabled:
+ from core.utils.cgm_manager import CGMManager
+ cgm_manager = CGMManager()
+
+ latest = None
+ if hasattr(cgm_manager, "get_latest_reading"):
+ latest = cgm_manager.get_latest_reading(client_id)
+ if latest:
+ result["glucose_now"] = latest.get("glucose")
+
+ # 这里尽量兼容你现有 manager,如果某个方法不存在就跳过
+ if hasattr(cgm_manager, "get_metrics_summary"):
+ metrics = cgm_manager.get_metrics_summary(client_id)
+ if isinstance(metrics, dict):
+ result["cgm_metrics"] = metrics.get("metrics", metrics)
+ if "events" in metrics and isinstance(metrics["events"], dict):
+ result["events"] = metrics["events"]
+
+ context_summary = None
+ if hasattr(cgm_manager, "get_context_summary"):
+ context_summary = cgm_manager.get_context_summary(client_id)
+ if context_summary:
+ result["patterns"]["daily"].append(context_summary)
+
+ if pump_enabled:
+ from core.utils.pump_manager import PumpManager
+ pump_manager = PumpManager()
+
+ # Coach pipeline fallback: use authoritative summary if structured methods are missing
+ if hasattr(pump_manager, "get_authoritative_summary"):
+ pump_context = pump_manager.get_authoritative_summary(client_id)
+ elif hasattr(pump_manager, "get_context_summary"):
+ pump_context = pump_manager.get_context_summary(client_id)
+
+ if pump_context:
+ result["pump_status"]["summary"] = pump_context
+
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to build pipeline analysis result: {e}")
+
+ return result
+
+ def run_coach_pipeline(self, query: str, context_needs: Optional[Dict[str, Any]] = None) -> Optional[str]:
+ """Run decision -> interpretation -> persona pipeline for diabetes coaching."""
+ prompts = self.pipeline_prompts or {}
+ persona_prompt = self.prompt or prompts.get("persona", "")
+ decision_prompt = prompts.get("decision", "")
+ interpretation_prompt = prompts.get("interpretation", "")
+
+ if not persona_prompt or not decision_prompt or not interpretation_prompt:
+ return None
+
+ analysis_result = self._build_pipeline_analysis_result(query, context_needs=context_needs)
+
+ decision_raw = self._llm_single_shot(decision_prompt, analysis_result)
+ decision_result = self._safe_parse_json(decision_raw)
+
+ interpretation_payload = {
+ "analysis_result": analysis_result,
+ "decision_result": decision_result,
+ }
+ insight_text = self._llm_single_shot(interpretation_prompt, interpretation_payload)
+ if not insight_text:
+ return None
+
+ persona_payload = {
+ "user_message": query,
+ "insight_text": insight_text,
+ "decision_result": decision_result,
+ "analysis_result": analysis_result,
+ }
+ final_reply = self._llm_single_shot(persona_prompt, persona_payload)
+ return final_reply or insight_text
+
+ def chat(self, query, depth=0, audio_data=None):
+ search_text = query or ""
+ if query is not None:
+ self.logger.bind(tag=TAG).info(f"LLM received user message: {query}")
+
+ # Parse Query (could be JSON or Text)
+ is_json = False
+ json_data = {}
+
+ if depth == 0:
+ try:
+ if query.strip().startswith("{") and query.strip().endswith("}"):
+ json_data = json.loads(query)
+ if "content" in json_data:
+ search_text = json_data["content"]
+ is_json = True
+ except json.JSONDecodeError:
+ pass
+
+ # 1. Intent Classification (Unified call for shortcuts, CGM context, pump context, and search injection)
+ intent_result = {
+ "needs_cgm": False,
+ "needs_pump": False,
+ "needs_news": False,
+ "needs_search": False,
+ "fast_answer": None,
+ "reply": None,
+ }
+ try:
+ client_id = self.headers.get("client-id") if self.headers else None
+ if client_id:
+ from core.utils.cgm_intent import classify_context_needs
+ intent_result = classify_context_needs(
+ search_text,
+ client_id,
+ self.config,
+ language_hint=getattr(self, "current_language_tag", None)
+ )
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Intent classification failed: {e}")
+
+ # 2. Fast Intent Check (time, weather, location, exit, volume, brightness - skip main LLM)
+ try:
+ client_id = self.headers.get("client-id") if self.headers else None
+ if client_id:
+ from core.utils.cgm_intent import get_fast_answer
+ fast_answer_type = intent_result.get("fast_answer")
+ if fast_answer_type:
+ # a. Special Case: Exit
+ if fast_answer_type == "exit":
+ self.logger.bind(tag=TAG).info(f"Exit intent recognized by LLM: {search_text}")
+ handle_exit(self)
+ return
+
+ # b. Apply Device Controls (Volume/Brightness)
+ if fast_answer_type in ["volume", "brightness"]:
+ self.logger.bind(tag=TAG).info(f"Applying device control: {fast_answer_type}")
+ # Execute IOT/Control commands here if necessary,
+ # but for now we'll just speak the confirmation.
+
+ # c. Get Content to Speak
+ fast_response = None
+
+ # Give priority to programmatic answers for data-driven intents
+ if fast_answer_type in ["time", "weather", "location", "battery", "volume"]:
+ hardware_stat = None
+ if fast_answer_type == "battery": hardware_stat = self._get_battery_level()
+ elif fast_answer_type == "volume": hardware_stat = self._get_volume_level()
+ fast_response = get_fast_answer(fast_answer_type, client_id, self.config, battery_level=hardware_stat)
+
+ # If no programmatic answer or it's a pure conversation intent, use LLM reply
+ if not fast_response:
+ fast_response = intent_result.get("reply")
+ elif intent_result.get("reply"):
+ # If we have both, we can optionally prefix (choosing to prefer the accurate data for now)
+ self.logger.bind(tag=TAG).debug(f"Combined response: LLM says '{intent_result.get('reply')}', using data: '{fast_response}'")
+
+ if fast_response:
+ self.logger.bind(tag=TAG).info(f"Fast response ({fast_answer_type}): {fast_response}")
+ self.sentence_id = str(uuid.uuid4().hex)
+ # Wake up TTS with FIRST message
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.FIRST,
+ content_type=ContentType.TEXT,
+ content_detail="",
+ )
+ )
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.TEXT,
+ content_detail=fast_response,
+ )
+ )
+ self.dialogue.put(Message(role="user", content=search_text))
+ self.dialogue.put(Message(role="assistant", content=fast_response))
+ return
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Fast answer check failed: {e}")
+
+ # Deterministic pump-bolus shortcut.
+ # ASR sometimes hears "bolus" as "bullet/bullets"; do not let this fall back to history/RAG.
+ # This answer must come directly from pump_events.csv via PumpManager.
+ try:
+ lower_search_text = (search_text or "").lower()
+ pump_bolus_keywords = [
+ "bolus",
+ "bolo",
+ "bullet",
+ "bullets",
+ "pump bolus",
+ "last pump bolus",
+ "last recorded bolus",
+ ]
+ asks_last = any(k in lower_search_text for k in ["last", "latest", "recent", "when", "上次", "最近", "上一"])
+ asks_pump_bolus = any(k in lower_search_text for k in pump_bolus_keywords)
+
+ if asks_pump_bolus and asks_last:
+ client_id = self.client_id if getattr(self, "client_id", None) else (self.headers.get("client-id") if self.headers else None)
+ if client_id:
+ from core.utils.pump_manager import PumpManager
+ pm = PumpManager()
+ self.logger.bind(tag=TAG).info(f"Direct pump bolus lookup for {client_id}: {search_text}")
+ pm.fetch_and_update(client_id)
+ direct_response = pm.format_latest_bolus_summary(client_id)
+ if direct_response:
+ direct_response = direct_response.replace("Last Bolus", "Last recorded bolus")
+ direct_response += " This is the last recorded bolus only, not the last insulin delivery."
+
+ self.sentence_id = str(uuid.uuid4().hex)
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.FIRST,
+ content_type=ContentType.TEXT,
+ content_detail="",
+ )
+ )
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.TEXT,
+ content_detail=direct_response,
+ )
+ )
+ self.dialogue.put(Message(role="user", content=search_text))
+ self.dialogue.put(Message(role="assistant", content=direct_response))
+ return None
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Direct pump bolus lookup failed: {e}")
+
+ try:
+ # Experimental: RAG Injection (using actual content)
+ if depth == 0 and self.headers:
+ client_id = self.headers.get("client-id")
+ if client_id:
+ context_list = []
+
+ # History RAG
+ hist_context = history_rag.search(search_text, client_id)
+ if hist_context:
+ self.logger.bind(tag=TAG).info(f"Injecting history RAG context for {client_id}")
+ context_list.append(hist_context)
+
+ # News/CGM RAG from Config
+ rag_config_path = os.path.join("data", client_id, "config.json")
+ if os.path.exists(rag_config_path):
+ with open(rag_config_path, "r") as f:
+ c = json.load(f)
+
+ # Use captured intent result (cached from start of chat)
+ context_needs = intent_result
+
+ # News RAG - only if enabled AND classifier says needed
+ if c.get("news_rag_enabled") and context_needs.get("needs_news"):
+ from core.utils.news_rag import news_rag
+ news_context = news_rag.search(search_text)
+ if news_context:
+ self.logger.bind(tag=TAG).info(f"Injecting news RAG context for {client_id}")
+ context_list.append(news_context)
+
+ # CGM - Only for clients with "cgm" config object
+ # Config format: {"cgm": {"api_secret": "...", "user_tz": "..."}}
+ cgm_config = c.get("cgm")
+ if cgm_config:
+ # Always include current reading (like time/date)
+ # Only fetch from service if data is stale (>5 min)
+ from core.utils.cgm_manager import CGMManager
+ import time as time_module
+ cgm_manager = CGMManager()
+
+ current_reading = cgm_manager.get_latest_reading(client_id)
+ cgm_is_critical = False
+
+ if current_reading:
+ glucose = current_reading.get("glucose", 0)
+ direction = current_reading.get("direction", "Unknown")
+ last_ts = current_reading.get("unix_s", 0)
+ now_ts = int(time_module.time())
+ data_age_min = (now_ts - last_ts) // 60
+
+ # Refresh from service if data is stale (>5 min)
+ if data_age_min > 5:
+ self.logger.bind(tag=TAG).debug(f"CGM data stale ({data_age_min}min), refreshing...")
+ cgm_manager.fetch_and_update(client_id)
+ current_reading = cgm_manager.get_latest_reading(client_id)
+ if current_reading:
+ glucose = current_reading.get("glucose", 0)
+ direction = current_reading.get("direction", "Unknown")
+
+ cgm_is_critical = glucose < 70 or glucose > 250
+
+ # Always add current reading to context (like time/date)
+ # The LLM prompt rules decide when to MENTION it
+ cgm_status = f"[Current CGM: {glucose} mg/dL, {direction}]"
+ if cgm_is_critical:
+ cgm_status = f"[CRITICAL CGM: {glucose} mg/dL, {direction}]"
+ self.logger.bind(tag=TAG).warning(f"CGM critical: {glucose} for {client_id}")
+ context_list.append(cgm_status)
+
+ # Full CGM context (trends, patterns) only if user asks
+ if context_needs.get("needs_cgm"):
+ cgm_summary = cgm_manager.get_context_summary(client_id)
+ if cgm_summary:
+ self.logger.bind(tag=TAG).info(f"Injecting full CGM context for {client_id}")
+ context_list.append(cgm_summary)
+
+ # Pump/CGM Sync moved to before coach pipeline above
+ pass
+
+ if context_needs.get("needs_cgm") and context_needs.get("needs_pump"):
+ self.logger.bind(tag=TAG).info(
+ f"Joint diabetes reasoning requested for {client_id}: injecting both CGM and pump context"
+ )
+
+ # Web Search - One-shot factual grounding
+ if context_needs.get("needs_search") and context_needs.get("search_query"):
+ search_query = context_needs.get("search_query")
+ self.logger.bind(tag=TAG).info(f"Triggering web search: {search_query}")
+ from core.utils.web_search import perform_web_search
+ search_results = perform_web_search(search_query, self.config)
+ if search_results:
+ # Truncate and wrap as a primary source
+ if len(search_results) > 2000:
+ search_results = search_results[:2000] + "... [truncated]"
+
+ context_list.append(
+ f"--- WEB SEARCH DATA: {search_query} ---\n"
+ f"{search_results}\n"
+ f"--- END DATA ---\n"
+ f"IMPORTANT: Use the data above to answer the user now. Do not mention searching again."
+ )
+
+ if not any([
+ context_needs.get("needs_cgm"),
+ context_needs.get("needs_pump"),
+ context_needs.get("needs_news"),
+ context_needs.get("needs_search"),
+ ]):
+ self.logger.bind(tag=TAG).debug(f"Context classifier: no extra injection needed")
+
+ # Inject Context into Query
+ if context_list:
+ full_context = "\n".join(context_list)
+ if is_json:
+ json_data["content"] = f"{search_text}\n{full_context}"
+ query = json.dumps(json_data, ensure_ascii=False)
+ else:
+ query = f"{search_text}\n{full_context}"
+
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"RAG Injection failed: {e}")
+
+ # Create session ID and send FIRST request when at top level
if depth == 0:
self.llm_finish_task = False
self.sentence_id = str(uuid.uuid4().hex)
+ self.suppress_tts = False
+
+
self.dialogue.put(Message(role="user", content=query))
self.tts.tts_text_queue.put(
TTSMessageDTO(
@@ -805,26 +1459,26 @@ class ConnectionHandler:
)
)
- # 设置最大递归深度,避免无限循环,可根据实际需求调整
+ # Set max recursion depth to avoid infinite loop, adjust as needed
MAX_DEPTH = 5
- force_final_answer = False # 标记是否强制最终回答
+ force_final_answer = False # Mark whether to force final answer
if depth >= MAX_DEPTH:
self.logger.bind(tag=TAG).debug(
- f"已达到最大工具调用深度 {MAX_DEPTH},将强制基于现有信息回答"
+ f"Max tool call depth {MAX_DEPTH} reached, forcing answer based on existing information"
)
force_final_answer = True
- # 添加系统指令,要求 LLM 基于现有信息回答
+ # Add system instruction, requesting LLM to answer based on existing information
self.dialogue.put(
Message(
role="user",
- content="[系统提示] 已达到最大工具调用次数限制,请你基于目前已经获取的所有信息,直接给出最终答案。不要再尝试调用任何工具。",
+ content="[System Prompt] Max tool call limit reached, please provide a final answer based on all information obtained so far. Do not attempt to call any more tools.",
)
)
# Define intent functions
functions = None
- # 达到最大深度时,禁用工具调用,强制 LLM 直接回答
+ # When max depth reached, disable tool calls, force LLM to answer directly
if (
self.intent_type == "function_call"
and hasattr(self, "func_handler")
@@ -834,22 +1488,104 @@ class ConnectionHandler:
response_message = []
try:
- # 使用带记忆的对话
+ # Layered diabetes-coach pipeline.
+ # Only run at top level for diabetes-related queries when layered prompts are available.
+ should_run_coach_pipeline = False
+ context_for_pipeline = intent_result if 'intent_result' in locals() else {}
+ if depth == 0 and self.pipeline_prompts and isinstance(context_for_pipeline, dict):
+ should_run_coach_pipeline = any([
+ context_for_pipeline.get("needs_cgm"),
+ context_for_pipeline.get("needs_pump"),
+ ])
+
+ # ON-DEMAND SYNC BEFORE COACH PIPELINE OR REGULAR CHAT
+ pump_summary = None
+ if isinstance(context_for_pipeline, dict):
+ client_id = self.client_id
+ if context_for_pipeline.get("needs_pump"):
+ from core.utils.pump_manager import PumpManager
+ pm = PumpManager()
+ self.logger.bind(tag=TAG).info(f"Syncing pump data for {client_id} before response...")
+ pm.fetch_and_update(client_id)
+ pump_summary = pm.get_authoritative_summary(client_id)
+
+ if context_for_pipeline.get("needs_cgm"):
+ from core.utils.cgm_manager import CGMManager
+ cm = CGMManager()
+ self.logger.bind(tag=TAG).info(f"Syncing CGM data for {client_id} before response...")
+ cm.fetch_and_update(client_id)
+ # CGM usually doesn't need an authoritative summary block in memory_str as it's less prone to "memory" confusion,
+ # but we sync it here anyway for the coach pipeline to be fresh.
+
+ if should_run_coach_pipeline:
+ try:
+ coach_reply = self.run_coach_pipeline(
+ search_text,
+ context_needs=context_for_pipeline,
+ )
+ if coach_reply:
+ self.logger.bind(tag=TAG).info(f"Coach pipeline reply: {coach_reply}")
+
+ self.dialogue.put(Message(role="assistant", content=coach_reply))
+
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.TEXT,
+ content_detail=coach_reply,
+ )
+ )
+ self.llm_finish_task = True
+ return None
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Coach pipeline failed, falling back to legacy chat path: {e}")
+
+ # Use dialogue with memory
+ # Use dialogue with memory
memory_str = None
+
if self.memory is not None:
future = asyncio.run_coroutine_threadsafe(
self.memory.query_memory(query), self.loop
)
memory_str = future.result()
+
+ # CRITICAL: Overwrite memory with authoritative pump data if available
+ if pump_summary:
+ authoritative_block = (
+ "[CRITICAL: THE DATA BELOW IS REAL-TIME. DISREGARD ANY CONTRADICTING PUMP INFO IN THE MEMORY TAG BELOW.]\n"
+ f"{pump_summary}\n"
+ "[END REAL-TIME DATA]"
+ )
+ if memory_str:
+ memory_str = f"{authoritative_block}\n\n{memory_str}"
+ else:
+ memory_str = authoritative_block
+
+ else:
+ # Fallback: Try to load local summary.txt
+ try:
+ c_id = self.headers.get("client-id") if self.headers else getattr(self, "device_id", None)
+ if c_id:
+ sum_path = os.path.join("data", c_id, "summary.txt")
+ if os.path.exists(sum_path):
+ with open(sum_path, "r", encoding="utf-8") as f:
+ memory_str = f.read().strip()
+ memory_str = self._filter_stale_realtime_summary_lines(memory_str)
+ except Exception as e:
+ self.logger.bind(tag=TAG).warning(f"Failed to load local summary: {e}")
+
if self.intent_type == "function_call" and functions is not None:
- # 使用支持functions的streaming接口
+ # Use streaming interface with function support
llm_responses = self.llm.response_with_functions(
self.session_id,
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
),
functions=functions,
+ audio_data=audio_data
)
else:
llm_responses = self.llm.response(
@@ -857,19 +1593,36 @@ class ConnectionHandler:
self.dialogue.get_llm_dialogue_with_memory(
memory_str, self.config.get("voiceprint", {})
),
+ audio_data=audio_data
)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
+ self.logger.bind(tag=TAG).error(f"LLM processing error {query}: {e}")
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail="I'm sorry, I'm not thinking clearly right now.")
return None
- # 处理流式响应
+ # Handle streaming response
tool_call_flag = False
- # 支持多个并行工具调用 - 使用列表存储
- tool_calls_list = [] # 格式: [{"id": "", "name": "", "arguments": ""}]
+ # Support multiple parallel tool calls - store in list
+ tool_calls_list = [] # Format: [{"id": "", "name": "", "arguments": ""}]
content_arguments = ""
self.client_abort = False
emotion_flag = True
+
+ # Buffer for intent trigger detection
+ stream_buffer = ""
+ trigger_executed = False
+ in_think_block = False # State for filtering tags
+
+ # Streaming watchdog (60s limit for total chat response)
+ chat_start_time = time.time()
+ CHAT_TIMEOUT = 60
+
for response in llm_responses:
+ # Check for total duration timeout
+ if time.time() - chat_start_time > CHAT_TIMEOUT:
+ self.logger.bind(tag=TAG).warning(f"Main chat stream exceeded {CHAT_TIMEOUT}s limit, aborting.")
+ break
+
if self.client_abort:
break
if self.intent_type == "function_call" and functions is not None:
@@ -881,7 +1634,6 @@ class ConnectionHandler:
content_arguments += content
if not tool_call_flag and content_arguments.startswith(""):
- # print("content_arguments", content_arguments)
tool_call_flag = True
if tools_call is not None and len(tools_call) > 0:
@@ -890,7 +1642,36 @@ class ConnectionHandler:
else:
content = response
- # 在llm回复中获取情绪表情,一轮对话只在开头获取一次
+ # --- Thinking Filter Logic ---
+ if content:
+ # Handle start of thinking block
+ if "" in content:
+ self.logger.bind(tag=TAG).info(f"Detected start in stream...")
+ pre, post = content.split("", 1)
+ # Process 'pre' (keep it)
+ # Discard 'post' (start of think) unless closed immediately
+ content = pre
+ in_think_block = True
+ # Check if closed in same chunk (edge case)
+ if " " in post:
+ _, remainder = post.split(" ", 1)
+ content += remainder
+ in_think_block = False
+ self.logger.bind(tag=TAG).info(f"Thinking block finished (same chunk).")
+
+ # Handle end of thinking block (if already in block)
+ elif in_think_block:
+ if " " in content:
+ _, post = content.split(" ", 1)
+ content = post
+ in_think_block = False
+ self.logger.bind(tag=TAG).info(f"Thinking block finished.")
+ else:
+ content = "" # Consume entire chunk as thinking
+ # Optional: self.logger.debug("Filtering thought chunk...")
+ # --- End Thinking Filter Logic ---
+
+ # Get emotion in LLM response, only once at the beginning of a turn
if emotion_flag and content is not None and content.strip():
asyncio.run_coroutine_threadsafe(
textUtils.get_emotion(self, content),
@@ -898,21 +1679,277 @@ class ConnectionHandler:
)
emotion_flag = False
- if content is not None and len(content) > 0:
- if not tool_call_flag:
- response_message.append(content)
- self.tts.tts_text_queue.put(
- TTSMessageDTO(
- sentence_id=self.sentence_id,
- sentence_type=SentenceType.MIDDLE,
- content_type=ContentType.TEXT,
- content_detail=content,
+
+ # STREAM TRIGGER HANDLING with BUFFERING
+ if content is not None and len(content) > 0 and not tool_call_flag:
+ # If we already executed a trigger, we suppress all subsequent output (assuming LLM complies with "ONLY output trigger")
+ if trigger_executed:
+ continue
+
+ stream_buffer += content
+
+ # Check if buffer *starts* with potential trigger marker "@@"
+ # We strip leading whitespace from buffer to be safe
+ buffer_stripped = stream_buffer.lstrip()
+
+ if buffer_stripped.startswith("@@"):
+ # We are potentially in a trigger. Hold output.
+ # Check if we have a full trigger
+ if "@@" in buffer_stripped[2:]: # Look for closing @@
+ # Full trigger found. Process it.
+ closing_index = buffer_stripped.find("@@", 2)
+ trigger_content = buffer_stripped[:closing_index+2]
+
+ # @@WEATHER@@
+ if "@@WEATHER@@" in trigger_content:
+ self.logger.bind(tag=TAG).info("Detected Stream Trigger: @@WEATHER@@")
+ trigger_executed = True
+ try:
+ w_res = get_weather(self, location=None)
+ w_text = w_res.response if w_res.response else w_res.result
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=w_text)
+ response_message.append(w_text)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Trigger execution failed: {e}")
+
+ # @@BATTERY@@
+ elif "@@BATTERY@@" in trigger_content:
+ self.logger.bind(tag=TAG).info("Detected Stream Trigger: @@BATTERY@@")
+ trigger_executed = True
+ try:
+ bat_level = self._get_battery_level()
+ b_text = f"The device battery level is {bat_level}%."
+ if bat_level == "unknown":
+ b_text = "I couldn't retrieve the battery level from the device."
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=b_text)
+ response_message.append(b_text)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Trigger execution failed: {e}")
+
+ # @@NEWS ...@@
+ elif "@@NEWS" in trigger_content:
+ self.logger.bind(tag=TAG).info(f"Detected Stream Trigger: NEWS")
+ trigger_executed = True
+ try:
+ match = re.search(r"@@NEWS[:\s]\s*(.*?)@@", trigger_content)
+ if match:
+ query = match.group(1).strip()
+ from core.utils.news_rag import news_rag as nr
+ n_text = nr.search(query)
+ if not n_text:
+ n_text = "I couldn't find any recent news on that topic."
+ else:
+ n_text = n_text.replace("---\nRELEVANT NEWS CONTEXT:\n", "").replace("\n---", "")
+ n_text = "Here is what I found in the news: " + n_text[:500]
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=n_text)
+ response_message.append(n_text)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Trigger execution failed: {e}")
+
+ # @@VOLUME ...@@
+ elif "@@VOLUME" in trigger_content:
+ self.logger.bind(tag=TAG).info(f"Detected Stream Trigger: VOLUME")
+ trigger_executed = True
+ try:
+ import re
+ match = re.search(r"@@VOLUME[:\s]\s*(\d+)@@", trigger_content)
+ if match:
+ vol = int(match.group(1))
+ # Send volume command to client using MCP protocol
+ payload = {
+ "jsonrpc": "2.0",
+ "method": "tools/call",
+ "params": {
+ "name": "self.audio_speaker.set_volume",
+ "arguments": {"volume": vol}
+ },
+ "id": int(time.time() * 1000)
+ }
+
+ # Use inline send to avoid library/attribute issues
+ # Protocol: {"type": "mcp", "payload": ...}
+
+ # Clamp volume to 0-100
+ vol = max(0, min(100, vol))
+ self.logger.bind(tag=TAG).info(f"Sending Volume MCP: {vol}")
+
+ message = json.dumps({"type": "mcp", "payload": payload})
+
+ if self.websocket:
+ asyncio.run_coroutine_threadsafe(
+ self.websocket.send(message),
+ self.loop
+ )
+
+ resp_text = f"Setting volume to {vol}%."
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=resp_text)
+ response_message.append(resp_text)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Trigger execution failed: {e}")
+
+ # @@EXIT@@
+ elif "@@EXIT@@" in trigger_content:
+ self.logger.bind(tag=TAG).info("Detected Stream Trigger: @@EXIT@@")
+ trigger_executed = True
+ self.close_after_chat = True
+ if not response_message:
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail="Goodbye!")
+ response_message.append("Goodbye!")
+
+ # [TOOL_CALL] - Web Search
+ elif "[TOOL_CALL]" in trigger_content:
+ self.logger.bind(tag=TAG).info("Detected Stream Trigger: [TOOL_CALL]")
+ trigger_executed = True
+ try:
+ # Extract JSON payload
+ # Format: [TOOL_CALL] { "tool": "google_search", "args": { "query": "..." } }
+ match = re.search(r"\[TOOL_CALL\]\s*(\{.*?\})", trigger_content)
+ if match:
+ json_str = match.group(1)
+ tool_data = json.loads(json_str)
+ tool_name = tool_data.get("tool")
+ args = tool_data.get("args", {})
+
+ if tool_name == "google_search":
+ query = args.get("query")
+ self.logger.bind(tag=TAG).info(f"Executing Web Search Tool: {query}")
+
+ # Speak loading message
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=f"Let me search specifically for {query}...")
+
+ # Execute Search
+ from core.utils.web_search import perform_web_search
+ results = perform_web_search(query, self.config)
+
+ if not results:
+ results = "No results found."
+
+ # Truncate results
+ if len(results) > 2000:
+ results = results[:2000] + "... [truncated]"
+
+ # RECURSIVE CALL: Feed results back to LLM
+ # We append the results as a "Function" or "System" message to history
+ # and call chat() again to get the final answer.
+
+ search_context = (
+ f"--- WEB SEARCH RESULTS for '{query}' ---\n"
+ f"{results}\n"
+ f"--- END RESULTS ---\n"
+ f"Instructions: Use the search results above to answer the user's question directly. "
+ f"Do not mention the tool call or the search process again. Just give the answer."
+ )
+
+ # Add to history
+ self.dialogue.put(Message(role="system", content=search_context))
+
+ # Recurse!
+ # Important: Increment depth to prevent infinite loops logic (though we handle it)
+ self.chat(query="[System: results injected, please answer]", depth=depth+1)
+ return # End this level of recursion, the child call handles the rest
+
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Tool execution failed: {e}")
+ self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail="I tried to search but something went wrong.")
+
+ else:
+ # Unknown tag
+ self.logger.bind(tag=TAG).warning(f"Unknown trigger detected and ignored: {trigger_content}")
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.MIDDLE,
+ content_type=ContentType.TEXT,
+ content_detail=stream_buffer,
+ )
+ )
+ response_message.append(stream_buffer)
+ stream_buffer = ""
+
+ if trigger_executed:
+ stream_buffer = ""
+ else:
+ stream_buffer = ""
+
+ else:
+ # Starts with @@ but no closing @@ yet. Wait.
+ pass
+
+ elif "@" in buffer_stripped and len(buffer_stripped) < 5:
+ # Could be start of @@. Hold briefly.
+ # e.g. "@" -> hold. "@@" -> move to startswith block.
+ # "Email@" -> "@" in... but "Email@" doesn't start with @
+ # We check `buffer_stripped` length. If it's short and contains @, we hold just in case.
+ # If user says "My email is foo@bar", buffer "My email is foo@bar" > 5.
+ # But at the start: "My" -> flush.
+ # So this logic only holds if valid Text starts with @.
+ pass
+
+ else:
+ # --- Garbage Filter for TTS ---
+ # If we detect tool call markup or start of JSON, we stop TTS for this response
+ # Also blocking web search tags
+ block_tags = ["[TOOL_CALL]", "", "{ \"tool\"", "```json", "", "", ""]
+ if self.suppress_tts:
+ stream_buffer = ""
+ continue
+
+ # --- Safety Buffer for Fragments ---
+ # Check if buffer ends with a potential start of a tag or markdown
+ # Capture unclosed tags: [ start, then non-] chars until end
+ # Capture unclosed markdown: ** start, then non-* chars until end
+ import re
+ partial_match = re.search(r'([<\[\{][^>\]\}]*|(?:\*\*|__)[^*_]*)$', stream_buffer)
+
+ safe_content = stream_buffer
+ kept_suffix = ""
+
+ if partial_match:
+ # If we have a potential start, hold it back
+ kept_suffix = partial_match.group(1)
+ safe_content = stream_buffer[:-len(kept_suffix)]
+ # If we end up holding everything, update buffer and continue
+ if not safe_content:
+ stream_buffer = kept_suffix
+ continue
+
+ # Check for complete tags inside the safe content
+ block_tags = ["[TOOL_CALL]", "", "{ \"tool\"", "```json", "", "", ""]
+ if any(tag in safe_content for tag in block_tags):
+ self.logger.bind(tag=TAG).info(f"Purging tool-call garbage: {safe_content[:50]}...")
+ self.suppress_tts = True
+ stream_buffer = ""
+ continue
+
+ # --- Markdown Cleaner ---
+ # 1. Links [text](url) -> text
+ safe_content = re.sub(r'\[([^\]]+)\]\([^)]+\)', r'\1', safe_content)
+ # 2. Bold/Italic (** or __) -> text
+ safe_content = re.sub(r'(\*\*|__)(.*?)\1', r'\2', safe_content)
+ # 3. Headers (## ) -> empty (or text)
+ safe_content = re.sub(r'^#+\s+', '', safe_content)
+
+ if safe_content:
+ self.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=self.sentence_id,
+ sentence_type=SentenceType.MIDDLE,
+ content_type=ContentType.TEXT,
+ content_detail=safe_content,
+ )
)
- )
- # 处理function call
+ response_message.append(safe_content)
+
+ # Keep the dangerous suffix for the next chunk
+ stream_buffer = kept_suffix
+
+
+ # End of loop body
+
+ # Handle function call
if tool_call_flag:
bHasError = False
- # 处理基于文本的工具调用格式
+ # Handle text-based tool call format
if len(tool_calls_list) == 0 and content_arguments:
a = extract_json_from_string(content_arguments)
if a is not None:
@@ -940,7 +1977,7 @@ class ConnectionHandler:
)
if not bHasError and len(tool_calls_list) > 0:
- # 如需要大模型先处理一轮,添加相关处理后的日志情况
+ # If LLM needs to process a round first, add related processing logs
if len(response_message) > 0:
text_buff = "".join(response_message)
self.tts_MessageText = text_buff
@@ -948,10 +1985,10 @@ class ConnectionHandler:
response_message.clear()
self.logger.bind(tag=TAG).debug(
- f"检测到 {len(tool_calls_list)} 个工具调用"
+ f"Detected {len(tool_calls_list)} tool calls"
)
- # 收集所有工具调用的 Future
+ # Collect all tool call Futures
futures_with_data = []
for tool_call_data in tool_calls_list:
self.logger.bind(tag=TAG).debug(
@@ -966,21 +2003,40 @@ class ConnectionHandler:
)
futures_with_data.append((future, tool_call_data))
- # 等待协程结束(实际等待时长为最慢的那个)
+ # Wait for coroutines to finish (actual wait time is the slowest one)
tool_results = []
for future, tool_call_data in futures_with_data:
result = future.result()
tool_results.append((result, tool_call_data))
- # 统一处理所有工具调用结果
+ # Unified handling of all tool call results
if tool_results:
self._handle_function_result(tool_results, depth=depth)
- # 存储对话内容
+ # Store dialogue content
if len(response_message) > 0:
text_buff = "".join(response_message)
self.tts_MessageText = text_buff
self.dialogue.put(Message(role="assistant", content=text_buff))
+
+ # Send full LLM text to client for on-screen display.
+ # This arrives while TTS audio is still being synthesized/played,
+ # allowing the device to show the complete response text immediately.
+ if depth == 0:
+ try:
+ display_text = textUtils.check_emoji(text_buff)
+ asyncio.run_coroutine_threadsafe(
+ self.websocket.send(json.dumps({
+ "type": "tts",
+ "state": "sentence_start",
+ "text": display_text,
+ "session_id": self.session_id,
+ })),
+ self.loop,
+ )
+ except Exception as e:
+ self.logger.bind(tag=TAG).warning(f"Failed to send LLM text to client: {e}")
+
if depth == 0:
self.tts.tts_text_queue.put(
TTSMessageDTO(
@@ -990,7 +2046,7 @@ class ConnectionHandler:
)
)
self.llm_finish_task = True
- # 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
+ # Use lambda for lazy evaluation, execute get_llm_dialogue() only at DEBUG level
self.logger.bind(tag=TAG).debug(
lambda: json.dumps(
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
@@ -1007,12 +2063,12 @@ class ConnectionHandler:
Action.RESPONSE,
Action.NOTFOUND,
Action.ERROR,
- ]: # 直接回复前端
+ ]: # Direct reply to frontend
text = result.response if result.response else result.result
self.tts.tts_one_sentence(self, ContentType.TEXT, content_detail=text)
self.dialogue.put(Message(role="assistant", content=text))
elif result.action == Action.REQLLM:
- # 收集需要 LLM 处理的工具
+ # Collect tools needing LLM processing
need_llm_tools.append((result, tool_call_data))
else:
pass
@@ -1054,51 +2110,232 @@ class ConnectionHandler:
self.chat(None, depth=depth + 1)
def _report_worker(self):
- """聊天记录上报工作线程"""
+ """Chat history report worker thread"""
while not self.stop_event.is_set():
try:
- # 从队列获取数据,设置超时以便定期检查停止事件
+ # Get data from queue, set timeout to check stop event regularly
item = self.report_queue.get(timeout=1)
- if item is None: # 检测毒丸对象
+ if item is None: # Check for poison pill
break
try:
- # 检查线程池状态
+ # Check thread pool status
if self.executor is None:
continue
- # 提交任务到线程池
+ # Submit task to thread pool
self.executor.submit(self._process_report, *item)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
+ self.logger.bind(tag=TAG).error(f"Chat history report thread exception: {e}")
except queue.Empty:
continue
except Exception as e:
- self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
+ self.logger.bind(tag=TAG).error(f"Chat history report worker thread exception: {e}")
- self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
+ self.logger.bind(tag=TAG).info("Chat history report thread exited")
def _process_report(self, type, text, audio_data, report_time):
- """处理上报任务"""
+ """Handle report task"""
try:
- # 执行异步上报(在事件循环中运行)
+ # Execute async report (run in event loop)
asyncio.run(report(self, type, text, audio_data, report_time))
except Exception as e:
- self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
+ self.logger.bind(tag=TAG).error(f"Report handling exception: {e}")
finally:
- # 标记任务完成
+ # Mark task as done
self.report_queue.task_done()
def clearSpeakStatus(self):
self.client_is_speaking = False
- self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
+ self.logger.bind(tag=TAG).debug(f"Clear server speaking status")
+
+ def save_session_memory(self):
+ """Save current session dialogue to local JSON memory"""
+ try:
+ # Determine Client ID
+ client_id = None
+ if self.headers:
+ client_id = self.headers.get("client-id")
+ if not client_id and hasattr(self, "device_id"):
+ client_id = self.device_id
+
+ if not client_id:
+ return
+
+ memory_dir = os.path.join("data", client_id)
+ if not os.path.exists(memory_dir):
+ os.makedirs(memory_dir, exist_ok=True)
+
+ memory_file = os.path.join(memory_dir, "memory.json")
+
+ # Serialize dialogue
+ messages = []
+ if hasattr(self.dialogue, "dialogue"):
+ for msg in self.dialogue.dialogue:
+ # Basic serialization
+ m_dict = {
+ "role": msg.role,
+ "content": msg.content
+ }
+ # Handle tool calls if present (simple serialization to avoid JSON errors)
+ if msg.tool_calls:
+ try:
+ # Attempt to convert to dict/list if possible, else str
+ if hasattr(msg.tool_calls, "to_dict"):
+ m_dict["tool_calls"] = msg.tool_calls.to_dict()
+ elif isinstance(msg.tool_calls, (list, dict)):
+ m_dict["tool_calls"] = msg.tool_calls
+ else:
+ m_dict["tool_calls"] = str(msg.tool_calls)
+ except:
+ m_dict["tool_calls"] = str(msg.tool_calls)
+
+ if msg.tool_call_id:
+ m_dict["tool_call_id"] = msg.tool_call_id
+
+ messages.append(m_dict)
+
+ if not messages:
+ return
+
+ session_data = {
+ "session_id": getattr(self, "session_id", str(uuid.uuid4().hex)),
+ "timestamp": datetime.now().isoformat(),
+ "messages": messages
+ }
+
+ # Load existing history
+ history = []
+ if os.path.exists(memory_file):
+ try:
+ with open(memory_file, "r", encoding="utf-8") as f:
+ history = json.load(f)
+ if not isinstance(history, list):
+ history = []
+ except Exception as e:
+ self.logger.bind(tag=TAG).warning(f"Failed to load existing memory json: {e}")
+ history = []
+
+ # Append new session
+ history.append(session_data)
+
+ # Save back
+ with open(memory_file, "w", encoding="utf-8") as f:
+ json.dump(history, f, ensure_ascii=False, indent=2)
+
+ self.logger.bind(tag=TAG).info(f"Session memory saved to {memory_file}")
+
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to save session memory: {e}")
+
+ def summarize_session(self):
+ """Summarize current session and update local summary file"""
+ try:
+ # 1. Check prerequisites
+ if not getattr(self, "client_id", None):
+ if self.headers:
+ self.client_id = self.headers.get("client-id")
+ if not getattr(self, "client_id", None) and hasattr(self, "device_id"):
+ self.client_id = self.device_id
+
+ if not self.client_id:
+ return
+
+ if not hasattr(self, "llm") or not self.llm:
+ return
+
+ # Avoid summarizing short conversations
+ if not hasattr(self.dialogue, "dialogue") or len(self.dialogue.dialogue) < 4:
+ return
+
+ memory_dir = os.path.join("data", self.client_id)
+ if not os.path.exists(memory_dir):
+ os.makedirs(memory_dir, exist_ok=True)
+ summary_file = os.path.join(memory_dir, "summary.txt")
+
+ # 2. Get existing summary
+ existing_summary = ""
+ if os.path.exists(summary_file):
+ try:
+ with open(summary_file, "r", encoding="utf-8") as f:
+ existing_summary = f.read().strip()
+ existing_summary = self._filter_stale_realtime_summary_lines(existing_summary)
+ except Exception as e:
+ self.logger.bind(tag=TAG).warning(f"Failed to read summary file: {e}")
+
+ # 3. Format current dialogue
+ new_dialogue_text = ""
+ for msg in self.dialogue.dialogue:
+ if msg.role in ["user", "assistant"] and msg.content:
+ new_dialogue_text += f"{msg.role}: {msg.content}\n"
+
+ if not new_dialogue_text:
+ return
+
+ # 4. Prompt LLM
+ prompt = (
+ "You are a memory manager maintaining long-term memory about a user.\n"
+ "Only store durable, stable information such as user preferences, habits, identity, and long-term context.\n"
+ "Do NOT store real-time or frequently changing data.\n"
+ "Specifically, NEVER store medical/device state such as: CGM values, glucose trends, Time in Range (TIR), GMI, mean glucose, pump events, boluses, basal rates, or sync-status statements.\n"
+ "All real-time health/device data must come from live system context (CSV/API), NOT memory.\n"
+ "Keep the summary concise and factual. Do not include timestamps, temporary observations, or conversational filler.\n\n"
+ )
+
+ if existing_summary:
+ prompt += f"EXISTING SUMMARY:\n{existing_summary}\n\n"
+
+ prompt += (
+ f"NEW CONVERSATION:\n{new_dialogue_text}\n\n"
+ "TASK: Update the summary using ONLY durable information from this conversation. "
+ "Do NOT include any real-time glucose, insulin, CGM, or pump-related values or interpretations. "
+ "If the new conversation only contains temporary or real-time data, do NOT modify the summary. "
+ "Return the existing summary unchanged in that case."
+ )
+
+ self.logger.bind(tag=TAG).info("Generating session summary...")
+
+ # Use response_no_stream for single-turn generation
+ # Ensure timeout is handled by LLM provider config
+ # Use response_no_stream for single-turn generation
+ # Ensure timeout is handled by LLM provider config
+ new_summary = self.llm.response_no_stream(
+ system_prompt="You are a memory manager.",
+ user_prompt=prompt,
+ max_tokens=1000,
+ temperature=0.3
+ )
+
+ # 5. Save updated summary
+ if new_summary and "[LLM Service Response Error]" not in new_summary and len(new_summary.strip()) > 0:
+ with open(summary_file, "w", encoding="utf-8") as f:
+ f.write(new_summary.strip())
+ self.logger.bind(tag=TAG).info(f"Updated summary saved to {summary_file}")
+ else:
+ self.logger.bind(tag=TAG).warning(f"Summary generation failed or empty. Result: {new_summary}")
+
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to summarize session: {e}")
async def close(self, ws=None):
- """资源清理方法"""
+ """Resource cleanup method"""
try:
- # 清理音频缓冲区
+ # Save session memory before closing
+ self.save_session_memory()
+
+ # Generate summary before closing (if not terminating due to error)
+ # Run in executor to avoid blocking main loop validation if possible,
+ # but close() is async, so we'll just run it.
+ # Note: response_no_stream might block if not truly async, but we are closing anyway.
+ # Ideally wrap in run_in_executor
+ try:
+ await self.loop.run_in_executor(None, self.summarize_session)
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Async summary generation failed: {e}")
+
+ # Clear audio buffer
if hasattr(self, "audio_buffer"):
self.audio_buffer.clear()
- # 取消超时任务
+ # Cancel timeout task
if self.timeout_task and not self.timeout_task.done():
self.timeout_task.cancel()
try:
@@ -1107,36 +2344,36 @@ class ConnectionHandler:
pass
self.timeout_task = None
- # 清理工具处理器资源
+ # Clear tool handler resources
if hasattr(self, "func_handler") and self.func_handler:
try:
await self.func_handler.cleanup()
except Exception as cleanup_error:
self.logger.bind(tag=TAG).error(
- f"清理工具处理器时出错: {cleanup_error}"
+ f"Error cleaning up tool handler: {cleanup_error}"
)
- # 触发停止事件
+ # Trigger stop event
if self.stop_event:
self.stop_event.set()
- # 清空任务队列
+ # Clear task queues
self.clear_queues()
- # 关闭WebSocket连接
+ # Close WebSocket connection
try:
if ws:
- # 安全地检查WebSocket状态并关闭
+ # Safely check WebSocket state and close
try:
if hasattr(ws, "closed") and not ws.closed:
await ws.close()
elif hasattr(ws, "state") and ws.state.name != "CLOSED":
await ws.close()
else:
- # 如果没有closed属性,直接尝试关闭
+ # If no closed attribute, try to close directly
await ws.close()
except Exception:
- # 如果关闭失败,忽略错误
+ # Ignore error if close fails
pass
elif self.websocket:
try:
@@ -1151,42 +2388,42 @@ class ConnectionHandler:
):
await self.websocket.close()
else:
- # 如果没有closed属性,直接尝试关闭
+ # If no closed attribute, try to close directly
await self.websocket.close()
except Exception:
- # 如果关闭失败,忽略错误
+ # Ignore error if close fails
pass
except Exception as ws_error:
- self.logger.bind(tag=TAG).error(f"关闭WebSocket连接时出错: {ws_error}")
+ self.logger.bind(tag=TAG).error(f"Error closing WebSocket connection: {ws_error}")
if self.tts:
await self.tts.close()
- # 最后关闭线程池(避免阻塞)
+ # Finally close thread pool (avoid blocking)
if self.executor:
try:
self.executor.shutdown(wait=False)
except Exception as executor_error:
self.logger.bind(tag=TAG).error(
- f"关闭线程池时出错: {executor_error}"
+ f"Error closing thread pool: {executor_error}"
)
self.executor = None
- self.logger.bind(tag=TAG).info("连接资源已释放")
+ self.logger.bind(tag=TAG).info("Connection resources released")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
+ self.logger.bind(tag=TAG).error(f"Error closing connection: {e}")
finally:
- # 确保停止事件被设置
+ # Ensure stop event is set
if self.stop_event:
self.stop_event.set()
def clear_queues(self):
- """清空所有任务队列"""
+ """Clear all task queues"""
if self.tts:
self.logger.bind(tag=TAG).debug(
- f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
+ f"Start cleanup: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}"
)
- # 使用非阻塞方式清空队列
+ # Clear queue in non-blocking way
for q in [
self.tts.tts_text_queue,
self.tts.tts_audio_queue,
@@ -1200,13 +2437,13 @@ class ConnectionHandler:
except queue.Empty:
break
- # 重置音频流控器(取消后台任务并清空队列)
+ # Reset audio rate controller (cancel background tasks and clear queue)
if hasattr(self, "audio_rate_controller") and self.audio_rate_controller:
self.audio_rate_controller.reset()
- self.logger.bind(tag=TAG).debug("已重置音频流控器")
+ self.logger.bind(tag=TAG).debug("Audio rate controller reset")
self.logger.bind(tag=TAG).debug(
- f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
+ f"Cleanup finished: TTS queue size={self.tts.tts_text_queue.qsize()}, audio queue size={self.tts.tts_audio_queue.qsize()}"
)
def reset_vad_states(self):
@@ -1227,57 +2464,57 @@ class ConnectionHandler:
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
async def _check_timeout(self):
- """检查连接超时"""
+ """Check connection timeout"""
try:
while not self.stop_event.is_set():
last_activity_time = self.last_activity_time
if self.need_bind:
last_activity_time = self.first_activity_time
- # 检查是否超时(只有在时间戳已初始化的情况下)
+ # Check for timeout (only if timestamp is initialized)
if last_activity_time > 0.0:
current_time = time.time() * 1000
if current_time - last_activity_time > self.timeout_seconds * 1000:
if not self.stop_event.is_set():
- self.logger.bind(tag=TAG).info("连接超时,准备关闭")
- # 设置停止事件,防止重复处理
+ self.logger.bind(tag=TAG).info("Connection timed out, preparing to close")
+ # Set stop event to prevent duplicate processing
self.stop_event.set()
- # 使用 try-except 包装关闭操作,确保不会因为异常而阻塞
+ # Wrap close operation with try-except to ensure it doesn't block due to exception
try:
await self.close(self.websocket)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
- f"超时关闭连接时出错: {close_error}"
+ f"Error closing connection due to timeout: {close_error}"
)
break
- # 每10秒检查一次,避免过于频繁
+ # Check every 10 seconds to avoid being too frequent
await asyncio.sleep(10)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
+ self.logger.bind(tag=TAG).error(f"Timeout check task error: {e}")
finally:
- self.logger.bind(tag=TAG).info("超时检查任务已退出")
+ self.logger.bind(tag=TAG).info("Timeout check task exited")
def _merge_tool_calls(self, tool_calls_list, tools_call):
- """合并工具调用列表
+ """Merge tool call list
Args:
- tool_calls_list: 已收集的工具调用列表
- tools_call: 新的工具调用
+ tool_calls_list: Collected tool call list
+ tools_call: New tool call
"""
for tool_call in tools_call:
tool_index = getattr(tool_call, "index", None)
if tool_index is None:
if tool_call.function.name:
- # 有 function_name,说明是新的工具调用
+ # Has function_name, indicating new tool call
tool_index = len(tool_calls_list)
else:
tool_index = len(tool_calls_list) - 1 if tool_calls_list else 0
- # 确保列表有足够的位置
+ # Ensure list has enough space
if tool_index >= len(tool_calls_list):
tool_calls_list.append({"id": "", "name": "", "arguments": ""})
- # 更新工具调用信息
+ # Update tool call info
if tool_call.id:
tool_calls_list[tool_index]["id"] = tool_call.id
if tool_call.function.name:
diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py
index 129b0aa79..f68e58166 100644
--- a/main/xiaozhi-server/core/handle/helloHandle.py
+++ b/main/xiaozhi-server/core/handle/helloHandle.py
@@ -9,65 +9,82 @@ from core.providers.tts.dto.dto import SentenceType
from core.utils.wakeup_word import WakeupWordsConfig
from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message
from core.utils.util import remove_punctuation_and_length, opus_datas_to_wav_bytes
-from core.providers.tools.device_mcp import (
- MCPClient,
- send_mcp_initialize_message,
- send_mcp_tools_list_request,
-)
TAG = __name__
WAKEUP_CONFIG = {
"refresh_time": 10,
"responses": [
- "我一直都在呢,您请说。",
- "在的呢,请随时吩咐我。",
- "来啦来啦,请告诉我吧。",
- "您请说,我正听着。",
- "请您讲话,我准备好了。",
- "请您说出指令吧。",
- "我认真听着呢,请讲。",
- "请问您需要什么帮助?",
- "我在这里,等候您的指令。",
+ "I'm here, go ahead.",
+ "I'm listening, how can I help?",
+ "Ready for your command.",
+ "I'm right here.",
+ "Yes? I'm listening.",
+ "Tell me what you need.",
+ "Ready when you are.",
+ "How can I assist you?",
+ "Awaiting your instructions.",
],
}
-# 创建全局的唤醒词配置管理器
+# Global wakeup words config manager
wakeup_words_config = WakeupWordsConfig()
-# 用于防止并发调用wakeupWordsResponse的锁
+# Lock to prevent concurrent calls to wakeupWordsResponse
_wakeup_response_lock = asyncio.Lock()
async def handleHelloMessage(conn, msg_json):
- """处理hello消息"""
+ """Protocol-compliant handshake for XiaoZhi firmware"""
+
+ # 1. Update session-specific audio params
audio_params = msg_json.get("audio_params")
if audio_params:
- format = audio_params.get("format")
- conn.logger.bind(tag=TAG).debug(f"客户端音频格式: {format}")
- conn.audio_format = format
- conn.welcome_msg["audio_params"] = audio_params
- features = msg_json.get("features")
- if features:
- conn.logger.bind(tag=TAG).debug(f"客户端特性: {features}")
- conn.features = features
- if features.get("mcp"):
- conn.logger.bind(tag=TAG).debug("客户端支持MCP")
- conn.mcp_client = MCPClient()
- # 发送初始化
- asyncio.create_task(send_mcp_initialize_message(conn))
- # 发送mcp消息,获取tools列表
- asyncio.create_task(send_mcp_tools_list_request(conn))
+ conn.audio_format = audio_params.get("format")
+
+ # 2. Assign features (Setting mcp to False in the response tells the
+ # firmware not to wait for further MCP packets during the handshake)
+ features = msg_json.get("features", {})
+ conn.features = features
- await conn.websocket.send(json.dumps(conn.welcome_msg))
+ # 3. Generate a Session ID
+ session_id = str(uuid.uuid4().hex)
+ conn.session_id = session_id
+
+ # 4. Construct protocol response
+ response = {
+ "type": "hello",
+ "version": msg_json.get("version", 1),
+ "transport": msg_json.get("transport", "websocket"),
+ "auth_key": conn.config["xiaozhi"]["auth_key"],
+ "session_id": session_id,
+ "message": "success",
+ # Force MCP enabled to ensure client listeners are active
+ "features": {**features, "mcp": True},
+ "audio_params": {
+ "format": "opus",
+ "sample_rate": 16000,
+ "channels": 1,
+ "frame_duration": 60
+ }
+ }
+
+ # 5. Brief pause to ensure network buffers are ready
+ await asyncio.sleep(0.1)
+
+ # 6. Send and Log exactly what was sent
+ resp_json = json.dumps(response)
+ await conn.websocket.send(resp_json)
+ conn.logger.bind(tag=TAG).info(f"Handshake mirrored: {resp_json}")
async def checkWakeupWords(conn, text):
- enable_wakeup_words_response_cache = conn.config[
- "enable_wakeup_words_response_cache"
- ]
+ """Check if the transcribed text matches any wakeup words"""
+ enable_wakeup_words_response_cache = conn.config.get(
+ "enable_wakeup_words_response_cache", False
+ )
- # 等待tts初始化,最多等待3秒
+ # Wait for TTS initialization (max 3 seconds)
start_time = time.time()
while time.time() - start_time < 3:
if conn.tts:
@@ -80,43 +97,38 @@ async def checkWakeupWords(conn, text):
return False
_, filtered_text = remove_punctuation_and_length(text)
- if filtered_text not in conn.config.get("wakeup_words"):
+ if filtered_text not in conn.config.get("wakeup_words", []):
return False
conn.just_woken_up = True
await send_tts_message(conn, "start")
- # 获取当前音色
- voice = getattr(conn.tts, "voice", "default")
- if not voice:
- voice = "default"
+ voice = getattr(conn.tts, "voice", "default") or "default"
- # 获取唤醒词回复配置
response = wakeup_words_config.get_wakeup_response(voice)
if not response or not response.get("file_path"):
response = {
"voice": "default",
"file_path": "config/assets/wakeup_words_short.wav",
"time": 0,
- "text": "我在这里哦!",
+ "text": "I'm here!",
}
- # 获取音频数据
+ # Get audio data
opus_packets = await audio_to_data(response.get("file_path"), use_cache=False)
- # 播放唤醒词回复
conn.client_abort = False
- # 将唤醒词回复视为新会话,生成新的 sentence_id,确保流控器重置
+ # Treat wakeup as a new session
conn.sentence_id = str(uuid.uuid4().hex)
- conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
+ conn.logger.bind(tag=TAG).info(f"Playing wakeup response: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)
- # 补充对话
+ # Append to dialogue
conn.dialogue.put(Message(role="assistant", content=response.get("text")))
- # 检查是否需要更新唤醒词回复
+ # Check if we need to refresh the cached response
if time.time() - response.get("time", 0) > WAKEUP_CONFIG["refresh_time"]:
if not _wakeup_response_lock.locked():
asyncio.create_task(wakeupWordsResponse(conn))
@@ -124,34 +136,32 @@ async def checkWakeupWords(conn, text):
async def wakeupWordsResponse(conn):
+ """Generate and cache a new random wakeup response"""
if not conn.tts:
return
try:
- # 尝试获取锁,如果获取不到就返回
if not await _wakeup_response_lock.acquire():
return
- # 从预定义回复列表中随机选择一个回复
result = random.choice(WAKEUP_CONFIG["responses"])
- if not result or len(result) == 0:
+ if not result:
return
- # 生成TTS音频
+ # Generate TTS audio in thread
tts_result = await asyncio.to_thread(conn.tts.to_tts, result)
if not tts_result:
return
- # 获取当前音色
voice = getattr(conn.tts, "voice", "default")
-
wav_bytes = opus_datas_to_wav_bytes(tts_result, sample_rate=16000)
file_path = wakeup_words_config.generate_file_path(voice)
+
with open(file_path, "wb") as f:
f.write(wav_bytes)
- # 更新配置
+
wakeup_words_config.update_wakeup_response(voice, file_path, result)
finally:
- # 确保在任何情况下都释放锁
if _wakeup_response_lock.locked():
_wakeup_response_lock.release()
+
diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index 402a23a9f..277d6a429 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -7,85 +7,84 @@ from core.handle.helloHandle import checkWakeupWords
from plugins_func.register import Action, ActionResponse
from core.handle.sendAudioHandle import send_stt_message
from core.utils.util import remove_punctuation_and_length
+from core.utils.exit_handler import is_exit_command, handle_exit
from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
TAG = __name__
async def handle_user_intent(conn, text):
- # 预处理输入文本,处理可能的JSON格式
+ # Preprocess input text, handle potential JSON format
try:
if text.strip().startswith('{') and text.strip().endswith('}'):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
- text = parsed_data["content"] # 提取content用于意图分析
- conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息
+ text = parsed_data["content"] # Extract content for intent analysis
+ conn.current_speaker = parsed_data.get("speaker") # Keep speaker info
except (json.JSONDecodeError, TypeError):
pass
- # 检查是否有明确的退出命令
+ # Check for direct exit command
_, filtered_text = remove_punctuation_and_length(text)
if await check_direct_exit(conn, filtered_text):
return True
- # 检查是否是唤醒词
+ # Check for wake word
if await checkWakeupWords(conn, filtered_text):
return True
if conn.intent_type == "function_call":
- # 使用支持function calling的聊天方法,不再进行意图分析
+ # Use chat method supporting function calling, skip intent analysis
return False
- # 使用LLM进行意图分析
+ # Use LLM for intent analysis
intent_result = await analyze_intent_with_llm(conn, text)
if not intent_result:
return False
- # 会话开始时生成sentence_id
+ # Generate sentence_id at session start
conn.sentence_id = str(uuid.uuid4().hex)
- # 处理各种意图
+ # Handle various intents
return await process_intent_result(conn, intent_result, text)
async def check_direct_exit(conn, text):
- """检查是否有明确的退出命令"""
+ """Check for explicit exit command"""
_, text = remove_punctuation_and_length(text)
- cmd_exit = conn.cmd_exit
- for cmd in cmd_exit:
- if text == cmd:
- conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
- await send_stt_message(conn, text)
- await conn.close()
- return True
+ if is_exit_command(text, conn.cmd_exit):
+ conn.logger.bind(tag=TAG).info(f"Detected explicit exit command: {text}")
+ await send_stt_message(conn, text)
+ handle_exit(conn)
+ return True
return False
async def analyze_intent_with_llm(conn, text):
- """使用LLM分析用户意图"""
+ """Analyze user intent with LLM"""
if not hasattr(conn, "intent") or not conn.intent:
- conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
+ conn.logger.bind(tag=TAG).warning("Intent service not initialized")
return None
- # 对话历史记录
+ # Dialogue history
dialogue = conn.dialogue
try:
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result
except Exception as e:
- conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
+ conn.logger.bind(tag=TAG).error(f"Intent recognition failed: {str(e)}")
return None
async def process_intent_result(conn, intent_result, original_text):
- """处理意图识别结果"""
+ """Process intent recognition result"""
try:
- # 尝试将结果解析为JSON
+ # Try to parse result as JSON
intent_data = json.loads(intent_result)
- # 检查是否有function_call
+ # Check for function_call
if "function_call" in intent_data:
- # 直接从意图识别获取了function_call
+ # Got function_call directly from intent
conn.logger.bind(tag=TAG).debug(
- f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}"
+ f"Detected function_call intent format: {intent_data['function_call']['name']}"
)
function_name = intent_data["function_call"]["name"]
if function_name == "continue_chat":
@@ -102,12 +101,16 @@ async def process_intent_result(conn, intent_result, original_text):
current_time, today_date, today_weekday, lunar_date = get_current_time_info()
- # 构建带上下文的基础提示
- context_prompt = f"""当前时间:{current_time}
- 今天日期:{today_date} ({today_weekday})
- 今天农历:{lunar_date}
+ # Build base prompt with context
+ # Prepend current system prompt (persona) if available
+ base_system = conn.prompt if hasattr(conn, "prompt") and conn.prompt else ""
+
+ context_prompt = f"""{base_system}
+ Current Time: {current_time}
+ Date: {today_date} ({today_weekday})
+ Lunar Date: {lunar_date}
- 请根据以上信息回答用户的问题:{original_text}"""
+ Please answer the user's question based on the above information: {original_text}"""
response = conn.intent.replyResult(context_prompt, original_text)
speak_txt(conn, response)
@@ -120,7 +123,7 @@ async def process_intent_result(conn, intent_result, original_text):
function_args = intent_data["function_call"]["arguments"]
if function_args is None:
function_args = {}
- # 确保参数是字符串格式的JSON
+ # Ensure args are JSON string
if isinstance(function_args, dict):
function_args = json.dumps(function_args)
@@ -133,11 +136,11 @@ async def process_intent_result(conn, intent_result, original_text):
await send_stt_message(conn, original_text)
conn.client_abort = False
- # 使用executor执行函数调用和结果处理
+ # Use executor to handle tool call and result processing
def process_function_call():
conn.dialogue.put(Message(role="user", content=original_text))
- # 使用统一工具处理器处理所有工具调用
+ # Use unified tool handler
try:
result = asyncio.run_coroutine_threadsafe(
conn.func_handler.handle_llm_function_call(
@@ -158,6 +161,7 @@ async def process_intent_result(conn, intent_result, original_text):
speak_txt(conn, text)
elif result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
text = result.result
+ conn.logger.bind(tag=TAG).info(f"Tool output for LLM generation: {text}")
conn.dialogue.put(Message(role="tool", content=text))
llm_result = conn.intent.replyResult(text, original_text)
if llm_result is None:
@@ -167,7 +171,9 @@ async def process_intent_result(conn, intent_result, original_text):
result.action == Action.NOTFOUND
or result.action == Action.ERROR
):
- text = result.result
+ text = result.response
+ if not text:
+ text = result.result
if text is not None:
speak_txt(conn, text)
elif function_name != "play_music":
@@ -179,17 +185,17 @@ async def process_intent_result(conn, intent_result, original_text):
if text is not None:
speak_txt(conn, text)
- # 将函数执行放在线程池中
+ # Execute function in thread pool
conn.executor.submit(process_function_call)
return True
return False
except json.JSONDecodeError as e:
- conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
+ conn.logger.bind(tag=TAG).error(f"Error processing intent result: {e}")
return False
def speak_txt(conn, text):
- # 记录文本
+ # Log text
conn.tts_MessageText = text
conn.tts.tts_text_queue.put(
diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
index ec1d3bc71..06ac87787 100644
--- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
@@ -37,7 +37,7 @@ async def resume_vad_detection(conn):
conn.just_woken_up = False
-async def startToChat(conn, text):
+async def startToChat(conn, text, audio_data=None):
# 检查输入是否是JSON格式(包含说话人信息)
speaker_name = None
language_tag = None
@@ -94,13 +94,19 @@ async def startToChat(conn, text):
# 意图未被处理,继续常规聊天流程,使用实际文本内容
await send_stt_message(conn, actual_text)
- conn.executor.submit(conn.chat, actual_text)
+ conn.executor.submit(conn.chat, actual_text, audio_data=audio_data)
async def no_voice_close_connect(conn, have_voice):
if have_voice:
conn.last_activity_time = time.time() * 1000
return
+
+ # Prevent idle timeout while LLM is actively thinking/speaking
+ if hasattr(conn, "llm_finish_task") and not conn.llm_finish_task:
+ conn.last_activity_time = time.time() * 1000
+ return
+
# 只有在已经初始化过时间戳的情况下才进行超时检查
if conn.last_activity_time > 0.0:
no_voice_time = time.time() * 1000 - conn.last_activity_time
@@ -115,12 +121,12 @@ async def no_voice_close_connect(conn, have_voice):
conn.client_abort = False
end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False:
- conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语")
+ conn.logger.bind(tag=TAG).info("Closing connection due to inactivity.")
await conn.close()
return
prompt = end_prompt.get("prompt")
if not prompt:
- prompt = "请你以```时间过得真快```未来头,用富有感情、依依不舍的话来结束这场对话吧。!"
+ prompt = "Please provide a very short, polite goodbye in the user's language to end the conversation since it has been idle."
await startToChat(conn, prompt)
diff --git a/main/xiaozhi-server/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py
index 323056d14..2f9fd8423 100644
--- a/main/xiaozhi-server/core/handle/sendAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/sendAudioHandle.py
@@ -7,20 +7,20 @@ from core.providers.tts.dto.dto import SentenceType
from core.utils.audioRateController import AudioRateController
TAG = __name__
-# 音频帧时长(毫秒)
+# Audio frame duration (ms)
AUDIO_FRAME_DURATION = 60
-# 预缓冲包数量,直接发送以减少延迟
+# Pre-buffer count, send directly to reduce latency
PRE_BUFFER_COUNT = 5
async def sendAudioMessage(conn, sentenceType, audios, text):
if conn.tts.tts_audio_first_sentence:
- conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
+ conn.logger.bind(tag=TAG).info(f"Sending first audio segment: {text}")
conn.tts.tts_audio_first_sentence = False
await send_tts_message(conn, "start", None)
if sentenceType == SentenceType.FIRST:
- # 同一句子的后续消息加入流控队列,其他情况立即发送
+ # Subsequent messages for the same sentence join the flow control queue, others send immediately
if (
hasattr(conn, "audio_rate_controller")
and conn.audio_rate_controller
@@ -31,15 +31,15 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
lambda: send_tts_message(conn, "sentence_start", text)
)
else:
- # 新句子或流控器未初始化,立即发送
+ # New sentence or rate controller not initialized, send immediately
await send_tts_message(conn, "sentence_start", text)
await sendAudio(conn, audios)
- # 发送句子开始消息
+ # Send sentence start message
if sentenceType is not SentenceType.MIDDLE:
- conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
+ conn.logger.bind(tag=TAG).info(f"Sending audio message: {sentenceType}, {text}")
- # 发送结束消息(如果是最后一个文本)
+ # Send end message (if it is the last text)
if sentenceType == SentenceType.LAST:
await send_tts_message(conn, "stop", None)
conn.client_is_speaking = False
@@ -49,57 +49,57 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
async def _wait_for_audio_completion(conn):
"""
- 等待音频队列清空并等待预缓冲包播放完成
+ Wait for audio queue to empty and wait for pre-buffer packets to finish playing
Args:
- conn: 连接对象
+ conn: connection object
"""
if hasattr(conn, "audio_rate_controller") and conn.audio_rate_controller:
rate_controller = conn.audio_rate_controller
conn.logger.bind(tag=TAG).debug(
- f"等待音频发送完成,队列中还有 {len(rate_controller.queue)} 个包"
+ f"Waiting for audio completion, {len(rate_controller.queue)} packets remaining"
)
await rate_controller.queue_empty_event.wait()
- # 等待预缓冲包播放完成
- # 前N个包直接发送,增加2个网络抖动包,需要额外等待它们在客户端播放完成
+ # Wait for pre-buffer packets to finish playing
+ # First N packets sent directly, adding 2 network jitter packets, need extra wait for them to finish playing on client
frame_duration_ms = rate_controller.frame_duration
pre_buffer_playback_time = (PRE_BUFFER_COUNT + 2) * frame_duration_ms / 1000.0
await asyncio.sleep(pre_buffer_playback_time)
- conn.logger.bind(tag=TAG).debug("音频发送完成")
+ conn.logger.bind(tag=TAG).debug("Audio sending completed")
async def _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence):
"""
- 发送带16字节头部的opus数据包给mqtt_gateway
+ Send opus packet with 16-byte header to mqtt_gateway
Args:
- conn: 连接对象
- opus_packet: opus数据包
- timestamp: 时间戳
- sequence: 序列号
+ conn: connection object
+ opus_packet: opus data packet
+ timestamp: timestamp
+ sequence: sequence number
"""
- # 为opus数据包添加16字节头部
+ # Add 16-byte header to opus packet
header = bytearray(16)
header[0] = 1 # type
header[2:4] = len(opus_packet).to_bytes(2, "big") # payload length
header[4:8] = sequence.to_bytes(4, "big") # sequence
- header[8:12] = timestamp.to_bytes(4, "big") # 时间戳
- header[12:16] = len(opus_packet).to_bytes(4, "big") # opus长度
+ header[8:12] = timestamp.to_bytes(4, "big") # timestamp
+ header[12:16] = len(opus_packet).to_bytes(4, "big") # opus length
- # 发送包含头部的完整数据包
+ # Send complete packet containing header
complete_packet = bytes(header) + opus_packet
await conn.websocket.send(complete_packet)
async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
"""
- 发送音频包,使用 AudioRateController 进行精确的流量控制
+ Send audio packets, use AudioRateController for precise flow control
Args:
- conn: 连接对象
- audios: 单个opus包(bytes) 或 opus包列表
- frame_duration: 帧时长(毫秒),默认使用全局常量AUDIO_FRAME_DURATION
+ conn: connection object
+ audios: single opus packet (bytes) or list of opus packets
+ frame_duration: frame duration (ms), default uses global constant AUDIO_FRAME_DURATION
"""
if audios is None or len(audios) == 0:
return
@@ -107,15 +107,15 @@ async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
send_delay = conn.config.get("tts_audio_send_delay", -1) / 1000.0
is_single_packet = isinstance(audios, bytes)
- # 初始化或获取 RateController
+ # Initialize or get RateController
rate_controller, flow_control = _get_or_create_rate_controller(
conn, frame_duration, is_single_packet
)
- # 统一转换为列表处理
+ # Unified conversion to list processing
audio_list = [audios] if is_single_packet else audios
- # 发送音频包
+ # Send audio packets
await _send_audio_with_rate_control(
conn, audio_list, rate_controller, flow_control, send_delay
)
@@ -123,32 +123,32 @@ async def sendAudio(conn, audios, frame_duration=AUDIO_FRAME_DURATION):
def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
"""
- 获取或创建 RateController 和 flow_control
+ Get or create RateController and flow_control
Args:
- conn: 连接对象
- frame_duration: 帧时长
- is_single_packet: 是否单包模式(True: TTS流式单包, False: 批量包)
+ conn: connection object
+ frame_duration: frame duration
+ is_single_packet: Whether single packet mode (True: TTS streaming single packet, False: batch packet)
Returns:
(rate_controller, flow_control)
"""
- # 检查是否需要重置控制器
+ # Check if controller needs reset
need_reset = False
if not hasattr(conn, "audio_rate_controller"):
- # 控制器不存在,需要创建
+ # Controller does not exist, need to create
need_reset = True
else:
rate_controller = conn.audio_rate_controller
- # 后台发送任务已停止, 则需要重置
+ # Background send task stopped, need to reset
if (
not rate_controller.pending_send_task
or rate_controller.pending_send_task.done()
):
need_reset = True
- # 当sentence_id 变化,需要重置
+ # When sentence_id changes, need to reset
elif (
getattr(conn, "audio_flow_control", {}).get("sentence_id")
!= conn.sentence_id
@@ -156,20 +156,20 @@ def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
need_reset = True
if need_reset:
- # 创建或获取 rate_controller
+ # Create or get rate_controller
if not hasattr(conn, "audio_rate_controller"):
conn.audio_rate_controller = AudioRateController(frame_duration)
else:
conn.audio_rate_controller.reset()
- # 初始化 flow_control
+ # Initialize flow_control
conn.audio_flow_control = {
"packet_count": 0,
"sequence": 0,
"sentence_id": conn.sentence_id,
}
- # 启动后台发送循环
+ # Start background send loop
_start_background_sender(
conn, conn.audio_rate_controller, conn.audio_flow_control
)
@@ -179,24 +179,24 @@ def _get_or_create_rate_controller(conn, frame_duration, is_single_packet):
def _start_background_sender(conn, rate_controller, flow_control):
"""
- 启动后台发送循环任务
+ Start background send loop task
Args:
- conn: 连接对象
- rate_controller: 速率控制器
- flow_control: 流控状态
+ conn: connection object
+ rate_controller: rate controller
+ flow_control: flow control status
"""
async def send_callback(packet):
- # 检查是否应该中止
+ # Check if should abort
if conn.client_abort:
- raise asyncio.CancelledError("客户端已中止")
+ raise asyncio.CancelledError("Client aborted")
conn.last_activity_time = time.time() * 1000
await _do_send_audio(conn, packet, flow_control)
conn.client_is_speaking = True
- # 使用 start_sending 启动后台循环
+ # Use start_sending to start background loop
rate_controller.start_sending(send_callback)
@@ -204,14 +204,14 @@ async def _send_audio_with_rate_control(
conn, audio_list, rate_controller, flow_control, send_delay
):
"""
- 使用 rate_controller 发送音频包
+ Use rate_controller to send audio packets
Args:
- conn: 连接对象
- audio_list: 音频包列表
- rate_controller: 速率控制器
- flow_control: 流控状态
- send_delay: 固定延迟(秒),-1表示使用动态流控
+ conn: connection object
+ audio_list: list of audio packets
+ rate_controller: rate controller
+ flow_control: flow control status
+ send_delay: fixed delay (seconds), -1 means use dynamic flow control
"""
for packet in audio_list:
if conn.client_abort:
@@ -219,52 +219,52 @@ async def _send_audio_with_rate_control(
conn.last_activity_time = time.time() * 1000
- # 预缓冲:前N个包直接发送
+ # Pre-buffer: first N packets send directly
if flow_control["packet_count"] < PRE_BUFFER_COUNT:
await _do_send_audio(conn, packet, flow_control)
conn.client_is_speaking = True
elif send_delay > 0:
- # 固定延迟模式
+ # Fixed delay mode
await asyncio.sleep(send_delay)
await _do_send_audio(conn, packet, flow_control)
conn.client_is_speaking = True
else:
- # 动态流控模式:仅添加到队列,由后台循环负责发送
+ # Dynamic flow control mode: only add to queue, background loop responsible for sending
rate_controller.add_audio(packet)
async def _do_send_audio(conn, opus_packet, flow_control):
"""
- 执行实际的音频发送
+ Execute actual audio sending
"""
packet_index = flow_control.get("packet_count", 0)
sequence = flow_control.get("sequence", 0)
if conn.conn_from_mqtt_gateway:
- # 计算时间戳(基于播放位置)
+ # Calculate timestamp (based on playback position)
start_time = time.time()
timestamp = int(start_time * 1000) % (2**32)
await _send_to_mqtt_gateway(conn, opus_packet, timestamp, sequence)
else:
- # 直接发送opus数据包
+ # Send opus data packet directly
await conn.websocket.send(opus_packet)
- # 更新流控状态
+ # Update flow control status
flow_control["packet_count"] = packet_index + 1
flow_control["sequence"] = sequence + 1
async def send_tts_message(conn, state, text=None):
- """发送 TTS 状态消息"""
+ """Send TTS state message"""
if text is None and state == "sentence_start":
return
message = {"type": "tts", "state": state, "session_id": conn.session_id}
if text is not None:
message["text"] = textUtils.check_emoji(text)
- # TTS播放结束
+ # TTS playback finished
if state == "stop":
- # 播放提示音
+ # Play notification sound
tts_notify = conn.config.get("enable_stop_tts_notify", False)
if tts_notify:
stop_tts_notify_voice = conn.config.get(
@@ -272,36 +272,36 @@ async def send_tts_message(conn, state, text=None):
)
audios = await audio_to_data(stop_tts_notify_voice, is_opus=True)
await sendAudio(conn, audios)
- # 等待所有音频包发送完成
+ # Wait for all audio packets to finish sending
await _wait_for_audio_completion(conn)
- # 清除服务端讲话状态
+ # Clear server speaking status
conn.clearSpeakStatus()
- # 发送消息到客户端
+ # Send message to client
await conn.websocket.send(json.dumps(message))
async def send_stt_message(conn, text):
- """发送 STT 状态消息"""
+ """Send STT state message"""
end_prompt_str = conn.config.get("end_prompt", {}).get("prompt")
if end_prompt_str and end_prompt_str == text:
await send_tts_message(conn, "start")
return
- # 解析JSON格式,提取实际的用户说话内容
+ # Parse JSON format, extract actual user spoken content
display_text = text
try:
- # 尝试解析JSON格式
+ # Try to parse JSON format
if text.strip().startswith("{") and text.strip().endswith("}"):
parsed_data = json.loads(text)
if isinstance(parsed_data, dict) and "content" in parsed_data:
- # 如果是包含说话人信息的JSON格式,只显示content部分
+ # If JSON format containing speaker info, only display content part
display_text = parsed_data["content"]
- # 保存说话人信息到conn对象
+ # Save speaker info to conn object
if "speaker" in parsed_data:
conn.current_speaker = parsed_data["speaker"]
except (json.JSONDecodeError, TypeError):
- # 如果不是JSON格式,直接使用原始文本
+ # If not JSON format, use original text directly
display_text = text
stt_text = textUtils.get_string_no_punctuation_or_emoji(display_text)
await conn.websocket.send(
diff --git a/main/xiaozhi-server/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py
index b5e877834..379f40645 100644
--- a/main/xiaozhi-server/core/handle/textHandle.py
+++ b/main/xiaozhi-server/core/handle/textHandle.py
@@ -3,12 +3,12 @@ from core.handle.textMessageProcessor import TextMessageProcessor
TAG = __name__
-# 全局处理器注册表
+# Global handler registry
message_registry = TextMessageHandlerRegistry()
-# 创建全局消息处理器实例
+# Create global message processor instance
message_processor = TextMessageProcessor(message_registry)
async def handleTextMessage(conn, message):
- """处理文本消息"""
+ """Handle text message"""
await message_processor.process_message(conn, message)
diff --git a/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py
index dc540d24a..d886a89d7 100644
--- a/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py
+++ b/main/xiaozhi-server/core/handle/textHandler/abortMessageHandler.py
@@ -6,7 +6,7 @@ from core.handle.textMessageType import TextMessageType
class AbortTextMessageHandler(TextMessageHandler):
- """Abort消息处理器"""
+ """Abort message handler"""
@property
def message_type(self) -> TextMessageType:
diff --git a/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py b/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py
index b9a235888..163d08aeb 100644
--- a/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py
+++ b/main/xiaozhi-server/core/handle/textHandler/serverMessageHandler.py
@@ -9,42 +9,42 @@ from core.providers.tools.device_mcp import handle_mcp_message
TAG = __name__
class ServerTextMessageHandler(TextMessageHandler):
- """MCP消息处理器"""
+ """MCP message handler"""
@property
def message_type(self) -> TextMessageType:
return TextMessageType.SERVER
async def handle(self, conn, msg_json: Dict[str, Any]) -> None:
- # 如果配置是从API读取的,则需要验证secret
+ # If config is read from API, need to verify secret
if not conn.read_config_from_api:
return
- # 获取post请求的secret
+ # Get secret from post request
post_secret = msg_json.get("content", {}).get("secret", "")
secret = conn.config["manager-api"].get("secret", "")
- # 如果secret不匹配,则返回
+ # If secret does not match, return
if post_secret != secret:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
- "message": "服务器密钥验证失败",
+ "message": "Server secret verification failed",
}
)
)
return
- # 动态更新配置
+ # Dynamically update config
if msg_json["action"] == "update_config":
try:
- # 更新WebSocketServer的配置
+ # Update WebSocketServer config
if not conn.server:
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
- "message": "无法获取服务器实例",
+ "message": "Cannot get server instance",
"content": {"action": "update_config"},
}
)
@@ -57,36 +57,36 @@ class ServerTextMessageHandler(TextMessageHandler):
{
"type": "server",
"status": "error",
- "message": "更新服务器配置失败",
+ "message": "Failed to update server config",
"content": {"action": "update_config"},
}
)
)
return
- # 发送成功响应
+ # Send success response
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "success",
- "message": "配置更新成功",
+ "message": "Config updated successfully",
"content": {"action": "update_config"},
}
)
)
except Exception as e:
- conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}")
+ conn.logger.bind(tag=TAG).error(f"Failed to update config: {str(e)}")
await conn.websocket.send(
json.dumps(
{
"type": "server",
"status": "error",
- "message": f"更新配置失败: {str(e)}",
+ "message": f"Failed to update config: {str(e)}",
"content": {"action": "update_config"},
}
)
)
- # 重启服务器
+ # Restart server
elif msg_json["action"] == "restart":
await conn.handle_restart(msg_json)
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py b/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py
index 65e9474f1..b4cffcf76 100644
--- a/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py
+++ b/main/xiaozhi-server/core/handle/textMessageHandlerRegistry.py
@@ -13,14 +13,14 @@ TAG = __name__
class TextMessageHandlerRegistry:
- """消息处理器注册表"""
+ """Message handler registry"""
def __init__(self):
self._handlers: Dict[str, TextMessageHandler] = {}
self._register_default_handlers()
def _register_default_handlers(self) -> None:
- """注册默认的消息处理器"""
+ """Register default message handlers"""
handlers = [
HelloTextMessageHandler(),
AbortTextMessageHandler(),
@@ -35,13 +35,13 @@ class TextMessageHandlerRegistry:
self.register_handler(handler)
def register_handler(self, handler: TextMessageHandler) -> None:
- """注册消息处理器"""
+ """Register message handler"""
self._handlers[handler.message_type.value] = handler
def get_handler(self, message_type: str) -> Optional[TextMessageHandler]:
- """获取消息处理器"""
+ """Get message handler"""
return self._handlers.get(message_type)
def get_supported_types(self) -> list:
- """获取支持的消息类型"""
+ """Get supported message types"""
return list(self._handlers.keys())
diff --git a/main/xiaozhi-server/core/handle/textMessageProcessor.py b/main/xiaozhi-server/core/handle/textMessageProcessor.py
index 0cae5e099..b7e11cf8f 100644
--- a/main/xiaozhi-server/core/handle/textMessageProcessor.py
+++ b/main/xiaozhi-server/core/handle/textMessageProcessor.py
@@ -1,41 +1,57 @@
import json
-
+import asyncio
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
TAG = __name__
-
class TextMessageProcessor:
- """消息处理器主类"""
+ """Main Message Processor Class"""
def __init__(self, registry: TextMessageHandlerRegistry):
self.registry = registry
async def process_message(self, conn, message: str) -> None:
- """处理消息的主入口"""
+ """Main entry point for message processing"""
try:
- # 解析JSON消息
+ # Parse JSON message
msg_json = json.loads(message)
- # 处理JSON消息
+ # Handle JSON message
if isinstance(msg_json, dict):
message_type = msg_json.get("type")
- # 记录日志
- conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}")
+ # SAFE LOGGING: Prevent terminal buffer overflow on large MCP payloads
+ if message_type == "mcp":
+ conn.logger.bind(tag=TAG).info(f"Received {message_type} message (Payload hidden for performance)")
+ else:
+ conn.logger.bind(tag=TAG).info(f"Received {message_type} message: {message}")
- # 获取并执行处理器
+ # TRIGGER: If this is NOT a hello message and MCP is enabled but not ready,
+ # start discovery now so it doesn't block the handshake.
+ if message_type != "hello" and conn.features.get("mcp"):
+ if not hasattr(conn, "mcp_client") or conn.mcp_client is None:
+ from core.providers.tools.device_mcp.mcp_handler import (
+ MCPClient, send_mcp_initialize_message, send_mcp_tools_list_request
+ )
+ conn.logger.bind(tag=TAG).info("First user interaction detected. Initializing MCP in background...")
+ conn.mcp_client = MCPClient()
+ asyncio.create_task(send_mcp_initialize_message(conn))
+ asyncio.create_task(send_mcp_tools_list_request(conn))
+
+ # Get and execute the handler
handler = self.registry.get_handler(message_type)
if handler:
await handler.handle(conn, msg_json)
else:
- conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
- # 处理纯数字消息
+ conn.logger.bind(tag=TAG).error(f"Received unknown message type: {message}")
+
+ # Handle numeric messages
elif isinstance(msg_json, int):
- conn.logger.bind(tag=TAG).info(f"收到数字消息:{message}")
+ conn.logger.bind(tag=TAG).info(f"Received numeric message: {message}")
await conn.websocket.send(message)
except json.JSONDecodeError:
- # 非JSON消息直接转发
- conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}")
+ # Forward non-JSON messages directly
+ conn.logger.bind(tag=TAG).error(f"Failed to parse message: {message}")
await conn.websocket.send(message)
+
diff --git a/main/xiaozhi-server/core/http_server.py b/main/xiaozhi-server/core/http_server.py
index feb96f3b7..bb983fe8a 100644
--- a/main/xiaozhi-server/core/http_server.py
+++ b/main/xiaozhi-server/core/http_server.py
@@ -15,22 +15,23 @@ class SimpleHttpServer:
self.vision_handler = VisionHandler(config)
def _get_websocket_url(self, local_ip: str, port: int) -> str:
- """获取websocket地址
+ """Get websocket address
Args:
- local_ip: 本地IP地址
- port: 端口号
+ local_ip: Local IP address
+ port: Port number
Returns:
- str: websocket地址
+ str: websocket address
"""
server_config = self.config["server"]
websocket_config = server_config.get("websocket")
- if websocket_config and "你" not in websocket_config:
+ # Check if config is valid (not a placeholder "localhost", and not "127.0.0.1")
+ if websocket_config and websocket_config != "default":
return websocket_config
else:
- return f"ws://{local_ip}:{port}/xiaozhi/v1/"
+ return f"ws://{local_ip}:{port}/xiaozhi/v1"
async def start(self):
try:
@@ -43,7 +44,7 @@ class SimpleHttpServer:
app = web.Application()
if not read_config_from_api:
- # 如果没有开启智控台,只是单模块运行,就需要再添加简单OTA接口,用于下发websocket接口
+ # If console is not enabled and running as single module, add simple OTA interface for distributing websocket interface
app.add_routes(
[
web.get("/xiaozhi/ota/", self.ota_handler.handle_get),
@@ -51,7 +52,7 @@ class SimpleHttpServer:
web.options(
"/xiaozhi/ota/", self.ota_handler.handle_options
),
- # 下载接口,仅提供 data/bin/*.bin 下载
+ # Download interface, only provides data/bin/*.bin download
web.get(
"/xiaozhi/ota/download/{filename}",
self.ota_handler.handle_download,
@@ -62,7 +63,7 @@ class SimpleHttpServer:
),
]
)
- # 添加路由
+ # Add routes
app.add_routes(
[
web.get("/mcp/vision/explain", self.vision_handler.handle_get),
@@ -75,18 +76,18 @@ class SimpleHttpServer:
]
)
- # 运行服务
+ # Run service
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host, port)
await site.start()
- # 保持服务运行
+ # Keep service running
while True:
- await asyncio.sleep(3600) # 每隔 1 小时检查一次
+ await asyncio.sleep(3600) # Check every 1 hour
except Exception as e:
- self.logger.bind(tag=TAG).error(f"HTTP服务器启动失败: {e}")
+ self.logger.bind(tag=TAG).error(f"HTTP server startup failed: {e}")
import traceback
- self.logger.bind(tag=TAG).error(f"错误堆栈: {traceback.format_exc()}")
+ self.logger.bind(tag=TAG).error(f"Error stack: {traceback.format_exc()}")
raise
diff --git a/main/xiaozhi-server/core/providers/asr/aliyun.py b/main/xiaozhi-server/core/providers/asr/aliyun.py
index 36f417457..aae6a2420 100644
--- a/main/xiaozhi-server/core/providers/asr/aliyun.py
+++ b/main/xiaozhi-server/core/providers/asr/aliyun.py
@@ -45,10 +45,10 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
- # 构造规范化的请求字符串
+ # Construct normalized request string
query_string = AccessToken._encode_dict(parameters)
- # print('规范化的请求字符串: %s' % query_string)
- # 构造待签名字符串
+ # print('Normalized request string: %s' % query_string)
+ # Construct string to sign
string_to_sign = (
"GET"
+ "&"
@@ -56,25 +56,25 @@ class AccessToken:
+ "&"
+ AccessToken._encode_text(query_string)
)
- # print('待签名的字符串: %s' % string_to_sign)
- # 计算签名
+ # print('String to sign: %s' % string_to_sign)
+ # Calculate signature
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
- # print('签名: %s' % signature)
- # 进行URL编码
+ # print('Signature: %s' % signature)
+ # URL encode
signature = AccessToken._encode_text(signature)
- # print('URL编码后的签名: %s' % signature)
- # 调用服务
+ # print('URL encoded signature: %s' % signature)
+ # Call service
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
- # 提交HTTP GET请求
+ # Submit HTTP GET request
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
@@ -91,8 +91,8 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
self.interface_type = InterfaceType.NON_STREAM
- """阿里云ASR初始化"""
- # 新增空值判断逻辑
+ """Aliyun ASR initialization"""
+ # Added null value check logic
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
@@ -105,27 +105,27 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file
if self.access_key_id and self.access_key_secret:
- # 使用密钥对生成临时token
+ # Use key pair to generate temporary token
self._refresh_token()
else:
- # 直接使用预生成的长期token
+ # Use pre-generated long-term token directly
self.token = config.get("token")
self.expire_time = None
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
def _refresh_token(self):
- """刷新Token并记录过期时间"""
+ """Refresh Token and record expiration time"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
- raise ValueError("无法获取有效的Token过期时间")
+ raise ValueError("Failed to get valid Token expiration time")
try:
- # 统一转换为字符串处理
+ # Convert to string for consistent handling
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
@@ -134,13 +134,13 @@ class ASRProvider(ASRProviderBase):
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
- raise ValueError(f"无效的过期时间格式: {expire_str}") from e
+ raise ValueError(f"Invalid expiration time format: {expire_str}") from e
else:
self.expire_time = None
if not self.token:
- raise ValueError("无法获取有效的访问Token")
+ raise ValueError("Failed to get valid access Token")
def _is_token_expired(self):
"""检查Token是否过期"""
@@ -148,14 +148,12 @@ class ASRProvider(ASRProviderBase):
return False # 长期Token不过期
# 新增调试日志
# current_time = time.time()
- # remaining = self.expire_time - current_time
- # print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
- # f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
- # f"剩余 {remaining:.2f}秒")
- return time.time() > self.expire_time
-
- def _construct_request_url(self) -> str:
- """构造请求URL,包含参数"""
+ def _is_token_expired(self):
+ """Check if Token is expired"""
+ if not self.expire_time:
+ return False # Long-term Token does not expire
+ # Added debug log
+ # current_time = time.time()
request = f"{self.base_url}?appkey={self.app_key}"
request += f"&format={self.format}"
request += f"&sample_rate={self.sample_rate}"
@@ -165,16 +163,16 @@ class ASRProvider(ASRProviderBase):
return request
async def _send_request(self, pcm_data: bytes) -> Optional[str]:
- """发送请求到阿里云ASR服务"""
+ """Send request to Aliyun ASR service"""
try:
- # 设置HTTP头
+ # Set HTTP headers
headers = {
"X-NLS-Token": self.token,
"Content-type": "application/octet-stream",
"Content-Length": str(len(pcm_data)),
}
- # 创建连接并发送请求
+ # Create connection and send request
conn = http.client.HTTPSConnection(self.host)
request_url = self._construct_request_url()
@@ -186,56 +184,56 @@ class ASRProvider(ASRProviderBase):
),
)
- # 获取响应
+ # Get response
response = await loop.run_in_executor(None, conn.getresponse)
body = await loop.run_in_executor(None, response.read)
conn.close()
- # 解析响应
+ # Parse response
try:
body_json = json.loads(body)
status = body_json.get("status")
if status == 20000000:
result = body_json.get("result", "")
- logger.bind(tag=TAG).debug(f"ASR结果: {result}")
+ logger.bind(tag=TAG).debug(f"ASR result: {result}")
return result
else:
- logger.bind(tag=TAG).error(f"ASR失败,状态码: {status}")
+ logger.bind(tag=TAG).error(f"ASR failed, status code: {status}")
return None
except ValueError:
- logger.bind(tag=TAG).error("响应不是JSON格式")
+ logger.bind(tag=TAG).error("Response is not in JSON format")
return None
except Exception as e:
- logger.bind(tag=TAG).error(f"ASR请求失败: {e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"ASR request failed: {e}", exc_info=True)
return None
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ """Convert speech data to text"""
if self._is_token_expired():
- logger.warning("Token已过期,正在自动刷新...")
+ logger.warning("Token expired, refreshing automatically...")
self._refresh_token()
file_path = None
try:
- # 解码Opus为PCM
+ # Decode Opus to PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
- # 发送请求并获取文本
+ # Send request and obtain text
text = await self._send_request(combined_pcm_data)
if text:
@@ -244,5 +242,5 @@ class ASRProvider(ASRProviderBase):
return "", file_path
except Exception as e:
- logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
diff --git a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py
index 4ce588a7f..3c1afa2ec 100644
--- a/main/xiaozhi-server/core/providers/asr/aliyun_stream.py
+++ b/main/xiaozhi-server/core/providers/asr/aliyun_stream.py
@@ -74,19 +74,19 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None
self.forward_task = None
self.is_processing = False
- self.server_ready = False # 服务器准备状态
+ self.server_ready = False # Server ready status
- # 基础配置
+ # Basic configuration
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
self.appkey = config.get("appkey")
self.token = config.get("token")
self.host = config.get("host", "nls-gateway-cn-shanghai.aliyuncs.com")
- # 如果配置的是内网地址(包含-internal.aliyuncs.com),则使用ws协议,默认是wss协议
+ # If internal address is configured (contains -internal.aliyuncs.com), use ws protocol, default is wss protocol
if "-internal." in self.host:
self.ws_url = f"ws://{self.host}/ws/v1"
else:
- # 默认使用wss协议
+ # Default to wss protocol
self.ws_url = f"wss://{self.host}/ws/v1"
self.max_sentence_silence = config.get("max_sentence_silence")
@@ -96,17 +96,17 @@ class ASRProvider(ASRProviderBase):
self.task_id = uuid.uuid4().hex
- # Token管理
+ # Token management
if self.access_key_id and self.access_key_secret:
self._refresh_token()
elif not self.token:
- raise ValueError("必须提供access_key_id+access_key_secret或者直接提供token")
+ raise ValueError("Must provide access_key_id+access_key_secret or token directly")
def _refresh_token(self):
- """刷新Token"""
+ """Refresh Token"""
self.token, expire_time_str = AccessToken.create_token(self.access_key_id, self.access_key_secret)
if not self.token:
- raise ValueError("无法获取有效的访问Token")
+ raise ValueError("Failed to obtain valid access Token")
try:
expire_str = str(expire_time_str).strip()
@@ -119,7 +119,7 @@ class ASRProvider(ASRProviderBase):
self.expire_time = None
def _is_token_expired(self):
- """检查Token是否过期"""
+ """Check if Token is expired"""
return self.expire_time and time.time() > self.expire_time
async def open_audio_channels(self, conn):
@@ -137,12 +137,12 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
- # 只在有声音且没有连接时建立连接(排除正在停止的情况)
+ # Establish connection only if there is voice and no connection exists (excluding stopping cases)
if audio_have_voice and not self.is_processing and not self.asr_ws:
try:
await self._start_recognition(conn)
except Exception as e:
- logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
await self._cleanup()
return
@@ -151,15 +151,15 @@ class ASRProvider(ASRProviderBase):
pcm_frame = self.decoder.decode(audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
- logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
+ logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup(conn)
async def _start_recognition(self, conn):
- """开始识别会话"""
+ """Start recognition session"""
if self._is_token_expired():
self._refresh_token()
- # 建立连接
+ # Establish connection
headers = {"X-NLS-Token": self.token}
self.asr_ws = await websockets.connect(
self.ws_url,
@@ -172,13 +172,13 @@ class ASRProvider(ASRProviderBase):
self.task_id = uuid.uuid4().hex
- logger.bind(tag=TAG).debug(f"WebSocket连接建立成功, task_id: {self.task_id}")
+ logger.bind(tag=TAG).debug(f"WebSocket connection established, task_id: {self.task_id}")
self.is_processing = True
- self.server_ready = False # 重置服务器准备状态
+ self.server_ready = False # Reset server ready status
self.forward_task = asyncio.create_task(self._forward_results(conn))
- # 发送开始请求
+ # Send start request
start_request = {
"header": {
"namespace": "SpeechTranscriber",
@@ -198,10 +198,10 @@ class ASRProvider(ASRProviderBase):
}
}
await self.asr_ws.send(json.dumps(start_request, ensure_ascii=False))
- logger.bind(tag=TAG).debug("已发送开始请求,等待服务器准备...")
+ logger.bind(tag=TAG).debug("Start request sent, waiting for server preparation...")
async def _forward_results(self, conn):
- """转发识别结果"""
+ """Forward recognition results"""
try:
while not conn.stop_event.is_set():
try:
@@ -215,58 +215,58 @@ class ASRProvider(ASRProviderBase):
if status != 20000000:
if status == 40010004:
- logger.bind(tag=TAG).warning(f"请在服务端响应完成后再关闭链接,状态码: {status}")
+ logger.bind(tag=TAG).warning(f"Please close connection after server response is complete, status code: {status}")
break
- if status in [40000004, 40010003]: # 连接超时或客户端断开
- logger.bind(tag=TAG).warning(f"连接问题,状态码: {status}")
+ if status in [40000004, 40010003]: # Connection timeout or client disconnect
+ logger.bind(tag=TAG).warning(f"Connection issue, status code: {status}")
break
- elif status in [40270002, 40270003]: # 音频问题
- logger.bind(tag=TAG).warning(f"音频处理问题,状态码: {status}")
+ elif status in [40270002, 40270003]: # Audio issue
+ logger.bind(tag=TAG).warning(f"Audio processing issue, status code: {status}")
continue
else:
- logger.bind(tag=TAG).error(f"识别错误,状态码: {status}, 消息: {header.get('status_text', '')}")
+ logger.bind(tag=TAG).error(f"Recognition error, status code: {status}, message: {header.get('status_text', '')}")
continue
- # 收到TranscriptionStarted表示服务器准备好接收音频数据
+ # Received TranscriptionStarted indicating server is ready to receive audio data
if message_name == "TranscriptionStarted":
self.server_ready = True
- logger.bind(tag=TAG).debug("服务器已准备,开始发送缓存音频...")
+ logger.bind(tag=TAG).debug("Server ready, starting to send cached audio...")
- # 发送缓存音频
+ # Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
- logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
+ logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break
continue
elif message_name == "SentenceEnd":
- # 句子结束(每个句子都会触发)
+ # Sentence end (triggered for each sentence)
text = payload.get("result", "")
if text:
- logger.bind(tag=TAG).info(f"识别到文本: {text}")
+ logger.bind(tag=TAG).info(f"Recognized text: {text}")
- # 手动模式下累积识别结果
+ # Accumulate recognition results in manual mode
if conn.client_listen_mode == "manual":
if self.text:
self.text += text
else:
self.text = text
- # 手动模式下,只有在收到stop信号后才触发处理(仅处理一次)
+ # In manual mode, only trigger processing after receiving stop signal (process only once)
if conn.client_voice_stop:
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
if len(audio_data) > 0:
- logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
+ logger.bind(tag=TAG).debug("Received final result, trigger processing")
await self.handle_voice_stop(conn, audio_data)
- # 清理音频缓存
+ # Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
else:
- # 自动模式下直接覆盖
+ # Overwrite directly in auto mode
self.text = text
conn.reset_vad_states()
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
@@ -274,20 +274,20 @@ class ASRProvider(ASRProviderBase):
break
except asyncio.TimeoutError:
- logger.bind(tag=TAG).error("接收结果超时")
+ logger.bind(tag=TAG).error("Receive result timeout")
break
except websockets.ConnectionClosed:
- logger.bind(tag=TAG).info("ASR服务连接已关闭")
+ logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
- logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to process result: {str(e)}")
break
except Exception as e:
- logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
- # 清理连接的音频缓存
+ # Clear connected audio cache
await self._cleanup()
if conn:
if hasattr(conn, 'asr_audio_for_voiceprint'):
@@ -296,10 +296,10 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio = []
async def _send_stop_request(self):
- """发送停止识别请求(不关闭连接)"""
+ """Send stop recognition request (without closing connection)"""
if self.asr_ws:
try:
- # 先停止音频发送
+ # Stop audio sending first
self.is_processing = False
stop_msg = {
@@ -311,44 +311,44 @@ class ASRProvider(ASRProviderBase):
"appkey": self.appkey
}
}
- logger.bind(tag=TAG).debug("停止识别请求已发送")
+ logger.bind(tag=TAG).debug("Stop recognition request sent")
await self.asr_ws.send(json.dumps(stop_msg, ensure_ascii=False))
except Exception as e:
- logger.bind(tag=TAG).error(f"发送停止识别请求失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to send stop recognition request: {e}")
async def _cleanup(self):
- """清理资源(关闭连接)"""
- logger.bind(tag=TAG).debug(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
+ """Cleanup resources (close connection)"""
+ logger.bind(tag=TAG).debug(f"Starting ASR session cleanup | Current Status: processing={self.is_processing}, server_ready={self.server_ready}")
- # 状态重置
+ # Reset status
self.is_processing = False
self.server_ready = False
- logger.bind(tag=TAG).debug("ASR状态已重置")
+ logger.bind(tag=TAG).debug("ASR status reset")
- # 关闭连接
+ # Close connection
if self.asr_ws:
try:
- logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
+ logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
- logger.bind(tag=TAG).debug("WebSocket连接已关闭")
+ logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
- logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
- # 清理任务引用
+ # Clean up task reference
self.forward_task = None
- logger.bind(tag=TAG).debug("ASR会话清理完成")
+ logger.bind(tag=TAG).debug("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
- """获取识别结果"""
+ """Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
- """关闭资源"""
+ """Close resources"""
await self._cleanup(None)
if hasattr(self, 'decoder') and self.decoder is not None:
try:
@@ -356,4 +356,4 @@ class ASRProvider(ASRProviderBase):
self.decoder = None
logger.bind(tag=TAG).debug("Aliyun decoder resources released")
except Exception as e:
- logger.bind(tag=TAG).debug(f"释放Aliyun decoder资源时出错: {e}")
+ logger.bind(tag=TAG).debug(f"Error when releasing Aliyun decoder resources: {e}")
diff --git a/main/xiaozhi-server/core/providers/asr/aliyunbl_stream.py b/main/xiaozhi-server/core/providers/asr/aliyunbl_stream.py
index a321ce9b9..4d8523091 100644
--- a/main/xiaozhi-server/core/providers/asr/aliyunbl_stream.py
+++ b/main/xiaozhi-server/core/providers/asr/aliyunbl_stream.py
@@ -22,16 +22,16 @@ class ASRProvider(ASRProviderBase):
self.asr_ws = None
self.forward_task = None
self.is_processing = False
- self.server_ready = False # 服务器准备状态
- self.task_id = None # 当前任务ID
+ self.server_ready = False # Server ready status
+ self.task_id = None # Current task ID
- # 阿里百炼配置
+ # Aliyun Bailian configuration
self.api_key = config.get("api_key")
self.model = config.get("model", "paraformer-realtime-v2")
self.sample_rate = config.get("sample_rate", 16000)
self.format = config.get("format", "pcm")
- # 可选参数
+ # Optional parameters
self.vocabulary_id = config.get("vocabulary_id")
self.disfluency_removal_enabled = config.get("disfluency_removal_enabled", False)
self.language_hints = config.get("language_hints")
@@ -52,40 +52,40 @@ class ASRProvider(ASRProviderBase):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
- # 初始化音频缓存
+ # Initialize audio buffer
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
- # 存储音频数据
+ # Store audio data
if audio:
conn.asr_audio_for_voiceprint.append(audio)
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
- # 只在有声音且没有连接时建立连接
+ # Establish connection only if there is voice and no connection exists
if audio_have_voice and not self.is_processing and not self.asr_ws:
try:
await self._start_recognition(conn)
except Exception as e:
- logger.bind(tag=TAG).error(f"开始识别失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to start recognition: {str(e)}")
await self._cleanup()
return
- # 发送音频数据
+ # Send audio data
if self.asr_ws and self.is_processing and self.server_ready:
try:
pcm_frame = self.decoder.decode(audio, 960)
- # 直接发送PCM音频数据(二进制)
+ # Directly send PCM audio data (binary)
await self.asr_ws.send(pcm_frame)
except Exception as e:
- logger.bind(tag=TAG).warning(f"发送音频失败: {str(e)}")
+ logger.bind(tag=TAG).warning(f"Failed to send audio: {str(e)}")
await self._cleanup()
async def _start_recognition(self, conn):
- """开始识别会话"""
+ """Start recognition session"""
try:
- # 如果为手动模式,设置超时时长为最大值
+ # If manual mode, set timeout to max value
if conn.client_listen_mode == "manual":
self.max_sentence_silence = 6000
@@ -97,7 +97,7 @@ class ASRProvider(ASRProviderBase):
"Authorization": f"Bearer {self.api_key}"
}
- logger.bind(tag=TAG).debug(f"正在连接阿里百炼ASR服务, task_id: {self.task_id}")
+ logger.bind(tag=TAG).debug(f"Connecting to Aliyun Bailian ASR service, task_id: {self.task_id}")
self.asr_ws = await websockets.connect(
self.ws_url,
@@ -108,18 +108,18 @@ class ASRProvider(ASRProviderBase):
close_timeout=5,
)
- logger.bind(tag=TAG).debug("WebSocket连接建立成功")
+ logger.bind(tag=TAG).debug("WebSocket connection established")
self.server_ready = False
self.forward_task = asyncio.create_task(self._forward_results(conn))
- # 发送run-task指令
+ # Send run-task command
run_task_msg = self._build_run_task_message()
await self.asr_ws.send(json.dumps(run_task_msg, ensure_ascii=False))
- logger.bind(tag=TAG).debug("已发送run-task指令,等待服务器准备...")
+ logger.bind(tag=TAG).debug("Sent run-task command, waiting for server preparation...")
except Exception as e:
- logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
@@ -127,7 +127,7 @@ class ASRProvider(ASRProviderBase):
raise
def _build_run_task_message(self) -> dict:
- """构建run-task指令"""
+ """Build run-task command"""
message = {
"header": {
"action": "run-task",
@@ -153,7 +153,7 @@ class ASRProvider(ASRProviderBase):
}
}
- # 只有当模型名称以v2结尾时才添加vocabulary_id参数
+ # Add vocabulary_id only if model name ends with v2
if self.model.lower().endswith("v2"):
message["payload"]["parameters"]["vocabulary_id"] = self.vocabulary_id
@@ -163,7 +163,7 @@ class ASRProvider(ASRProviderBase):
return message
async def _forward_results(self, conn):
- """转发识别结果"""
+ """Forward recognition results"""
try:
while not conn.stop_event.is_set():
try:
@@ -174,23 +174,23 @@ class ASRProvider(ASRProviderBase):
payload = result.get("payload", {})
event = header.get("event", "")
- # 处理task-started事件
+ # Handle task-started event
if event == "task-started":
self.server_ready = True
- logger.bind(tag=TAG).debug("服务器已准备,开始发送缓存音频...")
+ logger.bind(tag=TAG).debug("Server ready, starting to send cached audio...")
- # 发送缓存音频
+ # Send cached audio
if conn.asr_audio:
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self.asr_ws.send(pcm_frame)
except Exception as e:
- logger.bind(tag=TAG).warning(f"发送缓存音频失败: {e}")
+ logger.bind(tag=TAG).warning(f"Failed to send cached audio: {e}")
break
continue
- # 处理result-generated事件
+ # Handle result-generated event
elif event == "result-generated":
output = payload.get("output", {})
sentence = output.get("sentence", {})
@@ -199,63 +199,63 @@ class ASRProvider(ASRProviderBase):
sentence_end = sentence.get("sentence_end", False)
end_time = sentence.get("end_time")
- # 判断是否为最终结果(sentence_end为True且end_time不为null)
+ # Determine if it is final result (sentence_end is True and end_time is not null)
is_final = sentence_end and end_time is not None
if is_final:
- logger.bind(tag=TAG).info(f"识别到文本: {text}")
+ logger.bind(tag=TAG).info(f"Recognized text: {text}")
- # 手动模式下累积识别结果
+ # Accumulate recognition results in manual mode
if conn.client_listen_mode == "manual":
if self.text:
self.text += text
else:
self.text = text
- # 手动模式下,只有在收到stop信号后才触发处理
+ # In manual mode, only trigger processing after receiving stop signal
if conn.client_voice_stop:
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
if len(audio_data) > 0:
- logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
+ logger.bind(tag=TAG).debug("Received final recognition result, triggering processing")
await self.handle_voice_stop(conn, audio_data)
- # 清理音频缓存
+ # Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
else:
- # 自动模式下直接覆盖
+ # Overwrite directly in auto mode
self.text = text
conn.reset_vad_states()
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
await self.handle_voice_stop(conn, audio_data)
break
- # 处理task-finished事件
+ # Handle task-finished event
elif event == "task-finished":
- logger.bind(tag=TAG).debug("任务已完成")
+ logger.bind(tag=TAG).debug("Task finished")
break
- # 处理task-failed事件
+ # Handle task-failed event
elif event == "task-failed":
error_code = header.get("error_code", "UNKNOWN")
- error_message = header.get("error_message", "未知错误")
- logger.bind(tag=TAG).error(f"任务失败: {error_code} - {error_message}")
+ error_message = header.get("error_message", "Unknown error")
+ logger.bind(tag=TAG).error(f"Task failed: {error_code} - {error_message}")
break
except asyncio.TimeoutError:
continue
except websockets.ConnectionClosed:
- logger.bind(tag=TAG).info("ASR服务连接已关闭")
+ logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
- logger.bind(tag=TAG).error(f"处理结果失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Result processing failed: {str(e)}")
break
except Exception as e:
- logger.bind(tag=TAG).error(f"结果转发失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Result forwarding failed: {str(e)}")
finally:
- # 清理连接的音频缓存
+ # Clean up connected audio cache
await self._cleanup()
if conn:
if hasattr(conn, 'asr_audio_for_voiceprint'):
@@ -264,19 +264,19 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio = []
async def _send_stop_request(self):
- """发送停止请求(用于手动模式停止录音)"""
+ """Send stop request (for manual mode stop recording)"""
if self.asr_ws:
try:
- # 先停止音频发送
+ # Stop sending audio first
self.is_processing = False
- logger.bind(tag=TAG).debug("收到停止请求,发送finish-task指令")
+ logger.bind(tag=TAG).debug("Received stop request, sending finish-task command")
await self._send_finish_task()
except Exception as e:
- logger.bind(tag=TAG).error(f"发送停止请求失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to send stop request: {e}")
async def _send_finish_task(self):
- """发送finish-task指令"""
+ """Send finish-task command"""
if self.asr_ws and self.task_id:
try:
finish_msg = {
@@ -290,49 +290,49 @@ class ASRProvider(ASRProviderBase):
}
}
await self.asr_ws.send(json.dumps(finish_msg, ensure_ascii=False))
- logger.bind(tag=TAG).debug("已发送finish-task指令")
+ logger.bind(tag=TAG).debug("Sent finish-task command")
except Exception as e:
- logger.bind(tag=TAG).error(f"发送finish-task指令失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to send finish-task command: {e}")
async def _cleanup(self):
- """清理资源"""
- logger.bind(tag=TAG).debug(f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}")
+ """Cleanup resources"""
+ logger.bind(tag=TAG).debug(f"Starting ASR session cleanup | Current Status: processing={self.is_processing}, server_ready={self.server_ready}")
- # 状态重置
+ # Reset status
self.is_processing = False
self.server_ready = False
- logger.bind(tag=TAG).debug("ASR状态已重置")
+ logger.bind(tag=TAG).debug("ASR status reset")
# 关闭连接
if self.asr_ws:
try:
- # 先发送finish-task指令
+ # Send finish-task command first
await self._send_finish_task()
- # 等待一小段时间让服务器处理
+ # Wait for server to process
await asyncio.sleep(0.1)
- logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
+ logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
- logger.bind(tag=TAG).debug("WebSocket连接已关闭")
+ logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
- logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
- # 清理任务引用
+ # Clean up task reference
self.forward_task = None
self.task_id = None
- logger.bind(tag=TAG).debug("ASR会话清理完成")
+ logger.bind(tag=TAG).debug("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
- """获取识别结果"""
+ """Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
- """关闭资源"""
+ """Close resources"""
await self._cleanup()
if hasattr(self, 'decoder') and self.decoder is not None:
try:
@@ -340,4 +340,4 @@ class ASRProvider(ASRProviderBase):
self.decoder = None
logger.bind(tag=TAG).debug("Aliyun BL decoder resources released")
except Exception as e:
- logger.bind(tag=TAG).debug(f"释放Aliyun BL decoder资源时出错: {e}")
\ No newline at end of file
+ logger.bind(tag=TAG).debug(f"Error releasing Aliyun BL decoder resources: {e}")
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/providers/asr/baidu.py b/main/xiaozhi-server/core/providers/asr/baidu.py
index aa8ea9015..964962318 100644
--- a/main/xiaozhi-server/core/providers/asr/baidu.py
+++ b/main/xiaozhi-server/core/providers/asr/baidu.py
@@ -26,39 +26,42 @@ class ASRProvider(ASRProviderBase):
self.client = AipSpeech(str(self.app_id), self.api_key, self.secret_key)
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ async def speech_to_text(
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """Convert speech data to text"""
if not opus_data:
- logger.bind(tag=TAG).warning("音频数据为空!")
+ logger.bind(tag=TAG).warning("Audio data is empty!")
return None, None
file_path = None
try:
- # 检查配置是否已设置
+ # Check if configuration is set
if not self.app_id or not self.api_key or not self.secret_key:
- logger.bind(tag=TAG).error("百度语音识别配置未设置,无法进行识别")
+ logger.bind(tag=TAG).error("Baidu speech recognition configuration not set, cannot perform recognition")
return None, file_path
- # 将Opus音频数据解码为PCM
+ # Decode Opus audio data to PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
self.save_audio_to_file(pcm_data, session_id)
start_time = time.time()
- # 识别本地文件
+ # Recognize local file
result = self.client.asr(
combined_pcm_data,
"pcm",
@@ -70,16 +73,16 @@ class ASRProvider(ASRProviderBase):
if result and result["err_no"] == 0:
logger.bind(tag=TAG).debug(
- f"百度语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
+ f"Baidu speech recognition time: {time.time() - start_time:.3f}s | Result: {result}"
)
result = result["result"][0]
return result, file_path
else:
raise Exception(
- f"百度语音识别失败,错误码: {result['err_no']},错误信息: {result['err_msg']}"
+ f"Baidu speech recognition failed, error code: {result['err_no']}, error message: {result['err_msg']}"
)
return None, file_path
except Exception as e:
- logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Error occurred while processing audio! {e}", exc_info=True)
return None, file_path
diff --git a/main/xiaozhi-server/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py
index 0eb23d761..2b266cad6 100644
--- a/main/xiaozhi-server/core/providers/asr/base.py
+++ b/main/xiaozhi-server/core/providers/asr/base.py
@@ -9,12 +9,13 @@ import asyncio
import traceback
import threading
import opuslib_next
+from datetime import datetime
from abc import ABC, abstractmethod
from config.logger import setup_logging
from typing import Optional, Tuple, List
from core.handle.receiveAudioHandle import startToChat
from core.handle.reportHandle import enqueue_asr_report
-from core.utils.util import remove_punctuation_and_length
+from core.utils.util import remove_punctuation_and_length, check_for_noise
from core.handle.receiveAudioHandle import handleAudioMessage
TAG = __name__
@@ -25,18 +26,30 @@ class ASRProviderBase(ABC):
def __init__(self):
pass
- # 打开音频通道
+ # Open audio channel
async def open_audio_channels(self, conn):
conn.asr_priority_thread = threading.Thread(
target=self.asr_text_priority_thread, args=(conn,), daemon=True
)
conn.asr_priority_thread.start()
- # 有序处理ASR音频
+ # Process ASR audio in order
def asr_text_priority_thread(self, conn):
while not conn.stop_event.is_set():
try:
message = conn.asr_audio_queue.get(timeout=1)
+
+ # STRICT GATE: Drop audio if client is supposed to be speaking (prevent self-echo/voxing)
+ if conn.client_is_speaking:
+ # Clear the queue to discard accumulated echo
+ while not conn.asr_audio_queue.empty():
+ try:
+ conn.asr_audio_queue.get_nowait()
+ except queue.Empty:
+ break
+ logger.bind(tag=TAG).debug("Dropped ASR packet/cleared queue because client_is_speaking=True")
+ continue
+
future = asyncio.run_coroutine_threadsafe(
handleAudioMessage(conn, message),
conn.loop,
@@ -46,17 +59,17 @@ class ASRProviderBase(ABC):
continue
except Exception as e:
logger.bind(tag=TAG).error(
- f"处理ASR文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ f"Failed to process ASR text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
continue
- # 接收音频
+ # Receive audio
async def receive_audio(self, conn, audio, audio_have_voice):
if conn.client_listen_mode == "manual":
- # 手动模式:缓存音频用于ASR识别
+ # Manual mode: Cache audio for ASR recognition
conn.asr_audio.append(audio)
else:
- # 自动/实时模式:使用VAD检测
+ # Auto/Real-time mode: Use VAD detection
have_voice = audio_have_voice
conn.asr_audio.append(audio)
@@ -64,7 +77,7 @@ class ASRProviderBase(ABC):
conn.asr_audio = conn.asr_audio[-10:]
return
- # 自动模式下通过VAD检测到语音停止时触发识别
+ # Trigger recognition when voice stop detected by VAD in auto mode
if conn.client_voice_stop:
asr_audio_task = conn.asr_audio.copy()
conn.asr_audio.clear()
@@ -73,13 +86,13 @@ class ASRProviderBase(ABC):
if len(asr_audio_task) > 15:
await self.handle_voice_stop(conn, asr_audio_task)
- # 处理语音停止
+ # Handle voice stop
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
- """并行处理ASR和声纹识别"""
+ """Process ASR and voiceprint recognition in parallel"""
try:
total_start_time = time.monotonic()
- # 准备音频数据
+ # Prepare audio data
if conn.audio_format == "pcm":
pcm_data = asr_audio_task
else:
@@ -87,17 +100,37 @@ class ASRProviderBase(ABC):
combined_pcm_data = b"".join(pcm_data)
- # 预先准备WAV数据
+ # Energy-based Noise Filtering:
+ # Drop audio if it matches the criteria (Short & Low Energy)
+ if check_for_noise(combined_pcm_data):
+ logger.bind(tag=TAG).debug(f"Dropped audio packet due to low energy/noise (Size: {len(combined_pcm_data)})")
+ return
+
+ # Prepare WAV data in advance
wav_data = None
- if conn.voiceprint_provider and combined_pcm_data:
+ if (conn.voiceprint_provider or conn.config.get("gemini_speech_to_model")) and combined_pcm_data:
wav_data = self._pcm_to_wav(combined_pcm_data)
- # 定义ASR任务
- asr_task = self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format)
+ # Speech-to-Model check
+ if conn.config.get("llm", {}).get("provider") == "gemini" and conn.config.get("gemini_speech_to_model"):
+ logger.bind(tag=TAG).info("Speech-to-Model enabled for Gemini, bypassing ASR.")
+ speaker_name = ""
+ if conn.voiceprint_provider and wav_data:
+ try:
+ speaker_name = await conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Voiceprint failed in Speech-to-Model: {e}")
+
+ enhanced_text = self._build_enhanced_text("[Speech Input]", speaker_name)
+ await startToChat(conn, enhanced_text, audio_data=wav_data)
+ return
+
+ # Define ASR task
+ asr_task = self.speech_to_text(asr_audio_task, conn.session_id, conn.audio_format, client_id=getattr(conn, "client_id", None))
if conn.voiceprint_provider and wav_data:
voiceprint_task = conn.voiceprint_provider.identify_speaker(wav_data, conn.session_id)
- # 并发等待两个结果
+ # Wait for both results concurrently
asr_result, voiceprint_result = await asyncio.gather(
asr_task, voiceprint_task, return_exceptions=True
)
@@ -105,69 +138,71 @@ class ASRProviderBase(ABC):
asr_result = await asr_task
voiceprint_result = None
- # 记录识别结果 - 检查是否为异常
+ # Record recognition results - check for exceptions
if isinstance(asr_result, Exception):
- logger.bind(tag=TAG).error(f"ASR识别失败: {asr_result}")
+ logger.bind(tag=TAG).error(f"ASR recognition failed: {asr_result}")
raw_text = ""
else:
raw_text, _ = asr_result
if isinstance(voiceprint_result, Exception):
- logger.bind(tag=TAG).error(f"声纹识别失败: {voiceprint_result}")
+ logger.bind(tag=TAG).error(f"Voiceprint recognition failed: {voiceprint_result}")
speaker_name = ""
else:
speaker_name = voiceprint_result
- # 判断 ASR 结果类型
+ # Determine ASR result type
if isinstance(raw_text, dict):
- # FunASR 返回的 dict 格式
+ # Dict format returned by FunASR
if speaker_name:
raw_text["speaker"] = speaker_name
- # 记录识别结果
+ # Record recognition results
if raw_text.get("language"):
- logger.bind(tag=TAG).info(f"识别语言: {raw_text['language']}")
+ logger.bind(tag=TAG).info(f"Detected language: {raw_text['language']}")
if raw_text.get("emotion"):
- logger.bind(tag=TAG).info(f"识别情绪: {raw_text['emotion']}")
+ logger.bind(tag=TAG).info(f"Detected emotion: {raw_text['emotion']}")
if raw_text.get("content"):
- logger.bind(tag=TAG).info(f"识别文本: {raw_text['content']}")
+ logger.bind(tag=TAG).info(f"Detected text: {raw_text['content']}")
if speaker_name:
- logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}")
+ logger.bind(tag=TAG).info(f"Identified speaker: {speaker_name}")
- # 转换为 JSON 字符串用于下游
+ # Convert to JSON string for downstream
enhanced_text = json.dumps(raw_text, ensure_ascii=False)
content_for_length_check = raw_text.get("content", "")
else:
- # 其他 ASR 返回的纯文本
+ # Plain text returned by other ASRs
if raw_text:
- logger.bind(tag=TAG).info(f"识别文本: {raw_text}")
+ logger.bind(tag=TAG).info(f"Detected text: {raw_text}")
if speaker_name:
- logger.bind(tag=TAG).info(f"识别说话人: {speaker_name}")
+ logger.bind(tag=TAG).info(f"Identified speaker: {speaker_name}")
- # 构建包含说话人信息的JSON字符串
+ # Build JSON string containing speaker info
enhanced_text = self._build_enhanced_text(raw_text, speaker_name)
content_for_length_check = raw_text
- # 性能监控
+ # Performance monitoring
total_time = time.monotonic() - total_start_time
- logger.bind(tag=TAG).debug(f"总处理耗时: {total_time:.3f}s")
+ logger.bind(tag=TAG).debug(f"Total processing time: {total_time:.3f}s")
- # 检查文本长度
+ # Check text length
text_len, _ = remove_punctuation_and_length(content_for_length_check)
self.stop_ws_connection()
if text_len > 0:
- # 使用自定义模块进行上报
+ # Use custom module for reporting
await startToChat(conn, enhanced_text)
enqueue_asr_report(conn, enhanced_text, asr_audio_task)
+ elif content_for_length_check:
+ logger.bind(tag=TAG).info(f"Ignored noise/hallucination: {content_for_length_check}")
except Exception as e:
- logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
- logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
+ logger.bind(tag=TAG).debug(f"Exception details: {traceback.format_exc()}")
def _build_enhanced_text(self, text: str, speaker_name: Optional[str]) -> str:
- """构建包含说话人信息的文本(仅用于纯文本ASR)"""
+ """Build text containing speaker info (only for plain text ASR)"""
if speaker_name and speaker_name.strip():
return json.dumps({
"speaker": speaker_name,
@@ -177,22 +212,22 @@ class ASRProviderBase(ABC):
return text
def _pcm_to_wav(self, pcm_data: bytes) -> bytes:
- """将PCM数据转换为WAV格式"""
+ """Convert PCM data to WAV format"""
if len(pcm_data) == 0:
- logger.bind(tag=TAG).warning("PCM数据为空,无法转换WAV")
+ logger.bind(tag=TAG).warning("PCM data is empty, cannot convert to WAV")
return b""
- # 确保数据长度是偶数(16位音频)
+ # Ensure data length is even (16-bit audio)
if len(pcm_data) % 2 != 0:
pcm_data = pcm_data[:-1]
- # 创建WAV文件头
+ # Create WAV file header
wav_buffer = io.BytesIO()
try:
with wave.open(wav_buffer, 'wb') as wav_file:
- wav_file.setnchannels(1) # 单声道
- wav_file.setsampwidth(2) # 16位
- wav_file.setframerate(16000) # 16kHz采样率
+ wav_file.setnchannels(1) # Mono
+ wav_file.setsampwidth(2) # 16-bit
+ wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
wav_buffer.seek(0)
@@ -200,17 +235,32 @@ class ASRProviderBase(ABC):
return wav_data
except Exception as e:
- logger.bind(tag=TAG).error(f"WAV转换失败: {e}")
+ logger.bind(tag=TAG).error(f"WAV conversion failed: {e}")
return b""
def stop_ws_connection(self):
pass
- def save_audio_to_file(self, pcm_data: List[bytes], session_id: str) -> str:
- """PCM数据保存为WAV文件"""
- module_name = __name__.split(".")[-1]
- file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
- file_path = os.path.join(self.output_dir, file_name)
+ def save_audio_to_file(self, pcm_data: List[bytes], session_id: str, client_id: str = None) -> str:
+ """Save PCM data as WAV file"""
+ if client_id:
+ # Client-specific directory: data/{client_id}/
+ # Get project root (assuming output_dir is relative to project root or use absolute path)
+ # We'll assume current working directory is project root or close enough
+ client_dir = os.path.join("data", client_id)
+ if not os.path.exists(client_dir):
+ os.makedirs(client_dir, exist_ok=True)
+
+ # Timestamp suffix: YYMMDD-hhmmss-ffffff
+ timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
+ file_name = f"ASR_{timestamp}.wav"
+ file_path = os.path.join(client_dir, file_name)
+ else:
+ # Fallback to default behavior
+ module_name = __name__.split(".")[-1]
+ file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
+ # output_dir from config
+ file_path = os.path.join(self.output_dir, file_name)
with wave.open(file_path, "wb") as wf:
wf.setnchannels(1)
@@ -220,21 +270,54 @@ class ASRProviderBase(ABC):
return file_path
+ def save_audio_background(self, pcm_data: List[bytes], session_id: str, client_id: str = None) -> str:
+ """Save PCM data as WAV file in background (non-blocking)"""
+ # Generate path first
+ if client_id:
+ client_dir = os.path.join("data", client_id)
+ if not os.path.exists(client_dir):
+ os.makedirs(client_dir, exist_ok=True)
+ timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
+ file_name = f"ASR_{timestamp}.wav"
+ file_path = os.path.join(client_dir, file_name)
+ else:
+ module_name = __name__.split(".")[-1]
+ file_name = f"asr_{module_name}_{session_id}_{uuid.uuid4()}.wav"
+ file_path = os.path.join(self.output_dir, file_name)
+
+ # Define write operation
+ def _write():
+ try:
+ # Ensure directory exists (again, just in case of race/thread safety)
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
+ with wave.open(file_path, "wb") as wf:
+ wf.setnchannels(1)
+ wf.setsampwidth(2)
+ wf.setframerate(16000)
+ wf.writeframes(b"".join(pcm_data))
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Background audio save failed: {e}")
+
+ # Fire and forget
+ threading.Thread(target=_write, daemon=True).start()
+
+ return file_path
+
@abstractmethod
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str, audio_format="opus"
+ self, opus_data: List[bytes], session_id: str, audio_format="opus", client_id: str = None
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ """Convert speech data to text"""
pass
@staticmethod
def decode_opus(opus_data: List[bytes]) -> List[bytes]:
- """将Opus音频数据解码为PCM数据"""
+ """Decode Opus audio data to PCM data"""
decoder = None
try:
decoder = opuslib_next.Decoder(16000, 1)
pcm_data = []
- buffer_size = 960 # 每次处理960个采样点 (60ms at 16kHz)
+ buffer_size = 960 # Process 960 samples each time (60ms at 16kHz)
for i, opus_packet in enumerate(opus_data):
try:
@@ -246,18 +329,18 @@ class ASRProviderBase(ABC):
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
- logger.bind(tag=TAG).warning(f"Opus解码错误,跳过数据包 {i}: {e}")
+ logger.bind(tag=TAG).warning(f"Opus decoding error, skipping packet {i}: {e}")
except Exception as e:
- logger.bind(tag=TAG).error(f"音频处理错误,数据包 {i}: {e}")
+ logger.bind(tag=TAG).error(f"Audio processing error, packet {i}: {e}")
return pcm_data
except Exception as e:
- logger.bind(tag=TAG).error(f"音频解码过程发生错误: {e}")
+ logger.bind(tag=TAG).error(f"Error during audio decoding process: {e}")
return []
finally:
if decoder is not None:
try:
del decoder
except Exception as e:
- logger.bind(tag=TAG).debug(f"释放decoder资源时出错: {e}")
+ logger.bind(tag=TAG).debug(f"Error releasing decoder resources: {e}")
diff --git a/main/xiaozhi-server/core/providers/asr/doubao.py b/main/xiaozhi-server/core/providers/asr/doubao.py
index f6cd79c62..399dc712d 100644
--- a/main/xiaozhi-server/core/providers/asr/doubao.py
+++ b/main/xiaozhi-server/core/providers/asr/doubao.py
@@ -37,9 +37,12 @@ def parse_response(res):
protocol_version(4 bits), header_size(4 bits),
message_type(4 bits), message_type_specific_flags(4 bits)
serialization_method(4 bits) message_compression(4 bits)
- reserved (8bits) 保留字段
- header_extensions 扩展头(大小等于 8 * 4 * (header_size - 1) )
- payload 类似与http 请求体
+ protocol_version(4 bits), header_size(4 bits),
+ message_type(4 bits), message_type_specific_flags(4 bits)
+ serialization_method(4 bits) message_compression(4 bits)
+ reserved (8bits)
+ header_extensions (size equals 8 * 4 * (header_size - 1))
+ payload (similar to http request body)
"""
protocol_version = res[0] >> 4
header_size = res[0] & 0x0F
@@ -97,7 +100,7 @@ class ASRProvider(ASRProviderBase):
self.success_code = 1000
self.seg_duration = 15000
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
@staticmethod
@@ -168,7 +171,7 @@ class ASRProvider(ASRProviderBase):
if (
"payload_msg" in result
and result["payload_msg"]["code"] != self.success_code
- and result["payload_msg"]["code"] != 1013 # 忽略无有效语音的错误
+ and result["payload_msg"]["code"] != 1013 # Ignore error for no valid voice
):
logger.bind(tag=TAG).error(f"ASR error: {result}")
return None
@@ -205,7 +208,7 @@ class ASRProvider(ASRProviderBase):
return result["payload_msg"]["result"][0]["text"]
return None
elif "payload_msg" in result and result["payload_msg"]["code"] == 1013:
- # 无有效语音,返回空字符串
+ # No valid voice, return empty string
return ""
else:
logger.bind(tag=TAG).error(f"ASR error: {result}")
@@ -234,38 +237,38 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ """Convert speech data to text"""
file_path = None
try:
- # 合并所有opus数据包
+ # Merge all opus data packets
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
file_path = self.save_audio_to_file(pcm_data, session_id)
- # 直接使用PCM数据
- # 计算分段大小 (单声道, 16bit, 16kHz采样率)
+ # Use PCM data directly
+ # Calculate segment size (mono, 16bit, 16kHz sample rate)
size_per_sec = 1 * 2 * 16000 # nchannels * sampwidth * framerate
segment_size = int(size_per_sec * self.seg_duration / 1000)
- # 语音识别
+ # Speech recognition
start_time = time.time()
text = await self._send_request(combined_pcm_data, segment_size)
if text:
logger.bind(tag=TAG).debug(
- f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
+ f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
return "", file_path
except Exception as e:
- logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
diff --git a/main/xiaozhi-server/core/providers/asr/doubao_stream.py b/main/xiaozhi-server/core/providers/asr/doubao_stream.py
index 3a726b083..5d621c196 100644
--- a/main/xiaozhi-server/core/providers/asr/doubao_stream.py
+++ b/main/xiaozhi-server/core/providers/asr/doubao_stream.py
@@ -21,9 +21,9 @@ class ASRProvider(ASRProviderBase):
self.decoder = opuslib_next.Decoder(16000, 1)
self.asr_ws = None
self.forward_task = None
- self.is_processing = False # 添加处理状态标志
+ self.is_processing = False # Add processing status flag
- # 配置参数
+ # Configuration parameters
self.appid = str(config.get("appid"))
self.cluster = config.get("cluster")
self.access_token = config.get("access_token")
@@ -32,7 +32,7 @@ class ASRProvider(ASRProviderBase):
self.output_dir = config.get("output_dir", "tmp/")
self.delete_audio_file = delete_audio_file
- # 火山引擎ASR配置
+ # Volcengine ASR configuration
enable_multilingual = config.get("enable_multilingual", False)
self.enable_multilingual = False if str(enable_multilingual).lower() == 'false' else True
if self.enable_multilingual:
@@ -47,7 +47,7 @@ class ASRProvider(ASRProviderBase):
self.format = config.get("format", "pcm")
self.codec = config.get("codec", "pcm")
self.rate = config.get("sample_rate", 16000)
- # language参数仅在多语种模式(bigmodel_nostream)下有效
+ # language parameter is only valid in multilingual mode (bigmodel_nostream)
self.language = config.get("language") if self.enable_multilingual else None
self.bits = config.get("bits", 16)
self.channel = config.get("channel", 1)
@@ -62,23 +62,23 @@ class ASRProvider(ASRProviderBase):
async def receive_audio(self, conn, audio, audio_have_voice):
conn.asr_audio.append(audio)
conn.asr_audio = conn.asr_audio[-10:]
- # 存储音频数据
+ # Store audio data
if not hasattr(conn, 'asr_audio_for_voiceprint'):
conn.asr_audio_for_voiceprint = []
conn.asr_audio_for_voiceprint.append(audio)
- # 当没有音频数据时处理完整语音片段
+ # Process complete voice segment when no audio data
if conn.client_listen_mode != "manual" and not audio and len(conn.asr_audio_for_voiceprint) > 0:
await self.handle_voice_stop(conn, conn.asr_audio_for_voiceprint)
conn.asr_audio_for_voiceprint = []
- # 如果本次有声音,且之前没有建立连接
+ # If voice detected, and connection not established
if audio_have_voice and self.asr_ws is None and not self.is_processing:
try:
self.is_processing = True
- # 建立新的WebSocket连接
+ # Establish new WebSocket connection
headers = self.token_auth() if self.auth_method == "token" else None
- logger.bind(tag=TAG).info(f"正在连接ASR服务,headers: {headers}")
+ logger.bind(tag=TAG).info(f"Connecting to ASR service, headers: {headers}")
self.asr_ws = await websockets.connect(
self.ws_url,
@@ -89,7 +89,7 @@ class ASRProvider(ASRProviderBase):
close_timeout=10,
)
- # 发送初始化请求
+ # Send initialization request
request_params = self.construct_request(str(uuid.uuid4()))
try:
payload_bytes = str.encode(json.dumps(request_params))
@@ -98,30 +98,30 @@ class ASRProvider(ASRProviderBase):
full_client_request.extend((len(payload_bytes)).to_bytes(4, "big"))
full_client_request.extend(payload_bytes)
- logger.bind(tag=TAG).info(f"发送初始化请求: {request_params}")
+ logger.bind(tag=TAG).info(f"Send initialization request: {request_params}")
await self.asr_ws.send(full_client_request)
- # 等待初始化响应
+ # Wait for initialization response
init_res = await self.asr_ws.recv()
result = self.parse_response(init_res)
- logger.bind(tag=TAG).info(f"收到初始化响应: {result}")
+ logger.bind(tag=TAG).info(f"Received initialization response: {result}")
- # 检查初始化响应
+ # Check initialization response
if "code" in result and result["code"] != 1000:
- error_msg = f"ASR服务初始化失败: {result.get('payload_msg', {}).get('error', '未知错误')}"
+ error_msg = f"ASR service initialization failed: {result.get('payload_msg', {}).get('error', 'Unknown error')}"
logger.bind(tag=TAG).error(error_msg)
raise Exception(error_msg)
except Exception as e:
- logger.bind(tag=TAG).error(f"发送初始化请求失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to send initialization request: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
raise e
- # 启动接收ASR结果的异步任务
+ # Start async task to receive ASR results
self.forward_task = asyncio.create_task(self._forward_asr_results(conn))
- # 发送缓存的音频数据
+ # Send cached audio data
if conn.asr_audio and len(conn.asr_audio) > 0:
for cached_audio in conn.asr_audio[-10:]:
try:
@@ -135,20 +135,20 @@ class ASRProvider(ASRProviderBase):
await self.asr_ws.send(audio_request)
except Exception as e:
logger.bind(tag=TAG).info(
- f"发送缓存音频数据时发生错误: {e}"
+ f"Error sending cached audio data: {e}"
)
except Exception as e:
- logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
self.is_processing = False
return
- # 发送当前音频数据
+ # Send current audio data
if self.asr_ws and self.is_processing:
try:
pcm_frame = self.decoder.decode(audio, 960)
@@ -158,52 +158,52 @@ class ASRProvider(ASRProviderBase):
audio_request.extend(payload)
await self.asr_ws.send(audio_request)
except Exception as e:
- logger.bind(tag=TAG).info(f"发送音频数据时发生错误: {e}")
+ logger.bind(tag=TAG).info(f"Error sending audio data: {e}")
async def _forward_asr_results(self, conn):
try:
while self.asr_ws and not conn.stop_event.is_set():
- # 获取当前连接的音频数据
+ # Get audio data of current connection
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
try:
response = await self.asr_ws.recv()
result = self.parse_response(response)
- logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
+ logger.bind(tag=TAG).debug(f"Received ASR result: {result}")
if "payload_msg" in result:
payload = result["payload_msg"]
- # 检查是否是错误码1013(无有效语音)
+ # Check if it is error code 1013 (no valid voice)
if "code" in payload and payload["code"] == 1013:
- # 静默处理,不记录错误日志
+ # Silent handling, do not log error
continue
if "result" in payload:
utterances = payload["result"].get("utterances", [])
- # 检查duration和空文本的情况
+ # Check duration and empty text cases
if (
- not self.enable_multilingual # 注意:多语种模式不返回中间结果,需要等待最终结果
+ not self.enable_multilingual # Note: Multilingual mode does not return intermediate results, need to wait for final result
and payload.get("audio_info", {}).get("duration", 0) > 2000
and not utterances
and not payload["result"].get("text")
and conn.client_listen_mode != "manual"
):
- logger.bind(tag=TAG).error(f"识别文本:空")
+ logger.bind(tag=TAG).error(f"Recognition text: Empty")
self.text = ""
conn.reset_vad_states()
- if len(audio_data) > 15: # 确保有足够音频数据
+ if len(audio_data) > 15: # Ensure enough audio data
await self.handle_voice_stop(conn, audio_data)
break
- # 专门处理没有文本的识别结果(手动模式下可能已经识别完成但是没松按键)
+ # Handle cases with no text result (Manual mode might have finished recognition but button not released)
elif not payload["result"].get("text") and not utterances:
- # 多语种模式会持续返回空文本,直到最后返回完整结果,所以需要排除
+ # Multilingual mode keeps returning empty text until final result, so exclude it
if self.enable_multilingual:
continue
if conn.client_listen_mode == "manual" and conn.client_voice_stop and len(audio_data) > 0:
- logger.bind(tag=TAG).debug("消息结束收到停止信号,触发处理")
+ logger.bind(tag=TAG).debug("Received stop signal at end of message, trigger processing")
await self.handle_voice_stop(conn, audio_data)
- # 清理音频缓存
+ # Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
@@ -212,51 +212,51 @@ class ASRProvider(ASRProviderBase):
if utterance.get("definite", False):
current_text = utterance["text"]
logger.bind(tag=TAG).info(
- f"识别到文本: {current_text}"
+ f"Recognized text: {current_text}"
)
- # 手动模式下累积识别结果
+ # Accumulate recognition results in manual mode
if conn.client_listen_mode == "manual":
if self.text:
self.text += current_text
else:
self.text = current_text
- # 在接收消息中途时收到停止信号
+ # Received stop signal in the middle of message
if conn.client_voice_stop and len(audio_data) > 0:
- logger.bind(tag=TAG).debug("消息中途收到停止信号,触发处理")
+ logger.bind(tag=TAG).debug("Received stop signal in middle of message, trigger processing")
await self.handle_voice_stop(conn, audio_data)
- # 清理音频缓存
+ # Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
else:
- # 自动模式下直接覆盖
+ # Overwrite directly in auto mode
self.text = current_text
conn.reset_vad_states()
- if len(audio_data) > 15: # 确保有足够音频数据
+ if len(audio_data) > 15: # Ensure enough audio data
await self.handle_voice_stop(conn, audio_data)
break
elif "error" in payload:
- error_msg = payload.get("error", "未知错误")
- logger.bind(tag=TAG).error(f"ASR服务返回错误: {error_msg}")
+ error_msg = payload.get("error", "Unknown error")
+ logger.bind(tag=TAG).error(f"ASR service returned error: {error_msg}")
break
except websockets.ConnectionClosed:
- logger.bind(tag=TAG).info("ASR服务连接已关闭")
+ logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
- logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
+ logger.bind(tag=TAG).error(f"Error processing ASR result: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
self.is_processing = False
break
except Exception as e:
- logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
+ logger.bind(tag=TAG).error(f"ASR result forwarding task error: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
finally:
if self.asr_ws:
await self.asr_ws.close()
@@ -275,18 +275,18 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False
async def _send_stop_request(self):
- """发送最后一个音频帧以通知服务器结束"""
+ """Send last audio frame to notify server to end"""
if self.asr_ws:
try:
- # 发送结束标记的音频帧(gzip压缩的空数据)
+ # Send audio frame with end marker (gzip compressed empty data)
empty_payload = gzip.compress(b"")
last_audio_request = bytearray(self.generate_last_audio_default_header())
last_audio_request.extend(len(empty_payload).to_bytes(4, "big"))
last_audio_request.extend(empty_payload)
await self.asr_ws.send(last_audio_request)
- logger.bind(tag=TAG).debug("已发送结束音频帧")
+ logger.bind(tag=TAG).debug("Sent end audio frame")
except Exception as e:
- logger.bind(tag=TAG).debug(f"发送结束音频帧时出错: {e}")
+ logger.bind(tag=TAG).debug(f"Error sending end audio frame: {e}")
def construct_request(self, reqid):
req = {
@@ -321,7 +321,7 @@ class ASRProvider(ASRProviderBase):
req["audio"]["language"] = self.language
logger.bind(tag=TAG).debug(
- f"构造请求参数: {json.dumps(req, ensure_ascii=False)}"
+ f"Construct request parameters: {json.dumps(req, ensure_ascii=False)}"
)
return req
@@ -372,16 +372,16 @@ class ASRProvider(ASRProviderBase):
def parse_response(self, res: bytes) -> dict:
try:
- # 检查响应长度
+ # Check response length
if len(res) < 4:
- logger.bind(tag=TAG).error(f"响应数据长度不足: {len(res)}")
- return {"error": "响应数据长度不足"}
+ logger.bind(tag=TAG).error(f"Insufficient response data length: {len(res)}")
+ return {"error": "Insufficient response data length"}
- # 获取消息头
+ # Get message header
header = res[:4]
message_type = header[1] >> 4
- # 如果是错误响应
+ # If error response
if message_type == 0x0F: # SERVER_ERROR_RESPONSE
code = int.from_bytes(res[4:8], "big", signed=False)
msg_length = int.from_bytes(res[8:12], "big", signed=False)
@@ -392,25 +392,25 @@ class ASRProvider(ASRProviderBase):
"payload_msg": error_msg,
}
- # 获取JSON数据(跳过12字节头部)
+ # Get JSON data (skip 12 bytes header)
try:
json_data = res[12:].decode("utf-8")
result = json.loads(json_data)
- logger.bind(tag=TAG).debug(f"成功解析JSON响应: {result}")
+ logger.bind(tag=TAG).debug(f"Successfully parsed JSON response: {result}")
return {"payload_msg": result}
except (UnicodeDecodeError, json.JSONDecodeError) as e:
- logger.bind(tag=TAG).error(f"JSON解析失败: {str(e)}")
- logger.bind(tag=TAG).error(f"原始数据: {res}")
+ logger.bind(tag=TAG).error(f"JSON parsing failed: {str(e)}")
+ logger.bind(tag=TAG).error(f"Original data: {res}")
raise
except Exception as e:
- logger.bind(tag=TAG).error(f"解析响应失败: {str(e)}")
- logger.bind(tag=TAG).error(f"原始响应数据: {res.hex()}")
+ logger.bind(tag=TAG).error(f"Failed to parse response: {str(e)}")
+ logger.bind(tag=TAG).error(f"Original response data: {res.hex()}")
raise
async def speech_to_text(self, opus_data, session_id, audio_format):
result = self.text
- self.text = "" # 清空text
+ self.text = "" # Clear text
return result, None
async def close(self):
diff --git a/main/xiaozhi-server/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py
index bba53f8a8..589a773e9 100644
--- a/main/xiaozhi-server/core/providers/asr/fun_local.py
+++ b/main/xiaozhi-server/core/providers/asr/fun_local.py
@@ -17,10 +17,10 @@ TAG = __name__
logger = setup_logging()
MAX_RETRIES = 2
-RETRY_DELAY = 1 # 重试延迟(秒)
+RETRY_DELAY = 1 # Retry delay (seconds)
-# 捕获标准输出
+# Capture standard output
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
@@ -32,7 +32,7 @@ class CaptureOutput:
self.output = self._output.getvalue()
self._output.close()
- # 将捕获到的内容通过 logger 输出
+ # Output captured content via logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
@@ -41,38 +41,39 @@ class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
- # 内存检测,要求大于2G
+ # Memory check, requires > 2G
min_mem_bytes = 2 * 1024 * 1024 * 1024
total_mem = psutil.virtual_memory().total
if total_mem < min_mem_bytes:
- logger.bind(tag=TAG).error(f"可用内存不足2G,当前仅有 {total_mem / (1024*1024):.2f} MB,可能无法启动FunASR")
+ logger.bind(tag=TAG).error(f"Available memory less than 2G, currently only {total_mem / (1024*1024):.2f} MB, FunASR might not start")
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
- self.output_dir = config.get("output_dir") # 修正配置键名
+ self.output_dir = config.get("output_dir") # Correct config key name
+ self.device = config.get("device", "cpu")
self.delete_audio_file = delete_audio_file
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
with CaptureOutput():
self.model = AutoModel(
model=self.model_dir,
vad_kwargs={"max_single_segment_time": 30000},
disable_update=True,
- hub="hf",
- # device="cuda:0", # 启用GPU加速
+ hub="ms",
+ device=self.device,
)
async def speech_to_text(
- self, opus_data: List[bytes], session_id: str, audio_format="opus"
+ self, opus_data: List[bytes], session_id: str, audio_format="opus", client_id: str = None
) -> Tuple[Optional[str], Optional[str]]:
- """语音转文本主处理逻辑"""
+ """Main speech-to-text processing logic"""
file_path = None
retry_count = 0
while retry_count < MAX_RETRIES:
try:
- # 合并所有opus数据包
+ # Merge all Opus packets
if audio_format == "pcm":
pcm_data = opus_data
else:
@@ -80,19 +81,19 @@ class ASRProvider(ASRProviderBase):
combined_pcm_data = b"".join(pcm_data)
- # 检查磁盘空间
+ # Check disk space
if not self.delete_audio_file:
free_space = shutil.disk_usage(self.output_dir).free
- if free_space < len(combined_pcm_data) * 2: # 预留2倍空间
- raise OSError("磁盘空间不足")
+ if free_space < len(combined_pcm_data) * 2: # Reserve 2x space
+ raise OSError("Insufficient disk space")
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
- file_path = self.save_audio_to_file(pcm_data, session_id)
+ file_path = self.save_audio_background(pcm_data, session_id, client_id=client_id)
- # 语音识别 - 使用线程池避免阻塞事件循环
+ # Speech recognition - use thread pool to avoid blocking event loop
start_time = time.time()
result = await asyncio.to_thread(
self.model.generate,
@@ -102,9 +103,26 @@ class ASRProvider(ASRProviderBase):
use_itn=True,
batch_size_s=60,
)
- text = lang_tag_filter(result[0]["text"])
+ # Parse content based on different model return structures
+ raw_text = ""
+ if isinstance(result, list) and len(result) > 0:
+ item = result[0]
+ if isinstance(item, dict):
+ raw_text = item.get("text", "")
+ elif isinstance(item, str):
+ raw_text = item
+ else:
+ raw_text = str(item)
+ elif isinstance(result, dict):
+ raw_text = result.get("text", "")
+ else:
+ raw_text = str(result)
+
+ text = lang_tag_filter(raw_text)
+
+ log_content = text["content"] if isinstance(text, dict) else text
logger.bind(tag=TAG).debug(
- f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text['content']}"
+ f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {log_content}"
)
return text, file_path
@@ -113,25 +131,25 @@ class ASRProvider(ASRProviderBase):
retry_count += 1
if retry_count >= MAX_RETRIES:
logger.bind(tag=TAG).error(
- f"语音识别失败(已重试{retry_count}次): {e}", exc_info=True
+ f"Speech recognition failed (retried {retry_count} times): {e}", exc_info=True
)
return "", file_path
logger.bind(tag=TAG).warning(
- f"语音识别失败,正在重试({retry_count}/{MAX_RETRIES}): {e}"
+ f"Speech recognition failed, retrying ({retry_count}/{MAX_RETRIES}): {e}"
)
time.sleep(RETRY_DELAY)
except Exception as e:
- logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
- # 文件清理逻辑
+ # File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
- logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
+ logger.bind(tag=TAG).debug(f"Deleted temp audio file: {file_path}")
except Exception as e:
logger.bind(tag=TAG).error(
- f"文件删除失败: {file_path} | 错误: {e}"
+ f"File deletion failed: {file_path} | Error: {e}"
)
diff --git a/main/xiaozhi-server/core/providers/asr/fun_server.py b/main/xiaozhi-server/core/providers/asr/fun_server.py
index c6674df98..2b3167d94 100644
--- a/main/xiaozhi-server/core/providers/asr/fun_server.py
+++ b/main/xiaozhi-server/core/providers/asr/fun_server.py
@@ -116,7 +116,7 @@ class ASRProvider(ASRProviderBase):
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
diff --git a/main/xiaozhi-server/core/providers/asr/openai.py b/main/xiaozhi-server/core/providers/asr/openai.py
index 5c6e849c0..dfd79df89 100644
--- a/main/xiaozhi-server/core/providers/asr/openai.py
+++ b/main/xiaozhi-server/core/providers/asr/openai.py
@@ -32,7 +32,7 @@ class ASRProvider(ASRProviderBase):
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
- f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}"
+ f"Audio file saved in: {time.time() - start_time:.3f}s | Path: {file_path}"
)
logger.bind(tag=TAG).info(f"file path: {file_path}")
@@ -40,13 +40,13 @@ class ASRProvider(ASRProviderBase):
"Authorization": f"Bearer {self.api_key}",
}
- # 使用data参数传递模型名称
+ # Use data parameter to pass model name
data = {
"model": self.model
}
- with open(file_path, "rb") as audio_file: # 使用with语句确保文件关闭
+ with open(file_path, "rb") as audio_file: # Use with statement to ensure file closure
files = {
"file": audio_file
}
@@ -59,24 +59,24 @@ class ASRProvider(ASRProviderBase):
headers=headers
)
logger.bind(tag=TAG).debug(
- f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {response.text}"
+ f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {response.text}"
)
if response.status_code == 200:
text = response.json().get("text", "")
return text, file_path
else:
- raise Exception(f"API请求失败: {response.status_code} - {response.text}")
+ raise Exception(f"API request failed: {response.status_code} - {response.text}")
except Exception as e:
- logger.bind(tag=TAG).error(f"语音识别失败: {e}")
+ logger.bind(tag=TAG).error(f"Speech recognition failed: {e}")
return "", None
finally:
- # 文件清理逻辑
+ # File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
- logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
+ logger.bind(tag=TAG).debug(f"Temporary audio file deleted: {file_path}")
except Exception as e:
- logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
+ logger.bind(tag=TAG).error(f"Failed to delete file: {file_path} | Error: {e}")
diff --git a/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py b/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py
index 51c84a376..2b683fdd5 100644
--- a/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py
+++ b/main/xiaozhi-server/core/providers/asr/qwen3_asr_flash.py
@@ -13,59 +13,67 @@ logger = setup_logging()
class ASRProvider(ASRProviderBase):
def __init__(self, config: dict, delete_audio_file: bool):
super().__init__()
- # 音频文件上传类型,流式文本识别输出
+ def __init__(self, config: dict, delete_audio_file: bool):
+ super().__init__()
+ # Audio file upload type, stream text recognition output
self.interface_type = InterfaceType.NON_STREAM
- """Qwen3-ASR-Flash ASR初始化"""
+ """Qwen3-ASR-Flash ASR initialization"""
- # 配置参数
+ # Configuration parameters
self.api_key = config.get("api_key")
if not self.api_key:
- raise ValueError("Qwen3-ASR-Flash 需要配置 api_key")
+ raise ValueError("Qwen3-ASR-Flash needs api_key configuration")
self.model_name = config.get("model_name", "qwen3-asr-flash")
self.output_dir = config.get("output_dir", "./audio_output")
self.delete_audio_file = delete_audio_file
# ASR选项配置
- self.enable_lid = config.get("enable_lid", True) # 自动语种检测
- self.enable_itn = config.get("enable_itn", True) # 逆文本归一化
- self.language = config.get("language", None) # 指定语种,默认自动检测
- self.context = config.get("context", "") # 上下文信息,用于提高识别准确率
+ self.delete_audio_file = delete_audio_file
- # 确保输出目录存在
+ # ASR option configuration
+ self.enable_lid = config.get("enable_lid", True) # Auto language detection
+ self.enable_itn = config.get("enable_itn", True) # Inverse text normalization
+ self.language = config.get("language", None) # Specify language, default auto detect
+ self.context = config.get("context", "") # Context info to improve recognition accuracy
+
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
def _prepare_audio_file(self, pcm_data: bytes) -> str:
- """将PCM数据转换为WAV文件并返回文件路径"""
+ """Convert PCM data to WAV file and return file path"""
try:
import wave
- # 创建临时WAV文件
+ # Create temporary WAV file
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
temp_path = temp_file.name
- # 写入WAV格式
+ # Write WAV format
with wave.open(temp_path, 'wb') as wav_file:
- wav_file.setnchannels(1) # 单声道
- wav_file.setsampwidth(2) # 16位
- wav_file.setframerate(16000) # 16kHz采样率
+ wav_file.setnchannels(1) # Mono
+ wav_file.setsampwidth(2) # 16-bit
+ wav_file.setframerate(16000) # 16kHz sample rate
wav_file.writeframes(pcm_data)
return temp_path
except Exception as e:
- logger.bind(tag=tag).error(f"音频文件准备失败: {e}")
+ logger.bind(tag=tag).error(f"Failed to prepare audio file: {e}")
return None
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ async def speech_to_text(
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """Convert speech data to text"""
temp_file_path = None
file_path = None
try:
- # 解码音频数据
+ # Decode audio data
if audio_format == "pcm":
pcm_data = opus_data
else:
@@ -73,19 +81,19 @@ class ASRProvider(ASRProviderBase):
combined_pcm_data = b"".join(pcm_data)
if len(combined_pcm_data) == 0:
- logger.bind(tag=tag).warning("音频数据为空")
+ logger.bind(tag=tag).warning("Audio data is empty")
return "", None
- # 准备音频文件
+ # Prepare audio file
temp_file_path = self._prepare_audio_file(combined_pcm_data)
if not temp_file_path:
return "", None
- # 保存音频文件(如果需要)
+ # Save audio file (if needed)
if not self.delete_audio_file:
file_path = self.save_audio_to_file(pcm_data, session_id)
- # 构造请求消息
+ # Construct request messages
messages = [
{
"role": "user",
@@ -95,7 +103,7 @@ class ASRProvider(ASRProviderBase):
}
]
- # 如果有上下文信息,添加system消息
+ # If context info exists, add system message
if self.context:
messages.insert(0, {
"role": "system",
@@ -104,20 +112,20 @@ class ASRProvider(ASRProviderBase):
]
})
- # 准备ASR选项
+ # Prepare ASR options
asr_options = {
"enable_lid": self.enable_lid,
"enable_itn": self.enable_itn
}
- # 如果指定了语种,添加到选项中
+ # If language specified, add to options
if self.language:
asr_options["language"] = self.language
- # 设置API密钥
+ # Set API key
dashscope.api_key = self.api_key
- # 发送流式请求
+ # Send streaming request
response = dashscope.MultiModalConversation.call(
model=self.model_name,
messages=messages,
@@ -126,12 +134,12 @@ class ASRProvider(ASRProviderBase):
stream=True
)
- # 处理流式响应
+ # Handle streaming response
full_text = ""
for chunk in response:
try:
text = chunk["output"]["choices"][0]["message"].content[0]["text"]
- # 更新为最新的完整文本
+ # Update to latest complete text
full_text = text.strip()
except:
pass
@@ -139,13 +147,13 @@ class ASRProvider(ASRProviderBase):
return full_text, file_path
except Exception as e:
- logger.bind(tag=tag).error(f"语音识别失败: {e}")
+ logger.bind(tag=tag).error(f"Speech recognition failed: {e}")
return "", file_path
finally:
- # 清理临时文件
+ # Clean up temporary file
if temp_file_path and os.path.exists(temp_file_path):
try:
os.unlink(temp_file_path)
except Exception as e:
- logger.bind(tag=tag).warning(f"清理临时文件失败: {e}")
\ No newline at end of file
+ logger.bind(tag=tag).warning(f"Failed to clean up temporary file: {e}")
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
index c34909b24..b0c305e47 100644
--- a/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
+++ b/main/xiaozhi-server/core/providers/asr/sherpa_onnx_local.py
@@ -17,7 +17,7 @@ TAG = __name__
logger = setup_logging()
-# 捕获标准输出
+# Capture standard output
class CaptureOutput:
def __enter__(self):
self._output = io.StringIO()
@@ -29,7 +29,7 @@ class CaptureOutput:
self.output = self._output.getvalue()
self._output.close()
- # 将捕获到的内容通过 logger 输出
+ # Log captured content through logger
if self.output:
logger.bind(tag=TAG).info(self.output.strip())
@@ -40,23 +40,23 @@ class ASRProvider(ASRProviderBase):
self.interface_type = InterfaceType.LOCAL
self.model_dir = config.get("model_dir")
self.output_dir = config.get("output_dir")
- self.model_type = config.get("model_type", "sense_voice") # 支持 paraformer
+ self.model_type = config.get("model_type", "sense_voice") # Support paraformer
self.delete_audio_file = delete_audio_file
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
- # 初始化模型文件路径
+ # Initialize model file paths
model_files = {
"model.int8.onnx": os.path.join(self.model_dir, "model.int8.onnx"),
"tokens.txt": os.path.join(self.model_dir, "tokens.txt"),
}
- # 下载并检查模型文件
+ # Download and check model files
try:
for file_name, file_path in model_files.items():
if not os.path.isfile(file_path):
- logger.bind(tag=TAG).info(f"正在下载模型文件: {file_name}")
+ logger.bind(tag=TAG).info(f"Downloading model file: {file_name}")
model_file_download(
model_id="pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue",
file_path=file_name,
@@ -64,13 +64,13 @@ class ASRProvider(ASRProviderBase):
)
if not os.path.isfile(file_path):
- raise FileNotFoundError(f"模型文件下载失败: {file_path}")
+ raise FileNotFoundError(f"Failed to download model file: {file_path}")
self.model_path = model_files["model.int8.onnx"]
self.tokens_path = model_files["tokens.txt"]
except Exception as e:
- logger.bind(tag=TAG).error(f"模型文件处理失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Model file processing failed: {str(e)}")
raise
with CaptureOutput():
@@ -123,10 +123,10 @@ class ASRProvider(ASRProviderBase):
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
- """语音转文本主处理逻辑"""
+ """Main logic for speech to text"""
file_path = None
try:
- # 保存音频文件
+ # Save audio file
start_time = time.time()
if audio_format == "pcm":
pcm_data = opus_data
@@ -134,10 +134,10 @@ class ASRProvider(ASRProviderBase):
pcm_data = self.decode_opus(opus_data)
file_path = self.save_audio_to_file(pcm_data, session_id)
logger.bind(tag=TAG).debug(
- f"音频文件保存耗时: {time.time() - start_time:.3f}s | 路径: {file_path}"
+ f"Audio file saved in: {time.time() - start_time:.3f}s | Path: {file_path}"
)
- # 语音识别
+ # Speech recognition
start_time = time.time()
s = self.model.create_stream()
samples, sample_rate = self.read_wave(file_path)
@@ -145,19 +145,19 @@ class ASRProvider(ASRProviderBase):
self.model.decode_stream(s)
text = s.result.text
logger.bind(tag=TAG).debug(
- f"语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text}"
+ f"Speech recognition time: {time.time() - start_time:.3f}s | Result: {text}"
)
return text, file_path
except Exception as e:
- logger.bind(tag=TAG).error(f"语音识别失败: {e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Speech recognition failed: {e}", exc_info=True)
return "", file_path
finally:
- # 文件清理逻辑
+ # File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
- logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
+ logger.bind(tag=TAG).debug(f"Temporary audio file deleted: {file_path}")
except Exception as e:
- logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
+ logger.bind(tag=TAG).error(f"Failed to delete file: {file_path} | Error: {e}")
diff --git a/main/xiaozhi-server/core/providers/asr/tencent.py b/main/xiaozhi-server/core/providers/asr/tencent.py
index 1fd1c6f42..26a454c9e 100644
--- a/main/xiaozhi-server/core/providers/asr/tencent.py
+++ b/main/xiaozhi-server/core/providers/asr/tencent.py
@@ -18,7 +18,7 @@ logger = setup_logging()
class ASRProvider(ASRProviderBase):
API_URL = "https://asr.tencentcloudapi.com"
API_VERSION = "2019-06-14"
- FORMAT = "pcm" # 支持的音频格式:pcm, wav, mp3
+ FORMAT = "pcm" # Supported audio formats: pcm, wav, mp3
def __init__(self, config: dict, delete_audio_file: bool = True):
super().__init__()
@@ -28,103 +28,107 @@ class ASRProvider(ASRProviderBase):
self.output_dir = config.get("output_dir")
self.delete_audio_file = delete_audio_file
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
async def speech_to_text(
self, opus_data: List[bytes], session_id: str, audio_format="opus"
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ async def speech_to_text(
+ self, opus_data: List[bytes], session_id: str, audio_format="opus"
+ ) -> Tuple[Optional[str], Optional[str]]:
+ """Convert speech data to text"""
if not opus_data:
- logger.bind(tag=TAG).warning("音频数据为空!")
+ logger.bind(tag=TAG).warning("Audio data is empty!")
return None, None
file_path = None
try:
- # 检查配置是否已设置
+ # Check if configuration is set
if not self.secret_id or not self.secret_key:
- logger.bind(tag=TAG).error("腾讯云语音识别配置未设置,无法进行识别")
+ logger.bind(tag=TAG).error("Tencent Cloud Speech Recognition configuration not set, cannot perform recognition")
return None, file_path
- # 将Opus音频数据解码为PCM
+ # Decode Opus audio data to PCM
if audio_format == "pcm":
pcm_data = opus_data
else:
pcm_data = self.decode_opus(opus_data)
combined_pcm_data = b"".join(pcm_data)
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if self.delete_audio_file:
pass
else:
self.save_audio_to_file(pcm_data, session_id)
- # 将音频数据转换为Base64编码
+ # Convert audio data to Base64 encoding
base64_audio = base64.b64encode(combined_pcm_data).decode("utf-8")
- # 构建请求体
+ # Build request body
request_body = self._build_request_body(base64_audio)
- # 获取认证头
+ # Get auth headers
timestamp, authorization = self._get_auth_headers(request_body)
- # 发送请求
+ # Send request
start_time = time.time()
result = self._send_request(request_body, timestamp, authorization)
if result:
logger.bind(tag=TAG).debug(
- f"腾讯云语音识别耗时: {time.time() - start_time:.3f}s | 结果: {result}"
+ f"Tencent Cloud speech recognition time: {time.time() - start_time:.3f}s | Result: {result}"
)
return result, file_path
except Exception as e:
- logger.bind(tag=TAG).error(f"处理音频时发生错误!{e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Error occurred while processing audio! {e}", exc_info=True)
return None, file_path
def _build_request_body(self, base64_audio: str) -> str:
- """构建请求体"""
+ def _build_request_body(self, base64_audio: str) -> str:
+ """Build request body"""
request_map = {
"ProjectId": 0,
- "SubServiceType": 2, # 一句话识别
- "EngSerViceType": "16k_zh", # 中文普通话通用
- "SourceType": 1, # 音频数据来源为语音文件
- "VoiceFormat": self.FORMAT, # 音频格式
- "Data": base64_audio, # Base64编码的音频数据
- "DataLen": len(base64_audio), # 数据长度
+ "SubServiceType": 2, # Sentence recognition
+ "EngSerViceType": "16k_zh", # Mandarin Chinese general
+ "SourceType": 1, # Audio data source is voice file
+ "VoiceFormat": self.FORMAT, # Audio format
+ "Data": base64_audio, # Base64 encoded audio data
+ "DataLen": len(base64_audio), # Data length
}
return json.dumps(request_map)
def _get_auth_headers(self, request_body: str) -> Tuple[str, str]:
- """获取认证头"""
+ """Get auth headers"""
try:
- # 获取当前UTC时间戳
+ # Get current UTC timestamp
now = datetime.now(timezone.utc)
timestamp = str(int(now.timestamp()))
date = now.strftime("%Y-%m-%d")
- # 服务名称必须是 "asr"
+ # Service name must be "asr"
service = "asr"
- # 拼接凭证范围
+ # Splicing credential scope
credential_scope = f"{date}/{service}/tc3_request"
- # 使用TC3-HMAC-SHA256签名方法
+ # Use TC3-HMAC-SHA256 signature method
algorithm = "TC3-HMAC-SHA256"
- # 构建规范请求字符串
+ # Build canonical request string
http_request_method = "POST"
canonical_uri = "/"
canonical_query_string = ""
- # 注意:头部信息需要按照ASCII升序排列,且key和value都转为小写
- # 必须包含content-type和host头部
+ # Note: Header information needs to be arranged in ASCII ascending order, and keys and values are converted to lowercase
+ # Must include content-type and host headers
content_type = "application/json; charset=utf-8"
host = "asr.tencentcloudapi.com"
- action = "SentenceRecognition" # 接口名称
+ action = "SentenceRecognition" # Interface name
- # 构建规范头部信息,注意顺序和格式
+ # Build canonical header information, pay attention to order and format
canonical_headers = (
f"content-type:{content_type.lower()}\n"
+ f"host:{host.lower()}\n"
@@ -133,10 +137,10 @@ class ASRProvider(ASRProviderBase):
signed_headers = "content-type;host;x-tc-action"
- # 请求体哈希值
+ # Request body hash value
payload_hash = self._sha256_hex(request_body)
- # 构建规范请求字符串
+ # Build canonical request string
canonical_request = (
f"{http_request_method}\n"
+ f"{canonical_uri}\n"
@@ -146,10 +150,10 @@ class ASRProvider(ASRProviderBase):
+ f"{payload_hash}"
)
- # 计算规范请求的哈希值
+ # Calculate hash value of canonical request
hashed_canonical_request = self._sha256_hex(canonical_request)
- # 构建待签名字符串
+ # Build string to sign
string_to_sign = (
f"{algorithm}\n"
+ f"{timestamp}\n"
@@ -157,17 +161,17 @@ class ASRProvider(ASRProviderBase):
+ f"{hashed_canonical_request}"
)
- # 计算签名密钥
+ # Calculate signature key
secret_date = self._hmac_sha256(f"TC3{self.secret_key}", date)
secret_service = self._hmac_sha256(secret_date, service)
secret_signing = self._hmac_sha256(secret_service, "tc3_request")
- # 计算签名
+ # Calculate signature
signature = self._bytes_to_hex(
self._hmac_sha256(secret_signing, string_to_sign)
)
- # 构建授权头
+ # Build authorization header
authorization = (
f"{algorithm} "
+ f"Credential={self.secret_id}/{credential_scope}, "
@@ -178,13 +182,13 @@ class ASRProvider(ASRProviderBase):
return timestamp, authorization
except Exception as e:
- logger.bind(tag=TAG).error(f"生成认证头失败: {e}", exc_info=True)
- raise RuntimeError(f"生成认证头失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to generate auth header: {e}", exc_info=True)
+ raise RuntimeError(f"Failed to generate auth header: {e}")
def _send_request(
self, request_body: str, timestamp: str, authorization: str
) -> Optional[str]:
- """发送请求到腾讯云API"""
+ """Send request to Tencent Cloud API"""
headers = {
"Content-Type": "application/json; charset=utf-8",
"Host": "asr.tencentcloudapi.com",
@@ -199,40 +203,40 @@ class ASRProvider(ASRProviderBase):
response = requests.post(self.API_URL, headers=headers, data=request_body)
if not response.ok:
- raise IOError(f"请求失败: {response.status_code} {response.reason}")
+ raise IOError(f"Request failed: {response.status_code} {response.reason}")
response_json = response.json()
- # 检查是否有错误
+ # Check for errors
if "Response" in response_json and "Error" in response_json["Response"]:
error = response_json["Response"]["Error"]
error_code = error["Code"]
error_message = error["Message"]
- raise IOError(f"API返回错误: {error_code}: {error_message}")
+ raise IOError(f"API returned error: {error_code}: {error_message}")
- # 提取识别结果
+ # Extract recognition result
if "Response" in response_json and "Result" in response_json["Response"]:
return response_json["Response"]["Result"]
else:
- logger.bind(tag=TAG).warning(f"响应中没有识别结果: {response_json}")
+ logger.bind(tag=TAG).warning(f"No recognition result in response: {response_json}")
return ""
except Exception as e:
- logger.bind(tag=TAG).error(f"发送请求失败: {e}", exc_info=True)
+ logger.bind(tag=TAG).error(f"Failed to send request: {e}", exc_info=True)
return None
def _sha256_hex(self, data: str) -> str:
- """计算字符串的SHA256哈希值"""
+ """Calculate SHA256 hash of a string"""
digest = hashlib.sha256(data.encode("utf-8")).digest()
return self._bytes_to_hex(digest)
def _hmac_sha256(self, key, data: str) -> bytes:
- """计算HMAC-SHA256"""
+ """Calculate HMAC-SHA256"""
if isinstance(key, str):
key = key.encode("utf-8")
return hmac.new(key, data.encode("utf-8"), hashlib.sha256).digest()
def _bytes_to_hex(self, bytes_data: bytes) -> str:
- """字节数组转十六进制字符串"""
+ """Convert byte array to hexadecimal string"""
return "".join(f"{b:02x}" for b in bytes_data)
diff --git a/main/xiaozhi-server/core/providers/asr/utils.py b/main/xiaozhi-server/core/providers/asr/utils.py
index d1f538aeb..39780df0e 100644
--- a/main/xiaozhi-server/core/providers/asr/utils.py
+++ b/main/xiaozhi-server/core/providers/asr/utils.py
@@ -4,7 +4,7 @@ from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
-EMOTION_EMOJI_MAP = {
+EMOTION__MAP = {
"HAPPY": "🙂",
"SAD": "😔",
"ANGRY": "😡",
@@ -14,7 +14,7 @@ EMOTION_EMOJI_MAP = {
"SURPRISED": "😲",
"EMO_UNKNOWN": "😶", # 未知情绪默认用中性表情
}
-# EVENT_EMOJI_MAP = {
+# EVENT__MAP = {
# "<|BGM|>": "🎼",
# "<|Speech|>": "",
# "<|Applause|>": "👏",
@@ -33,15 +33,15 @@ def lang_tag_filter(text: str) -> dict | str:
text: ASR 识别的原始文本,可能包含多种标签
Returns:
- dict: {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好"} 如果有标签
+ dict: {"language": "zh", "emotion": "SAD", "": "😔", "content": "你好"} 如果有标签
str: 纯文本,如果没有标签
Examples:
FunASR 输出格式:<|语种|><|情绪|><|事件|><|其他选项|>原文
>>> lang_tag_filter("<|zh|><|SAD|><|Speech|><|withitn|>你好啊,测试测试。")
- {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好啊,测试测试。"}
+ {"language": "zh", "emotion": "SAD", "": "😔", "content": "你好啊,测试测试。"}
>>> lang_tag_filter("<|en|><|HAPPY|><|Speech|><|withitn|>Hello hello.")
- {"language": "en", "emotion": "HAPPY", "emoji": "🙂", "content": "Hello hello."}
+ {"language": "en", "emotion": "HAPPY", "": "🙂", "content": "Hello hello."}
>>> lang_tag_filter("plain text")
"plain text"
"""
@@ -68,12 +68,12 @@ def lang_tag_filter(text: str) -> dict | str:
# "event": event,
}
- # 添加 emoji 映射
- if emotion in EMOTION_EMOJI_MAP:
- result["emotion"] = EMOTION_EMOJI_MAP[emotion]
+ # 添加 映射
+ if emotion in EMOTION__MAP:
+ result["emotion"] = EMOTION__MAP[emotion]
# 事件标签暂不使用
- # if event in EVENT_EMOJI_MAP:
- # result["event"] = EVENT_EMOJI_MAP[event]
+ # if event in EVENT__MAP:
+ # result["event"] = EVENT__MAP[event]
return result
diff --git a/main/xiaozhi-server/core/providers/asr/vosk.py b/main/xiaozhi-server/core/providers/asr/vosk.py
index 19d318225..1544deacf 100644
--- a/main/xiaozhi-server/core/providers/asr/vosk.py
+++ b/main/xiaozhi-server/core/providers/asr/vosk.py
@@ -18,66 +18,66 @@ class ASRProvider(ASRProviderBase):
self.output_dir = config.get("output_dir", "tmp/")
self.delete_audio_file = delete_audio_file
- # 初始化VOSK模型
+ # Initialize VOSK model
self.model = None
self.recognizer = None
self._load_model()
- # 确保输出目录存在
+ # Ensure output directory exists
os.makedirs(self.output_dir, exist_ok=True)
def _load_model(self):
- """加载VOSK模型"""
+ """Load VOSK model"""
try:
if not os.path.exists(self.model_path):
- raise FileNotFoundError(f"VOSK模型路径不存在: {self.model_path}")
+ raise FileNotFoundError(f"VOSK model path does not exist: {self.model_path}")
- logger.bind(tag=TAG).info(f"正在加载VOSK模型: {self.model_path}")
+ logger.bind(tag=TAG).info(f"Loading VOSK model: {self.model_path}")
self.model = vosk.Model(self.model_path)
- # 初始化VOSK识别器(采样率必须为16kHz)
+ # Initialize VOSK recognizer (sample rate must be 16kHz)
self.recognizer = vosk.KaldiRecognizer(self.model, 16000)
- logger.bind(tag=TAG).info("VOSK模型加载成功")
+ logger.bind(tag=TAG).info("VOSK model loaded successfully")
except Exception as e:
- logger.bind(tag=TAG).error(f"加载VOSK模型失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to load VOSK model: {e}")
raise
async def speech_to_text(
self, audio_data: List[bytes], session_id: str, audio_format: str = "opus"
) -> Tuple[Optional[str], Optional[str]]:
- """将语音数据转换为文本"""
+ """Convert speech data to text"""
file_path = None
try:
- # 检查模型是否加载成功
+ # Check if model loaded successfully
if not self.model:
- logger.bind(tag=TAG).error("VOSK模型未加载,无法进行识别")
+ logger.bind(tag=TAG).error("VOSK model not loaded, cannot perform recognition")
return "", None
- # 解码音频(如果原始格式是Opus)
+ # Decode audio (if original format is Opus)
if audio_format == "pcm":
pcm_data = audio_data
else:
pcm_data = self.decode_opus(audio_data)
if not pcm_data:
- logger.bind(tag=TAG).warning("解码后的PCM数据为空,无法进行识别")
+ logger.bind(tag=TAG).warning("Decoded PCM data is empty, cannot perform recognition")
return "", None
- # 合并PCM数据
+ # Combine PCM data
combined_pcm_data = b"".join(pcm_data)
if len(combined_pcm_data) == 0:
- logger.bind(tag=TAG).warning("合并后的PCM数据为空")
+ logger.bind(tag=TAG).warning("Combined PCM data is empty")
return "", None
- # 判断是否保存为WAV文件
+ # Determine whether to save as WAV file
if not self.delete_audio_file:
- file_path = self.save_audio_to_file(pcm_data, session_id)
+ file_path = self.save_audio_background(pcm_data, session_id)
start_time = time.time()
-
- # 进行识别(VOSK推荐每次送入2000字节的数据)
+
+ # Perform recognition (VOSK recommends sending 2000 bytes of data each time)
chunk_size = 2000
text_result = ""
@@ -89,26 +89,26 @@ class ASRProvider(ASRProviderBase):
if text:
text_result += text + " "
- # 获取最终结果
+ # Get final result
final_result = json.loads(self.recognizer.FinalResult())
final_text = final_result.get('text', '')
if final_text:
text_result += final_text
logger.bind(tag=TAG).debug(
- f"VOSK语音识别耗时: {time.time() - start_time:.3f}s | 结果: {text_result.strip()}"
+ f"VOSK speech recognition time: {time.time() - start_time:.3f}s | Result: {text_result.strip()}"
)
return text_result.strip(), file_path
except Exception as e:
- logger.bind(tag=TAG).error(f"VOSK语音识别失败: {e}")
+ logger.bind(tag=TAG).error(f"VOSK speech recognition failed: {e}")
return "", None
finally:
- # 文件清理逻辑
+ # File cleanup logic
if self.delete_audio_file and file_path and os.path.exists(file_path):
try:
os.remove(file_path)
- logger.bind(tag=TAG).debug(f"已删除临时音频文件: {file_path}")
+ logger.bind(tag=TAG).debug(f"Removed temporary audio file: {file_path}")
except Exception as e:
- logger.bind(tag=TAG).error(f"文件删除失败: {file_path} | 错误: {e}")
+ logger.bind(tag=TAG).error(f"Failed to delete file: {file_path} | Error: {e}")
diff --git a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py
index b7e7886ea..fd62d20a2 100644
--- a/main/xiaozhi-server/core/providers/asr/xunfei_stream.py
+++ b/main/xiaozhi-server/core/providers/asr/xunfei_stream.py
@@ -18,10 +18,10 @@ from core.providers.asr.dto.dto import InterfaceType
TAG = __name__
logger = setup_logging()
-# 帧状态常量
-STATUS_FIRST_FRAME = 0 # 第一帧的标识
-STATUS_CONTINUE_FRAME = 1 # 中间帧标识
-STATUS_LAST_FRAME = 2 # 最后一帧的标识
+# Frame status constants
+STATUS_FIRST_FRAME = 0 # First frame identifier
+STATUS_CONTINUE_FRAME = 1 # Intermediate frame identifier
+STATUS_LAST_FRAME = 2 # Last frame identifier
class ASRProvider(ASRProviderBase):
@@ -36,15 +36,17 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False
self.server_ready = False
- # 讯飞配置
+ self.server_ready = False
+
+ # Xunfei config
self.app_id = config.get("app_id")
self.api_key = config.get("api_key")
self.api_secret = config.get("api_secret")
if not all([self.app_id, self.api_key, self.api_secret]):
- raise ValueError("必须提供app_id、api_key和api_secret")
+ raise ValueError("Must provide app_id, api_key and api_secret")
- # 识别参数
+ # Recognition parameters
self.iat_params = {
"domain": config.get("domain", "slm"),
"language": config.get("language", "zh_cn"),
@@ -56,18 +58,22 @@ class ASRProvider(ASRProviderBase):
self.delete_audio_file = delete_audio_file
def create_url(self) -> str:
- """生成认证URL"""
+ """Generate Auth URL"""
url = "ws://iat.cn-huabei-1.xf-yun.com/v1"
- # 生成RFC1123格式的时间戳
+ # Generate RFC1123 format timestamp
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
- # 拼接字符串
+ date = format_date_time(mktime(now.timetuple()))
+
+ # Concatenate string
signature_origin = "host: " + "iat.cn-huabei-1.xf-yun.com" + "\n"
signature_origin += "date: " + date + "\n"
signature_origin += "GET " + "/v1 " + "HTTP/1.1"
- # 进行hmac-sha256进行加密
+ signature_origin += "GET " + "/v1 " + "HTTP/1.1"
+
+ # Encrypt with hmac-sha256
signature_sha = hmac.new(
self.api_secret.encode("utf-8"),
signature_origin.encode("utf-8"),
@@ -83,14 +89,18 @@ class ASRProvider(ASRProviderBase):
encoding="utf-8"
)
- # 将请求的鉴权参数组合为字典
+ )
+
+ # Combine auth parameters into dictionary
v = {
"authorization": authorization,
"date": date,
"host": "iat.cn-huabei-1.xf-yun.com",
}
- # 拼接鉴权参数,生成url
+ }
+
+ # Concatenate auth parameters to generate URL
url = url + "?" + urlencode(v)
return url
@@ -98,41 +108,43 @@ class ASRProvider(ASRProviderBase):
await super().open_audio_channels(conn)
async def receive_audio(self, conn, audio, audio_have_voice):
- # 先调用父类方法处理基础逻辑
+ # Call parent method to handle basic logic
await super().receive_audio(conn, audio, audio_have_voice)
- # 存储音频数据用于声纹识别
+ # Store audio data for voiceprint recognition
if not hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
conn.asr_audio_for_voiceprint.append(audio)
- # 如果本次有声音,且之前没有建立连接
+ # If voice detected, and connection not established
if audio_have_voice and self.asr_ws is None and not self.is_processing:
try:
await self._start_recognition(conn)
except Exception as e:
- logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
await self._cleanup()
return
- # 发送当前音频数据
+ return
+
+ # Send current audio data
if self.asr_ws and self.is_processing and self.server_ready:
try:
pcm_frame = self.decoder.decode(audio, 960)
await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME)
except Exception as e:
- logger.bind(tag=TAG).warning(f"发送音频数据时发生错误: {e}")
+ logger.bind(tag=TAG).warning(f"Error sending audio data: {e}")
await self._cleanup()
async def _start_recognition(self, conn):
- """开始识别会话"""
+ """Start recognition session"""
try:
self.is_processing = True
- # 建立WebSocket连接
+ # Establish WebSocket connection
ws_url = self.create_url()
- logger.bind(tag=TAG).info(f"正在连接ASR服务: {ws_url[:50]}...")
+ logger.bind(tag=TAG).info(f"Connecting to ASR service: {ws_url[:50]}...")
- # 如果为手动模式,设置超时时长为一分钟
+ # If manual mode, set timeout to 1 minute
if conn.client_listen_mode == "manual":
self.iat_params["eos"] = 60000
@@ -144,11 +156,11 @@ class ASRProvider(ASRProviderBase):
close_timeout=10,
)
- logger.bind(tag=TAG).info("ASR WebSocket连接已建立")
+ logger.bind(tag=TAG).info("ASR WebSocket connection established")
self.server_ready = False
self.forward_task = asyncio.create_task(self._forward_results(conn))
- # 发送首帧音频
+ # Send first audio frame
if conn.asr_audio and len(conn.asr_audio) > 0:
first_audio = conn.asr_audio[-1] if conn.asr_audio else b""
pcm_frame = (
@@ -156,21 +168,21 @@ class ASRProvider(ASRProviderBase):
)
await self._send_audio_frame(pcm_frame, STATUS_FIRST_FRAME)
self.server_ready = True
- logger.bind(tag=TAG).info("已发送首帧,开始识别")
+ logger.bind(tag=TAG).info("First frame sent, starting recognition")
- # 发送缓存的音频数据
+ # Send cached audio data
for cached_audio in conn.asr_audio[-10:]:
try:
pcm_frame = self.decoder.decode(cached_audio, 960)
await self._send_audio_frame(pcm_frame, STATUS_CONTINUE_FRAME)
except Exception as e:
- logger.bind(tag=TAG).info(f"发送缓存音频数据时发生错误: {e}")
+ logger.bind(tag=TAG).info(f"Error sending cached audio data: {e}")
break
except Exception as e:
- logger.bind(tag=TAG).error(f"建立ASR连接失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to establish ASR connection: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
@@ -178,7 +190,7 @@ class ASRProvider(ASRProviderBase):
raise
async def _send_audio_frame(self, audio_data: bytes, status: int):
- """发送音频帧"""
+ """Send audio frame"""
if not self.asr_ws:
return
@@ -195,13 +207,13 @@ class ASRProvider(ASRProviderBase):
await self.asr_ws.send(json.dumps(frame_data, ensure_ascii=False))
async def _forward_results(self, conn):
- """转发识别结果"""
+ """Forward recognition results"""
try:
while not conn.stop_event.is_set():
try:
response = await asyncio.wait_for(self.asr_ws.recv(), timeout=60)
result = json.loads(response)
- logger.bind(tag=TAG).debug(f"收到ASR结果: {result}")
+ logger.bind(tag=TAG).debug(f"Received ASR result: {result}")
header = result.get("header", {})
payload = result.get("payload", {})
@@ -210,20 +222,20 @@ class ASRProvider(ASRProviderBase):
if code != 0:
logger.bind(tag=TAG).error(
- f"识别错误,错误码: {code}, 消息: {header.get('message', '')}"
+ f"Recognition error, code: {code}, message: {header.get('message', '')}"
)
- if code in [10114, 10160]: # 连接问题
+ if code in [10114, 10160]: # Connection issue
break
continue
- # 处理识别结果
+ # Process recognition result
if payload and "result" in payload:
text_data = payload["result"]["text"]
if text_data:
- # 解码base64文本
+ # Decode base64 text
decoded_text = base64.b64decode(text_data).decode("utf-8")
text_json = json.loads(decoded_text)
- # 提取文本内容
+ # Extract text content
text_ws = text_json.get("ws", [])
for i in text_ws:
for j in i.get("cw", []):
@@ -234,36 +246,36 @@ class ASRProvider(ASRProviderBase):
if conn.client_listen_mode == "manual":
audio_data = getattr(conn, 'asr_audio_for_voiceprint', [])
if len(audio_data) > 0:
- logger.bind(tag=TAG).debug("收到最终识别结果,触发处理")
+ logger.bind(tag=TAG).debug("Received final result, trigger processing")
await self.handle_voice_stop(conn, audio_data)
- # 清理音频缓存
+ # Clear audio cache
conn.asr_audio.clear()
conn.reset_vad_states()
break
except asyncio.TimeoutError:
- logger.bind(tag=TAG).error("接收结果超时")
+ logger.bind(tag=TAG).error("Receive result timeout")
break
except websockets.ConnectionClosed:
- logger.bind(tag=TAG).info("ASR服务连接已关闭")
+ logger.bind(tag=TAG).info("ASR service connection closed")
self.is_processing = False
break
except Exception as e:
- logger.bind(tag=TAG).error(f"处理ASR结果时发生错误: {str(e)}")
+ logger.bind(tag=TAG).error(f"Error processing ASR result: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
self.is_processing = False
break
except Exception as e:
- logger.bind(tag=TAG).error(f"ASR结果转发任务发生错误: {str(e)}")
+ logger.bind(tag=TAG).error(f"ASR result forwarding task error: {str(e)}")
if hasattr(e, "__cause__") and e.__cause__:
- logger.bind(tag=TAG).error(f"错误原因: {str(e.__cause__)}")
+ logger.bind(tag=TAG).error(f"Error cause: {str(e.__cause__)}")
finally:
- # 清理连接资源
+ # Clean up connection resources
await self._cleanup()
- # 清理连接的音频缓存
+ # Clean up connected audio cache
if conn:
if hasattr(conn, "asr_audio_for_voiceprint"):
conn.asr_audio_for_voiceprint = []
@@ -271,24 +283,24 @@ class ASRProvider(ASRProviderBase):
conn.asr_audio = []
async def handle_voice_stop(self, conn, asr_audio_task: List[bytes]):
- """处理语音停止,发送最后一帧并处理识别结果"""
+ """Handle voice stop, send last frame and process recognition results"""
try:
- # 先发送最后一帧表示音频结束
+ # Send last frame to indicate audio end
if self.asr_ws and self.is_processing:
try:
await self._send_audio_frame(b"", STATUS_LAST_FRAME)
- logger.bind(tag=TAG).debug(f"已发送停止请求")
+ logger.bind(tag=TAG).debug(f"Stop request sent")
await asyncio.sleep(0.25)
except Exception as e:
- logger.bind(tag=TAG).error(f"发送停止请求失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to send stop request: {e}")
await super().handle_voice_stop(conn, asr_audio_task)
except Exception as e:
- logger.bind(tag=TAG).error(f"处理语音停止失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to handle voice stop: {e}")
import traceback
- logger.bind(tag=TAG).debug(f"异常详情: {traceback.format_exc()}")
+ logger.bind(tag=TAG).debug(f"Exception details: {traceback.format_exc()}")
def stop_ws_connection(self):
if self.asr_ws:
@@ -297,51 +309,51 @@ class ASRProvider(ASRProviderBase):
self.is_processing = False
async def _send_stop_request(self):
- """发送停止识别请求(不关闭连接)"""
+ """Send stop recognition request (without closing connection)"""
if self.asr_ws:
try:
- # 先停止音频发送
+ # Stop sending audio first
self.is_processing = False
await self._send_audio_frame(b"", STATUS_LAST_FRAME)
- logger.bind(tag=TAG).debug("已发送停止请求")
+ logger.bind(tag=TAG).debug("Stop request sent")
except Exception as e:
- logger.bind(tag=TAG).error(f"发送停止请求失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to send stop request: {e}")
async def _cleanup(self):
- """清理资源(关闭连接)"""
+ """Cleanup resources (close connection)"""
logger.bind(tag=TAG).debug(
- f"开始ASR会话清理 | 当前状态: processing={self.is_processing}, server_ready={self.server_ready}"
+ f"Starting ASR session cleanup | Current Status: processing={self.is_processing}, server_ready={self.server_ready}"
)
- # 状态重置
+ # Reset status
self.is_processing = False
self.server_ready = False
- logger.bind(tag=TAG).debug("ASR状态已重置")
+ logger.bind(tag=TAG).debug("ASR status reset")
- # 关闭连接
+ # Close connection
if self.asr_ws:
try:
- logger.bind(tag=TAG).debug("正在关闭WebSocket连接")
+ logger.bind(tag=TAG).debug("Closing WebSocket connection")
await asyncio.wait_for(self.asr_ws.close(), timeout=2.0)
- logger.bind(tag=TAG).debug("WebSocket连接已关闭")
+ logger.bind(tag=TAG).debug("WebSocket connection closed")
except Exception as e:
- logger.bind(tag=TAG).error(f"关闭WebSocket连接失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to close WebSocket connection: {e}")
finally:
self.asr_ws = None
- # 清理任务引用
+ # Clean up task reference
self.forward_task = None
- logger.bind(tag=TAG).debug("ASR会话清理完成")
+ logger.bind(tag=TAG).debug("ASR session cleanup completed")
async def speech_to_text(self, opus_data, session_id, audio_format):
- """获取识别结果"""
+ """Get recognition result"""
result = self.text
self.text = ""
return result, None
async def close(self):
- """资源清理方法"""
+ """Resource cleanup method"""
if self.asr_ws:
await self.asr_ws.close()
self.asr_ws = None
@@ -354,16 +366,16 @@ class ASRProvider(ASRProviderBase):
self.forward_task = None
self.is_processing = False
- # 显式释放decoder资源
+ # Explicitly release decoder resources
if hasattr(self, 'decoder') and self.decoder is not None:
try:
del self.decoder
self.decoder = None
logger.bind(tag=TAG).debug("Xunfei decoder resources released")
except Exception as e:
- logger.bind(tag=TAG).debug(f"释放Xunfei decoder资源时出错: {e}")
+ logger.bind(tag=TAG).debug(f"Error releasing Xunfei decoder resources: {e}")
- # 清理所有连接的音频缓冲区
+ # Clean up all connected audio buffers
if hasattr(self, "_connections"):
for conn in self._connections.values():
if hasattr(conn, "asr_audio_for_voiceprint"):
diff --git a/main/xiaozhi-server/core/providers/intent/base.py b/main/xiaozhi-server/core/providers/intent/base.py
index f6df10ddf..5678255a7 100644
--- a/main/xiaozhi-server/core/providers/intent/base.py
+++ b/main/xiaozhi-server/core/providers/intent/base.py
@@ -12,22 +12,21 @@ class IntentProviderBase(ABC):
def set_llm(self, llm):
self.llm = llm
- # 获取模型名称和类型信息
+ # Get model name and type info
model_name = getattr(llm, "model_name", str(llm.__class__.__name__))
- # 记录更详细的日志
- logger.bind(tag=TAG).info(f"意图识别设置LLM: {model_name}")
+ # Log more detailed info
+ logger.bind(tag=TAG).info(f"Intent recognition LLM set to: {model_name}")
@abstractmethod
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
- 检测用户最后一句话的意图
+ Detect intent of the user's last sentence
Args:
- dialogue_history: 对话历史记录列表,每条记录包含role和content
+ dialogue_history: List of dialogue history records, each containing role and content
Returns:
- 返回识别出的意图,格式为:
- - "继续聊天"
- - "结束聊天"
- - "播放音乐 歌名" 或 "随机播放音乐"
- - "查询天气 地点名" 或 "查询天气 [当前位置]"
+ Identified intent string, format:
+ - "continue_chat"
+ - "handle_exit_intent"
+ ...
"""
pass
diff --git a/main/xiaozhi-server/core/providers/intent/function_call/function_call.py b/main/xiaozhi-server/core/providers/intent/function_call/function_call.py
index d43ada429..bad8c52d9 100644
--- a/main/xiaozhi-server/core/providers/intent/function_call/function_call.py
+++ b/main/xiaozhi-server/core/providers/intent/function_call/function_call.py
@@ -9,12 +9,12 @@ logger = setup_logging()
class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
- 默认的意图识别实现,始终返回继续聊天
+ Default intent recognition implementation, always returns 'continue chat'.
Args:
- dialogue_history: 对话历史记录列表
- text: 本次对话记录
+ dialogue_history: List of dialogue history records
+ text: Current dialogue text
Returns:
- 固定返回"继续聊天"
+ Always returns 'continue chat'
"""
logger.bind(tag=TAG).debug(
"Using functionCallProvider, always returning continue chat"
diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
index 73ab843ac..738349555 100644
--- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
+++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py
@@ -16,108 +16,73 @@ class IntentProvider(IntentProviderBase):
super().__init__(config)
self.llm = None
self.promot = ""
- # 导入全局缓存管理器
+ # Import global cache manager
from core.utils.cache.manager import cache_manager, CacheType
self.cache_manager = cache_manager
self.CacheType = CacheType
- self.history_count = 4 # 默认使用最近4条对话记录
+ self.history_count = 4 # Default to using the last 4 dialogue records
- def get_intent_system_prompt(self, functions_list: str) -> str:
+ def get_intent_system_prompt(self, functions_list: list) -> str:
"""
- 根据配置的意图选项和可用函数动态生成系统提示词
- Args:
- functions: 可用的函数列表,JSON格式字符串
- Returns:
- 格式化后的系统提示词
+ Dynamically generate a concise English system prompt for intent recognition.
"""
-
- # 构建函数说明部分
- functions_desc = "可用的函数列表:\n"
+ # Build tool description section
+ functions_desc = "AVAILABLE TOOLS:\n"
for func in functions_list:
func_info = func.get("function", {})
name = func_info.get("name", "")
desc = func_info.get("description", "")
params = func_info.get("parameters", {})
- functions_desc += f"\n函数名: {name}\n"
- functions_desc += f"描述: {desc}\n"
-
+ functions_desc += f"\n- {name}: {desc}\n"
if params:
- functions_desc += "参数:\n"
- for param_name, param_info in params.get("properties", {}).items():
- param_desc = param_info.get("description", "")
- param_type = param_info.get("type", "")
- functions_desc += f"- {param_name} ({param_type}): {param_desc}\n"
-
- functions_desc += "---\n"
+ props = params.get("properties", {})
+ for p_name, p_info in props.items():
+ functions_desc += f" * {p_name} ({p_info.get('type')}): {p_info.get('description')}\n"
prompt = (
- "【严格格式要求】你必须只能返回JSON格式,绝对不能返回任何自然语言!\n\n"
- "你是一个意图识别助手。请分析用户的最后一句话,判断用户意图并调用相应的函数。\n\n"
- "【重要规则】以下类型的查询请直接返回result_for_context,无需调用函数:\n"
- "- 询问当前时间(如:现在几点、当前时间、查询时间等)\n"
- "- 询问今天日期(如:今天几号、今天星期几、今天是什么日期等)\n"
- "- 询问今天农历(如:今天农历几号、今天什么节气等)\n"
- "- 询问所在城市(如:我现在在哪里、你知道我在哪个城市吗等)"
- "系统会根据上下文信息直接构建回答。\n\n"
- "- 如果用户使用疑问词(如'怎么'、'为什么'、'如何')询问退出相关的问题(例如'怎么退出了?'),注意这不是让你退出,请返回 {'function_call': {'name': 'continue_chat'}\n"
- "- 仅当用户明确使用'退出系统'、'结束对话'、'我不想和你说话了'等指令时,才触发 handle_exit_intent\n\n"
+ "You are a strict code interpreter. Your ONLY job is to route user input to a tool.\n"
+ "OUTPUT valid JSON ONLY. NO explanation.\n\n"
+ "TOOLS:\n"
f"{functions_desc}\n"
- "处理步骤:\n"
- "1. 分析用户输入,确定用户意图\n"
- "2. 检查是否为上述基础信息查询(时间、日期等),如是则返回result_for_context\n"
- "3. 从可用函数列表中选择最匹配的函数\n"
- "4. 如果找到匹配的函数,生成对应的function_call 格式\n"
- '5. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n\n'
- "返回格式要求:\n"
- "1. 必须返回纯JSON格式,不要包含任何其他文字\n"
- "2. 必须包含function_call字段\n"
- "3. function_call必须包含name字段\n"
- "4. 如果函数需要参数,必须包含arguments字段\n\n"
- "示例:\n"
- "```\n"
- "用户: 现在几点了?\n"
- '返回: {"function_call": {"name": "result_for_context"}}\n'
- "```\n"
- "```\n"
- "用户: 当前电池电量是多少?\n"
- '返回: {"function_call": {"name": "get_battery_level", "arguments": {"response_success": "当前电池电量为{value}%", "response_failure": "无法获取Battery的当前电量百分比"}}}\n'
- "```\n"
- "```\n"
- "用户: 当前屏幕亮度是多少?\n"
- '返回: {"function_call": {"name": "self_screen_get_brightness"}}\n'
- "```\n"
- "```\n"
- "用户: 设置屏幕亮度为50%\n"
- '返回: {"function_call": {"name": "self_screen_set_brightness", "arguments": {"brightness": 50}}}\n'
- "```\n"
- "```\n"
- "用户: 我想结束对话\n"
- '返回: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n'
- "```\n"
- "```\n"
- "用户: 你好啊\n"
- '返回: {"function_call": {"name": "continue_chat"}}\n'
- "```\n\n"
- "注意:\n"
- "1. 只返回JSON格式,不要包含任何其他文字\n"
- '2. 优先检查用户查询是否为基础信息(时间、日期等),如是则返回{"function_call": {"name": "result_for_context"}},不需要arguments参数\n'
- '3. 如果没有找到匹配的函数,返回{"function_call": {"name": "continue_chat"}}\n'
- "4. 确保返回的JSON格式正确,包含所有必要的字段\n"
- "5. result_for_context不需要任何参数,系统会自动从上下文获取信息\n"
- "特殊说明:\n"
- "- 当用户单次输入包含多个指令时(如'打开灯并且调高音量')\n"
- "- 请返回多个function_call组成的JSON数组\n"
- "- 示例:{'function_calls': [{name:'light_on'}, {name:'volume_up'}]}\n\n"
- "【最终警告】绝对禁止输出任何自然语言、表情符号或解释文字!只能输出有效JSON格式!违反此规则将导致系统错误!"
+ "MAPPING RULES:\n"
+ "1. WEATHER -> 'get_weather'\n"
+ "2. LOCATION -> 'get_location'\n"
+ "3. TIME/DATE -> {'function_call': {'name': 'result_for_context'}}\n"
+ "4. CHANGE HARDWARE (Volume, Brightness, Theme) -> 'self_*' tool\n"
+ "5. GET HARDWARE STATUS (Battery, Volume, Wifi, etc.) -> 'self_get_device_status'\n"
+ "6. TAKE PHOTO/VISION -> 'self_camera_take_photo'\n"
+ "7. GENERAL KNOWLEDGE (e.g. Science, History) -> {'function_call': {'name': 'continue_chat'}}\n"
+ "8. OTHER -> {'function_call': {'name': 'continue_chat'}}\n\n"
+ "EXAMPLES:\n"
+ "User: Hello\n"
+ "{\"function_call\": {\"name\": \"continue_chat\"}}\n\n"
+ "User: What is your battery level?\n"
+ "{\"function_call\": {\"name\": \"self_get_device_status\"}}\n\n"
+ "User: Is the wifi connected?\n"
+ "{\"function_call\": {\"name\": \"self_get_device_status\"}}\n\n"
+ "User: Weather in Tokyo?\n"
+ "{\"function_call\": {\"name\": \"get_weather\", \"arguments\": {\"location\": \"Tokyo\"}}}\n\n"
+ "User: Volume up\n"
+ "{\"function_call\": {\"name\": \"self_audio_speaker_set_volume\", \"arguments\": {\"volume\": 80}}}\n\n"
+ "User: Set brightness to 50%\n"
+ "{\"function_call\": {\"name\": \"self_screen_set_brightness\", \"arguments\": {\"brightness\": 50}}}\n\n"
+ "User: Take a photo of this\n"
+ "{\"function_call\": {\"name\": \"self_camera_take_photo\", \"arguments\": {\"question\": \"Describe this photo\"}}}\n\n"
+ "User: Who won the game?\n"
+ "{\"function_call\": {\"name\": \"continue_chat\"}}\n"
+ "User: Okay, thanks\n"
+ "{\"function_call\": {\"name\": \"continue_chat\"}}\n"
+ "User: Where are we?\n"
+ "{\"function_call\": {\"name\": \"get_location\"}}\n"
)
return prompt
def replyResult(self, text: str, original_text: str):
llm_result = self.llm.response_no_stream(
system_prompt=text,
- user_prompt="请根据以上内容,像人类一样说话的口吻回复用户,要求简洁,请直接返回结果。用户现在说:"
+ user_prompt="Based on the above, reply to the user in a human-like tone. Be concise and return the result directly. The user says: "
+ original_text,
)
return llm_result
@@ -128,22 +93,22 @@ class IntentProvider(IntentProviderBase):
if conn.func_handler is None:
return '{"function_call": {"name": "continue_chat"}}'
- # 记录整体开始时间
+ # Record total start time
total_start_time = time.time()
- # 打印使用的模型信息
+ # Print model info
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
- logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}")
+ logger.bind(tag=TAG).debug(f"Using intent model: {model_info}")
- # 计算缓存键
+ # Calculate cache key
cache_key = hashlib.md5((conn.device_id + text).encode()).hexdigest()
- # 检查缓存
+ # Check cache
cached_intent = self.cache_manager.get(self.CacheType.INTENT, cache_key)
if cached_intent is not None:
cache_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
- f"使用缓存的意图: {cache_key} -> {cached_intent}, 耗时: {cache_time:.4f}秒"
+ f"Using cached intent: {cache_key} -> {cached_intent}, Time: {cache_time:.4f}s"
)
return cached_intent
@@ -168,17 +133,17 @@ class IntentProvider(IntentProviderBase):
else:
devices = []
if len(devices) > 0:
- hass_prompt = "\n下面是我家智能设备列表(位置,设备名,entity_id),可以通过homeassistant控制\n"
+ hass_prompt = "\nHere is my list of smart devices (location, device name, entity_id), which can be controlled via Home Assistant\n"
for device in devices:
hass_prompt += device + "\n"
prompt_music += hass_prompt
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
- # 构建用户对话历史的提示
+ # Build user dialogue history prompt
msgStr = ""
- # 获取最近的对话历史
+ # Get recent dialogue history
start_idx = max(0, len(dialogue_history) - self.history_count)
for i in range(start_idx, len(dialogue_history)):
msgStr += f"{dialogue_history[i].role}: {dialogue_history[i].content}\n"
@@ -186,85 +151,120 @@ class IntentProvider(IntentProviderBase):
msgStr += f"User: {text}\n"
user_prompt = f"current dialogue:\n{msgStr}"
- # 记录预处理完成时间
+ # Record preprocessing completion time
preprocess_time = time.time() - total_start_time
- logger.bind(tag=TAG).debug(f"意图识别预处理耗时: {preprocess_time:.4f}秒")
+ logger.bind(tag=TAG).debug(f"Intent preprocessing time: {preprocess_time:.4f}s")
- # 使用LLM进行意图识别
+ # Use LLM for intent recognition
llm_start_time = time.time()
- logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}")
+ logger.bind(tag=TAG).debug(f"Start LLM intent call, model: {model_info}")
intent = self.llm.response_no_stream(
- system_prompt=prompt_music, user_prompt=user_prompt
+ system_prompt=prompt_music, user_prompt=user_prompt, response_format={"type": "json_object"}
)
- # 记录LLM调用完成时间
+ # Record LLM call completion time
llm_time = time.time() - llm_start_time
logger.bind(tag=TAG).debug(
- f"外挂的大模型意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}秒"
+ f"External LLM intent completed, model: {model_info}, Time: {llm_time:.4f}s"
)
- # 记录后处理开始时间
+ # Record post-processing start time
postprocess_start_time = time.time()
- # 清理和解析响应
+ # Clean and parse response
intent = intent.strip()
- # 尝试提取JSON部分
+ # Try to extract JSON part
match = re.search(r"\{.*\}", intent, re.DOTALL)
if match:
intent = match.group(0)
- # 记录总处理时间
+ # Record total processing time
total_time = time.time() - total_start_time
logger.bind(tag=TAG).debug(
- f"【意图识别性能】模型: {model_info}, 总耗时: {total_time:.4f}秒, LLM调用: {llm_time:.4f}秒, 查询: '{text[:20]}...'"
+ f"[Intent Performance] Model: {model_info}, Total: {total_time:.4f}s, LLM: {llm_time:.4f}s, Query: '{text[:20]}...'"
)
- # 尝试解析为JSON
+ # Try to parse as JSON
try:
intent_data = json.loads(intent)
- # 如果包含function_call,则格式化为适合处理的格式
- if "function_call" in intent_data:
- function_data = intent_data["function_call"]
- function_name = function_data.get("name")
- function_args = function_data.get("arguments", {})
+ except json.JSONDecodeError:
+ # Fallback regex parsing
+ logger.bind(tag=TAG).warning(f"JSON extract failed for: {intent}, attempting regex fallback")
+
+ # Try to find function name
+ name_match = re.search(r'"name"\s*:\s*"([^"]+)"', intent)
+ if not name_match:
+ # Try to find name without quotes if model is very broken
+ name_match = re.search(r'name\s*:\s*"([^"]+)"', intent)
+
+ if name_match:
+ func_name = name_match.group(1)
+ args = {}
+ # Try to find simple arguments
+ # This is a very basic extraction
+ args_match = re.search(r'"arguments"\s*:\s*({[^}]+})', intent)
+ if args_match:
+ try:
+ args = json.loads(args_match.group(1))
+ except:
+ pass
+
+ intent_data = {
+ "function_call": {
+ "name": func_name,
+ "arguments": args
+ }
+ }
+ logger.bind(tag=TAG).info(f"Regex recovery successful: {func_name}")
+ else:
+ postprocess_time = time.time() - postprocess_start_time
+ logger.bind(tag=TAG).error(
+ f"Cannot parse intent JSON: {intent}, Post-process time: {postprocess_time:.4f}s"
+ )
+ return '{"function_call": {"name": "continue_chat"}}'
- # 记录识别到的function call
+ # If it contains function_call, format it for processing
+ if "function_call" in intent_data:
+ function_data = intent_data["function_call"]
+ function_name = function_data.get("name")
+ function_args = function_data.get("arguments", {})
+
+ # Record identified function call
+ logger.bind(tag=TAG).info(
+ f"LLM identified intent: {function_name}, args: {function_args}"
+ )
+
+ # Handle different types of intents
+ if function_name == "result_for_context":
+ # Handle basic info query, answer directly from context
logger.bind(tag=TAG).info(
- f"llm 识别到意图: {function_name}, 参数: {function_args}"
+ "Detected result_for_context intent, answering directly from context"
)
- # 处理不同类型的意图
- if function_name == "result_for_context":
- # 处理基础信息查询,直接从context构建结果
- logger.bind(tag=TAG).info(
- "检测到result_for_context意图,将使用上下文信息直接回答"
- )
+ elif function_name == "continue_chat":
+ # Handle normal chat
+ # Keep non-tool related messages
+ clean_history = [
+ msg
+ for msg in conn.dialogue.dialogue
+ if msg.role not in ["tool", "function"]
+ ]
+ conn.dialogue.dialogue = clean_history
- elif function_name == "continue_chat":
- # 处理普通对话
- # 保留非工具相关的消息
- clean_history = [
- msg
- for msg in conn.dialogue.dialogue
- if msg.role not in ["tool", "function"]
- ]
- conn.dialogue.dialogue = clean_history
+ else:
+ # Handle function call
+ logger.bind(tag=TAG).info(f"Detected function call intent: {function_name}")
- else:
- # 处理函数调用
- logger.bind(tag=TAG).info(f"检测到函数调用意图: {function_name}")
+ # Unified cache processing and return
+ # Re-dump to ensure valid JSON string is returned even if we repaired it
+ final_intent_str = json.dumps(intent_data)
- # 统一缓存处理和返回
- self.cache_manager.set(self.CacheType.INTENT, cache_key, intent)
- postprocess_time = time.time() - postprocess_start_time
- logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒")
- return intent
- except json.JSONDecodeError:
- # 后处理时间
- postprocess_time = time.time() - postprocess_start_time
- logger.bind(tag=TAG).error(
- f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒"
- )
- # 如果解析失败,默认返回继续聊天意图
- return '{"function_call": {"name": "continue_chat"}}'
+ # Log the entire JSON structure if it's a function call (MCP request)
+ if "function_call" in intent_data:
+ logger.bind(tag=TAG).info(f"Intent LLM Response: {final_intent_str}")
+
+ self.cache_manager.set(self.CacheType.INTENT, cache_key, final_intent_str)
+ postprocess_time = time.time() - postprocess_start_time
+ logger.bind(tag=TAG).debug(f"Intent post-processing time: {postprocess_time:.4f}s")
+ return final_intent_str
diff --git a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
index 4b08ae8f1..be49d954f 100644
--- a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
+++ b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
@@ -9,12 +9,12 @@ logger = setup_logging()
class IntentProvider(IntentProviderBase):
async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
- 默认的意图识别实现,始终返回继续聊天
+ Default intent recognition implementation, always returns 'continue chat'
Args:
- dialogue_history: 对话历史记录列表
- text: 本次对话记录
+ dialogue_history: List of dialogue history records
+ text: Current dialogue text
Returns:
- 固定返回"继续聊天"
+ Always returns 'continue chat'
"""
logger.bind(tag=TAG).debug(
"Using NoIntentProvider, always returning continue chat"
diff --git a/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py b/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py
index a68c4348b..96548f6e2 100644
--- a/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py
+++ b/main/xiaozhi-server/core/providers/llm/AliBL/AliBL.py
@@ -17,45 +17,45 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("base_url")
self.is_No_prompt = config.get("is_no_prompt")
self.memory_id = config.get("ali_memory_id")
- self.streaming_chunk_size = config.get("streaming_chunk_size", 3) # 每次流式返回的字符数
+ self.streaming_chunk_size = config.get("streaming_chunk_size", 3) # Number of characters returned in each stream chunk
check_model_key("AliBLLLM", self.api_key)
def response(self, session_id, dialogue):
try:
- # 处理dialogue
+ # Process dialogue
if self.is_No_prompt:
dialogue.pop(0)
logger.bind(tag=TAG).debug(
- f"【阿里百练API服务】处理后的dialogue: {dialogue}"
+ f"【Aliyun Bailian API Service】Processed dialogue: {dialogue}"
)
- # 构造调用参数
+ # Construct call parameters
call_params = {
"api_key": self.api_key,
"app_id": self.app_id,
"session_id": session_id,
"messages": dialogue,
- # 开启SDK原生流式
+ # Enable SDK native streaming
"stream": True,
}
if self.memory_id != False:
- # 百练memory需要prompt参数
+ # Bailian memory needs prompt parameter
prompt = dialogue[-1].get("content")
call_params["memory_id"] = self.memory_id
call_params["prompt"] = prompt
logger.bind(tag=TAG).debug(
- f"【阿里百练API服务】处理后的prompt: {prompt}"
+ f"【Aliyun Bailian API Service】Processed prompt: {prompt}"
)
- # 可选地设置自定义API基地址(若配置为兼容模式URL则忽略)
+ # Optionally set custom API base address (ignored if configured as compatibility mode URL)
if self.base_url and ("/api/" in self.base_url):
dashscope.base_http_api_url = self.base_url
responses = Application.call(**call_params)
- # 流式处理(SDK在stream=True时返回可迭代对象;否则返回单次响应对象)
+ # Stream processing (SDK returns iterable object when stream=True; otherwise returns single response object)
logger.bind(tag=TAG).debug(
- f"【阿里百练API服务】构造参数: {dict(call_params, api_key='***')}"
+ f"【Aliyun Bailian API Service】Construct parameters: {dict(call_params, api_key='***')}"
)
last_text = ""
@@ -63,32 +63,32 @@ class LLMProvider(LLMProviderBase):
for resp in responses:
if resp.status_code != HTTPStatus.OK:
logger.bind(tag=TAG).error(
- f"code={resp.status_code}, message={resp.message}, 请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
+ f"code={resp.status_code}, message={resp.message}, please refer to document: https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
)
continue
current_text = getattr(getattr(resp, "output", None), "text", None)
if current_text is None:
continue
- # SDK流式为增量覆盖,计算差量输出
+ # SDK streaming is incremental overwrite, calculate delta output
if len(current_text) >= len(last_text):
delta = current_text[len(last_text):]
else:
- # 避免偶发回退
+ # Avoid occasional rollback
delta = current_text
if delta:
yield delta
last_text = current_text
except TypeError:
- # 非流式回落(一次性返回)
+ # Non-streaming fallback (single return)
if responses.status_code != HTTPStatus.OK:
logger.bind(tag=TAG).error(
- f"code={responses.status_code}, message={responses.message}, 请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
+ f"code={responses.status_code}, message={responses.message}, please refer to document: https://help.aliyun.com/zh/model-studio/developer-reference/error-code"
)
- yield "【阿里百练API服务响应异常】"
+ yield "【Aliyun Bailian API Service Response Exception】"
else:
full_text = getattr(getattr(responses, "output", None), "text", "")
logger.bind(tag=TAG).info(
- f"【阿里百练API服务】完整响应长度: {len(full_text)}"
+ f"【Aliyun Bailian API Service】Full response length: {len(full_text)}"
)
for i in range(0, len(full_text), self.streaming_chunk_size):
chunk = full_text[i:i + self.streaming_chunk_size]
@@ -96,14 +96,14 @@ class LLMProvider(LLMProviderBase):
yield chunk
except Exception as e:
- logger.bind(tag=TAG).error(f"【阿里百练API服务】响应异常: {e}")
- yield "【LLM服务响应异常】"
+ logger.bind(tag=TAG).error(f"【Aliyun Bailian API Service】Response Exception: {e}")
+ yield "【LLM Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
- # 阿里百练当前未支持原生的 function call。为保持兼容,这里回退到普通文本流式输出。
- # 上层会按 (content, tool_calls) 的形式消费,这里始终返回 (token, None)
+ # Aliyun Bailian currently does not support native function call. To maintain compatibility, fallback to plain text streaming output here.
+ # The upper layer will consume in the form of (content, tool_calls), here always return (token, None)
logger.bind(tag=TAG).warning(
- "阿里百练未实现原生 function call,已回退为纯文本流式输出"
+ "Aliyun Bailian does not implement native function call, has fallen back to plain text streaming output"
)
for token in self.response(session_id, dialogue):
yield token, None
diff --git a/main/xiaozhi-server/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py
index 777861403..b70091d2f 100644
--- a/main/xiaozhi-server/core/providers/llm/base.py
+++ b/main/xiaozhi-server/core/providers/llm/base.py
@@ -12,19 +12,28 @@ class LLMProviderBase(ABC):
def response_no_stream(self, system_prompt, user_prompt, **kwargs):
try:
- # 构造对话格式
+ # Construct dialogue format
dialogue = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
+
+ timeout = kwargs.get("timeout")
+ import time
+ start_time = time.time()
+
result = ""
for part in self.response("", dialogue, **kwargs):
+ # Strict wall-clock check
+ if timeout and (time.time() - start_time) > timeout:
+ logger.bind(tag=TAG).warning(f"Response consumption exceeded timeout of {timeout}s, returning partial.")
+ break
result += part
return result
except Exception as e:
- logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
- return "【LLM服务响应异常】"
+ logger.bind(tag=TAG).error(f"Error in LLM response generation: {e}")
+ return "[LLM Service Response Error]"
def response_with_functions(self, session_id, dialogue, functions=None):
"""
diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py
index 31a7d4ac3..3e3219b5e 100644
--- a/main/xiaozhi-server/core/providers/llm/coze/coze.py
+++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py
@@ -22,7 +22,7 @@ class LLMProvider(LLMProviderBase):
self.personal_access_token = config.get("personal_access_token")
self.bot_id = str(config.get("bot_id"))
self.user_id = str(config.get("user_id"))
- self.session_conversation_map = {} # 存储session_id和conversation_id的映射
+ self.session_conversation_map = {} # Store mapping of session_id and conversation_id
model_key_msg = check_model_key("CozeLLM", self.personal_access_token)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
@@ -36,11 +36,11 @@ class LLMProvider(LLMProviderBase):
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
conversation_id = self.session_conversation_map.get(session_id)
- # 如果没有找到conversation_id,则创建新的对话
+ # If conversation_id is not found, create a new conversation
if not conversation_id:
conversation = coze.conversations.create(messages=[])
conversation_id = conversation.id
- self.session_conversation_map[session_id] = conversation_id # 更新映射
+ self.session_conversation_map[session_id] = conversation_id # Update mapping
for event in coze.chat.stream(
bot_id=self.bot_id,
@@ -56,13 +56,13 @@ class LLMProvider(LLMProviderBase):
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
- # 第一次调用llm, 取最后一条用户消息,附加tool提示词
+ # First LLM call, get the last user message, append tool prompt
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
- # 如果最后一个是 role="tool",附加到user上
+ # If the last one is role="tool", append to user
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1:
diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py
index 4ec04ec76..f7473b84c 100644
--- a/main/xiaozhi-server/core/providers/llm/dify/dify.py
+++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py
@@ -14,18 +14,18 @@ class LLMProvider(LLMProviderBase):
self.api_key = config["api_key"]
self.mode = config.get("mode", "chat-messages")
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip("/")
- self.session_conversation_map = {} # 存储session_id和conversation_id的映射
+ self.session_conversation_map = {} # Store mapping of session_id and conversation_id
model_key_msg = check_model_key("DifyLLM", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
def response(self, session_id, dialogue, **kwargs):
try:
- # 取最后一条用户消息
+ # Get the last user message
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
conversation_id = self.session_conversation_map.get(session_id)
- # 发起流式请求
+ # Initiate streaming request
if self.mode == "chat-messages":
request_json = {
"query": last_msg["content"],
@@ -57,13 +57,13 @@ class LLMProvider(LLMProviderBase):
for line in r.iter_lines():
if line.startswith(b"data: "):
event = json.loads(line[6:])
- # 如果没有找到conversation_id,则获取此次conversation_id
+ # If conversation_id is not found, get conversation_id for this time
if not conversation_id:
conversation_id = event.get("conversation_id")
self.session_conversation_map[session_id] = (
- conversation_id # 更新映射
+ conversation_id # Update mapping
)
- # 过滤 message_replace 事件,此事件会全量推一次
+ # Filter message_replace event, this event will push full amount once
if event.get("event") != "message_replace" and event.get(
"answer"
):
@@ -76,12 +76,12 @@ class LLMProvider(LLMProviderBase):
if event["data"]["status"] == "succeeded":
yield event["data"]["outputs"]["answer"]
else:
- yield "【服务响应异常】"
+ yield "【Service Response Exception】"
elif self.mode == "completion-messages":
for line in r.iter_lines():
if line.startswith(b"data: "):
event = json.loads(line[6:])
- # 过滤 message_replace 事件,此事件会全量推一次
+ # Filter message_replace event, this event will push full amount once
if event.get("event") != "message_replace" and event.get(
"answer"
):
@@ -89,17 +89,17 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
- yield "【服务响应异常】"
+ yield "【Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
if len(dialogue) == 2 and functions is not None and len(functions) > 0:
- # 第一次调用llm, 取最后一条用户消息,附加tool提示词
+ # First LLM call, get the last user message, append tool prompt
last_msg = dialogue[-1]["content"]
function_str = json.dumps(functions, ensure_ascii=False)
modify_msg = get_system_prompt_for_function(function_str) + last_msg
dialogue[-1]["content"] = modify_msg
- # 如果最后一个是 role="tool",附加到user上
+ # If the last one is role="tool", append to user
if len(dialogue) > 1 and dialogue[-1]["role"] == "tool":
assistant_msg = "\ntool call result: " + dialogue[-1]["content"] + "\n\n"
while len(dialogue) > 1:
diff --git a/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py b/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py
index 4f3f4259c..2657452c0 100644
--- a/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py
+++ b/main/xiaozhi-server/core/providers/llm/fastgpt/fastgpt.py
@@ -20,10 +20,10 @@ class LLMProvider(LLMProviderBase):
def response(self, session_id, dialogue, **kwargs):
try:
- # 取最后一条用户消息
+ # Get the last user message
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
- # 发起流式请求
+ # Initiate streaming request
with requests.post(
f"{self.base_url}/chat/completions",
headers={"Authorization": f"Bearer {self.api_key}"},
@@ -65,9 +65,9 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in response generation: {e}")
- yield "【服务响应异常】"
+ yield "【Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
logger.bind(tag=TAG).error(
- f"fastgpt暂未实现完整的工具调用(function call),建议使用其他意图识别"
+ f"FastGPT has not implemented full tool calling (function call) yet, it is recommended to use other intent recognition"
)
diff --git a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
index 0b996882b..4e2bb900b 100644
--- a/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
+++ b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py
@@ -26,8 +26,8 @@ def test_proxy(proxy_url: str, test_url: str) -> bool:
def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
"""
- 分别测试 HTTP 和 HTTPS 代理是否可用,并设置环境变量。
- 如果 HTTPS 代理不可用但 HTTP 可用,会将 HTTPS_PROXY 也指向 HTTP。
+ Test if HTTP and HTTPS proxies are available separately, and set environment variables.
+ If HTTPS proxy is unavailable but HTTP is available, set HTTPS_PROXY to point to HTTP as well.
"""
test_http_url = "http://www.google.com"
test_https_url = "https://www.google.com"
@@ -38,32 +38,32 @@ def setup_proxy_env(http_proxy: str | None, https_proxy: str | None):
ok_http = test_proxy(http_proxy, test_http_url)
if ok_http:
os.environ["HTTP_PROXY"] = http_proxy
- log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {http_proxy}")
+ log.bind(tag=TAG).info(f"Gemini HTTPS proxy provided in config connected successfully: {http_proxy}")
else:
- log.bind(tag=TAG).warning(f"配置提供的Gemini HTTP代理不可用: {http_proxy}")
+ log.bind(tag=TAG).warning(f"Gemini HTTP proxy provided in config unavailable: {http_proxy}")
if https_proxy:
ok_https = test_proxy(https_proxy, test_https_url)
if ok_https:
os.environ["HTTPS_PROXY"] = https_proxy
- log.bind(tag=TAG).info(f"配置提供的Gemini HTTPS代理连通成功: {https_proxy}")
+ log.bind(tag=TAG).info(f"Gemini HTTPS proxy provided in config connected successfully: {https_proxy}")
else:
log.bind(tag=TAG).warning(
- f"配置提供的Gemini HTTPS代理不可用: {https_proxy}"
+ f"Gemini HTTPS proxy provided in config unavailable: {https_proxy}"
)
- # 如果https_proxy不可用,但http_proxy可用且能走通https,则复用http_proxy作为https_proxy
+ # If https_proxy is unavailable, but http_proxy is available and can reach https, reuse http_proxy as https_proxy
if ok_http and not ok_https:
if test_proxy(http_proxy, test_https_url):
os.environ["HTTPS_PROXY"] = http_proxy
ok_https = True
- log.bind(tag=TAG).info(f"复用HTTP代理作为HTTPS代理: {http_proxy}")
+ log.bind(tag=TAG).info(f"Reuse HTTP proxy as HTTPS proxy: {http_proxy}")
if not ok_http and not ok_https:
log.bind(tag=TAG).error(
- f"Gemini 代理设置失败: HTTP 和 HTTPS 代理都不可用,请检查配置"
+ f"Gemini proxy setup failed: Both HTTP and HTTPS proxies are unavailable, please check configuration"
)
- raise RuntimeError("HTTP 和 HTTPS 代理都不可用,请检查配置")
+ raise RuntimeError("Both HTTP and HTTPS proxies are unavailable, please check configuration")
class LLMProvider(LLMProviderBase):
@@ -79,19 +79,19 @@ class LLMProvider(LLMProviderBase):
if http_proxy or https_proxy:
log.bind(tag=TAG).info(
- f"检测到Gemini代理配置,开始测试代理连通性和设置代理环境..."
+ f"Gemini proxy configuration detected, starting to test proxy connectivity and setup proxy environment..."
)
setup_proxy_env(http_proxy, https_proxy)
log.bind(tag=TAG).info(
- f"Gemini 代理设置成功 - HTTP: {http_proxy}, HTTPS: {https_proxy}"
+ f"Gemini proxy set up successfully - HTTP: {http_proxy}, HTTPS: {https_proxy}"
)
- # 配置API密钥
+ # Configure API key
genai.configure(api_key=self.api_key)
- # 设置请求超时(秒)
- self.timeout = cfg.get("timeout", 120) # 默认120秒
+ # Set request timeout (seconds)
+ self.timeout = cfg.get("timeout", 120) # Default 120 seconds
- # 创建模型实例
+ # Create model instance
self.model = genai.GenerativeModel(self.model_name)
self.gen_cfg = GenerationConfig(
@@ -118,7 +118,7 @@ class LLMProvider(LLMProviderBase):
)
]
- # Gemini文档提到,无需维护session-id,直接用dialogue拼接而成
+ # Gemini documentation mentions that session-id management is not needed, directly constructed from dialogue
def response(self, session_id, dialogue, **kwargs):
yield from self._generate(dialogue, None)
@@ -128,7 +128,7 @@ class LLMProvider(LLMProviderBase):
def _generate(self, dialogue, tools):
role_map = {"assistant": "model", "user": "user"}
contents: list = []
- # 拼接对话
+ # Splice dialogue
for m in dialogue:
r = m["role"]
@@ -158,10 +158,22 @@ class LLMProvider(LLMProviderBase):
)
continue
+ parts = [{"text": str(m.get("content", ""))}]
+ # If this is the last message (user's latest input) and we have audio, attach it
+ if i == len(dialogue) - 1 and r == "user" and kwargs.get("audio_data"):
+ parts.append(
+ {
+ "inline_data": {
+ "mime_type": "audio/wav",
+ "data": kwargs.get("audio_data")
+ }
+ }
+ )
+
contents.append(
{
"role": role_map.get(r, "user"),
- "parts": [{"text": str(m.get("content", ""))}],
+ "parts": parts,
}
)
@@ -177,7 +189,7 @@ class LLMProvider(LLMProviderBase):
for chunk in stream:
cand = chunk.candidates[0]
for part in cand.content.parts:
- # a) 函数调用-通常是最后一段话才是函数调用
+ # a) Function call - usually the last paragraph is the function call
if getattr(part, "function_call", None):
fc = part.function_call
yield None, [
@@ -193,15 +205,15 @@ class LLMProvider(LLMProviderBase):
)
]
return
- # b) 普通文本
+ # b) Plain text
if getattr(part, "text", None):
yield part.text if tools is None else (part.text, None)
finally:
if tools is not None:
- yield None, None # function‑mode 结束,返回哑包
+ yield None, None # function-mode ended, return dummy package
- # 关闭stream,预留后续打断对话功能的功能方法,官方文档推荐打断对话要关闭上一个流,可以有效减少配额计费和资源占用
+ # Close stream, reserved for subsequent conversation interruption function method. Official documentation recommends closing the previous stream to interrupt conversation, which can effectively reduce quota billing and resource usage
@staticmethod
def _safe_finish_stream(stream: GenerateContentResponse):
if hasattr(stream, "resolve"):
@@ -209,5 +221,5 @@ class LLMProvider(LLMProviderBase):
elif hasattr(stream, "close"):
stream.close() # Gemini SDK version < 0.5.0
else:
- for _ in stream: # 兜底耗尽
+ for _ in stream: # Exhaust fallback
pass
diff --git a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
index f203e5f7d..c13d1c4c0 100644
--- a/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
+++ b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py
@@ -9,43 +9,43 @@ logger = setup_logging()
class LLMProvider(LLMProviderBase):
def __init__(self, config):
- self.agent_id = config.get("agent_id") # 对应 agent_id
+ self.agent_id = config.get("agent_id") # Corresponds to agent_id
self.api_key = config.get("api_key")
- self.base_url = config.get("base_url", config.get("url")) # 默认使用 base_url
- self.api_url = f"{self.base_url}/api/conversation/process" # 拼接完整的 API URL
+ self.base_url = config.get("base_url", config.get("url")) # Default use base_url
+ self.api_url = f"{self.base_url}/api/conversation/process" # Splice complete API URL
def response(self, session_id, dialogue, **kwargs):
try:
- # home assistant语音助手自带意图,无需使用xiaozhi ai自带的,只需要把用户说的话传递给home assistant即可
+ # home assistant voice assistant has its own intent, no need to use xiaozhi ai's, just pass what user said to home assistant
- # 提取最后一个 role 为 'user' 的 content
+ # Extract content of the last role as 'user'
input_text = None
- if isinstance(dialogue, list): # 确保 dialogue 是一个列表
- # 逆序遍历,找到最后一个 role 为 'user' 的消息
+ if isinstance(dialogue, list): # Ensure dialogue is a list
+ # Reverse traverse, find the last message with role 'user'
for message in reversed(dialogue):
- if message.get("role") == "user": # 找到 role 为 'user' 的消息
+ if message.get("role") == "user": # Find message with role 'user'
input_text = message.get("content", "")
- break # 找到后立即退出循环
+ break # Exit loop immediately after finding
- # 构造请求数据
+ # Construct request data
payload = {
"text": input_text,
"agent_id": self.agent_id,
- "conversation_id": session_id, # 使用 session_id 作为 conversation_id
+ "conversation_id": session_id, # Use session_id as conversation_id
}
- # 设置请求头
+ # Set request headers
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
- # 发起 POST 请求
+ # Initiate POST request
response = requests.post(self.api_url, json=payload, headers=headers)
- # 检查请求是否成功
+ # Check if request is successful
response.raise_for_status()
- # 解析返回数据
+ # Parse return data
data = response.json()
speech = (
data.get("response", {})
@@ -54,18 +54,18 @@ class LLMProvider(LLMProviderBase):
.get("speech", "")
)
- # 返回生成的内容
+ # Return generated content
if speech:
yield speech
else:
- logger.bind(tag=TAG).warning("API 返回数据中没有 speech 内容")
+ logger.bind(tag=TAG).warning("No speech content in API return data")
except RequestException as e:
- logger.bind(tag=TAG).error(f"HTTP 请求错误: {e}")
+ logger.bind(tag=TAG).error(f"HTTP request error: {e}")
except Exception as e:
- logger.bind(tag=TAG).error(f"生成响应时出错: {e}")
+ logger.bind(tag=TAG).error(f"Error generating response: {e}")
def response_with_functions(self, session_id, dialogue, functions=None):
logger.bind(tag=TAG).error(
- f"homeassistant不支持(function call),建议使用其他意图识别"
+ f"homeassistant does not support (function call), it is recommended to use other intent recognition"
)
diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
index c973cacd8..056dc62de 100644
--- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
+++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py
@@ -12,7 +12,7 @@ class LLMProvider(LLMProviderBase):
self.model_name = config.get("model_name")
self.base_url = config.get("base_url", "http://localhost:11434")
# Initialize OpenAI client with Ollama base URL
- # 如果没有v1,增加v1
+ # If no v1, add v1
if not self.base_url.endswith("/v1"):
self.base_url = f"{self.base_url}/v1"
@@ -21,34 +21,34 @@ class LLMProvider(LLMProviderBase):
api_key="ollama", # Ollama doesn't need an API key but OpenAI client requires one
)
- # 检查是否是qwen3模型
+ # Check if it is qwen3 model
self.is_qwen3 = self.model_name and self.model_name.lower().startswith("qwen3")
def response(self, session_id, dialogue, **kwargs):
try:
- # 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
+ # If it is qwen3 model, add /no_think instruction to the last user message
if self.is_qwen3:
- # 复制对话列表,避免修改原始对话
+ # Copy dialogue list to avoid modifying original dialogue
dialogue_copy = dialogue.copy()
- # 找到最后一条用户消息
+ # Find the last user message
for i in range(len(dialogue_copy) - 1, -1, -1):
if dialogue_copy[i]["role"] == "user":
- # 在用户消息前添加/no_think指令
+ # Add /no_think instruction before user message
dialogue_copy[i]["content"] = (
"/no_think " + dialogue_copy[i]["content"]
)
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
break
- # 使用修改后的对话
+ # Use modified dialogue
dialogue = dialogue_copy
responses = self.client.chat.completions.create(
model=self.model_name, messages=dialogue, stream=True
)
is_active = True
- # 用于处理跨chunk的标签
+ # For handling tags across chunks
buffer = ""
for chunk in responses:
@@ -61,56 +61,56 @@ class LLMProvider(LLMProviderBase):
content = delta.content if hasattr(delta, "content") else ""
if content:
- # 将内容添加到缓冲区
+ # Append content to buffer
buffer += content
- # 处理缓冲区中的标签
+ # Process tags in buffer
while "" in buffer and " " in buffer:
# 找到完整的 标签并移除
pre = buffer.split("", 1)[0]
post = buffer.split(" ", 1)[1]
buffer = pre + post
- # 处理只有开始标签的情况
+ # Handle case with only start tag
if "" in buffer:
is_active = False
buffer = buffer.split("", 1)[0]
- # 处理只有结束标签的情况
+ # Handle case with only end tag
if " " in buffer:
is_active = True
buffer = buffer.split(" ", 1)[1]
- # 如果当前处于活动状态且缓冲区有内容,则输出
+ # If currently active and buffer has content, output
if is_active and buffer:
yield buffer
- buffer = "" # 清空缓冲区
+ buffer = "" # Clear buffer
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing chunk: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}")
- yield "【Ollama服务响应异常】"
+ yield "【Ollama Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
try:
- # 如果是qwen3模型,在用户最后一条消息中添加/no_think指令
+ # If it is qwen3 model, add /no_think instruction to the last user message
if self.is_qwen3:
- # 复制对话列表,避免修改原始对话
+ # Copy dialogue list to avoid modifying original dialogue
dialogue_copy = dialogue.copy()
- # 找到最后一条用户消息
+ # Find the last user message
for i in range(len(dialogue_copy) - 1, -1, -1):
if dialogue_copy[i]["role"] == "user":
- # 在用户消息前添加/no_think指令
+ # Add /no_think instruction before user message
dialogue_copy[i]["content"] = (
"/no_think " + dialogue_copy[i]["content"]
)
logger.bind(tag=TAG).debug(f"为qwen3模型添加/no_think指令")
break
- # 使用修改后的对话
+ # Use modified dialogue
dialogue = dialogue_copy
stream = self.client.chat.completions.create(
@@ -135,41 +135,41 @@ class LLMProvider(LLMProviderBase):
delta.tool_calls if hasattr(delta, "tool_calls") else None
)
- # 如果是工具调用,直接传递
+ # If it is tool call, pass directly
if tool_calls:
yield None, tool_calls
continue
- # 处理文本内容
+ # Process text content
if content:
- # 将内容添加到缓冲区
+ # Append content to buffer
buffer += content
- # 处理缓冲区中的标签
+ # Process tags in buffer
while "" in buffer and " " in buffer:
- # 找到完整的 标签并移除
+ # Find complete tags and remove
pre = buffer.split("", 1)[0]
post = buffer.split(" ", 1)[1]
buffer = pre + post
- # 处理只有开始标签的情况
+ # Handle case with only start tag
if "" in buffer:
is_active = False
buffer = buffer.split("", 1)[0]
- # 处理只有结束标签的情况
+ # Handle case with only end tag
if " " in buffer:
is_active = True
buffer = buffer.split(" ", 1)[1]
- # 如果当前处于活动状态且缓冲区有内容,则输出
+ # If currently active and buffer has content, output
if is_active and buffer:
yield buffer, None
- buffer = "" # 清空缓冲区
+ buffer = "" # Clear buffer
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing function chunk: {e}")
continue
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}")
- yield f"【Ollama服务响应异常: {str(e)}】", None
+ yield f"【Ollama Service Response Exception: {str(e)}】", None
diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py
index 2863c4204..eb4445a07 100644
--- a/main/xiaozhi-server/core/providers/llm/openai/openai.py
+++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py
@@ -19,6 +19,11 @@ class LLMProvider(LLMProviderBase):
self.base_url = config.get("url")
timeout = config.get("timeout", 300)
self.timeout = int(timeout) if timeout else 300
+ self.num_ctx = config.get("num_ctx")
+ self.options = config.get("options", {})
+ if self.num_ctx:
+ self.options["num_ctx"] = int(self.num_ctx)
+ self.extra_body_config = config.get("extra_body", {})
param_defaults = {
"max_tokens": int,
@@ -38,18 +43,26 @@ class LLMProvider(LLMProviderBase):
except (ValueError, TypeError):
setattr(self, param, None)
+ self.max_retries = int(config.get("max_retries", 2))
+
logger.debug(
- f"意图识别参数初始化: {self.temperature}, {self.max_tokens}, {self.top_p}, {self.frequency_penalty}"
+ f"LLM initialization: {self.model_name}, timeout={self.timeout}s, max_retries={self.max_retries}"
)
model_key_msg = check_model_key("LLM", self.api_key)
if model_key_msg:
logger.bind(tag=TAG).error(model_key_msg)
- self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url, timeout=httpx.Timeout(self.timeout))
+
+ self.client = openai.OpenAI(
+ api_key=self.api_key,
+ base_url=self.base_url,
+ timeout=httpx.Timeout(self.timeout),
+ max_retries=self.max_retries
+ )
@staticmethod
def normalize_dialogue(dialogue):
- """自动修复 dialogue 中缺失 content 的消息"""
+ """Automatically fix missing content in dialogue messages"""
for msg in dialogue:
if "role" in msg and "content" not in msg:
msg["content"] = ""
@@ -65,19 +78,59 @@ class LLMProvider(LLMProviderBase):
"stream": True,
}
- # 添加可选参数,只有当参数不为None时才添加
+ # Prepare extra_body, starting with generic extra_body from config
+ final_extra_body = getattr(self, "extra_body_config", {}).copy()
+
+ # Merge in self.options (which includes num_ctx)
+ if self.options:
+ if "options" not in final_extra_body:
+ final_extra_body["options"] = {}
+ # self.options take precedence over generic config if distinct,
+ # but usually self.options ARE from config, so update is fine.
+ final_extra_body["options"].update(self.options)
+
+ if final_extra_body:
+ request_params["extra_body"] = final_extra_body
+
+ # Add optional parameters, only add if parameter is not None
optional_params = {
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
"temperature": kwargs.get("temperature", self.temperature),
"top_p": kwargs.get("top_p", self.top_p),
"frequency_penalty": kwargs.get("frequency_penalty", self.frequency_penalty),
+ "response_format": kwargs.get("response_format"),
}
for key, value in optional_params.items():
if value is not None:
request_params[key] = value
- responses = self.client.chat.completions.create(**request_params)
+
+
+ # Support for checking num_ctx in config (passed via self.xxx if we add it to init)
+ # We need to add it to init first, or just check config again?
+ # Better to check if we can access config. config is passed to init.
+ # We should update init to read num_ctx.
+
+ # Wait, I cannot edit init in this same tool call easily if I am targeting line 81.
+ # I will assume I need to do 2 edits or one big edit.
+ # For now, let's just use getattr(self, 'num_ctx', None) and assume I added it to init.
+
+ extra_body = {}
+ if getattr(self, "num_ctx", None):
+ # Ollama uses "options" for parameters in the OpenAI endpoint often,
+ # BUT some versions mapping allow "num_ctx" at top level of extra_body??
+ # "options" is the safest for Ollama native parameters.
+ extra_body["options"] = {"num_ctx": int(self.num_ctx)}
+
+ # Standard OpenAI SDK per-request timeout
+ request_timeout = kwargs.get("timeout", self.timeout)
+ request_retries = kwargs.get("max_retries", self.max_retries)
+
+ responses = self.client.with_options(max_retries=request_retries).chat.completions.create(
+ **request_params,
+ timeout=request_timeout
+ )
is_active = True
for chunk in responses:
@@ -110,6 +163,9 @@ class LLMProvider(LLMProviderBase):
"tools": functions,
}
+ if self.options:
+ request_params["extra_body"] = {"options": self.options}
+
optional_params = {
"max_tokens": kwargs.get("max_tokens", self.max_tokens),
"temperature": kwargs.get("temperature", self.temperature),
@@ -121,7 +177,14 @@ class LLMProvider(LLMProviderBase):
if value is not None:
request_params[key] = value
- stream = self.client.chat.completions.create(**request_params)
+ # Standard OpenAI SDK per-request timeout
+ request_timeout = kwargs.get("timeout", self.timeout)
+ request_retries = kwargs.get("max_retries", self.max_retries)
+
+ stream = self.client.with_options(max_retries=request_retries).chat.completions.create(
+ **request_params,
+ timeout=request_timeout
+ )
for chunk in stream:
if getattr(chunk, "choices", None):
@@ -132,11 +195,11 @@ class LLMProvider(LLMProviderBase):
elif isinstance(getattr(chunk, "usage", None), CompletionUsage):
usage_info = getattr(chunk, "usage", None)
logger.bind(tag=TAG).info(
- f"Token 消耗:输入 {getattr(usage_info, 'prompt_tokens', '未知')},"
- f"输出 {getattr(usage_info, 'completion_tokens', '未知')},"
- f"共计 {getattr(usage_info, 'total_tokens', '未知')}"
+ f"Token usage: Input {getattr(usage_info, 'prompt_tokens', 'Unknown')}, "
+ f"Output {getattr(usage_info, 'completion_tokens', 'Unknown')}, "
+ f"Total {getattr(usage_info, 'total_tokens', 'Unknown')}"
)
except Exception as e:
logger.bind(tag=TAG).error(f"Error in function call streaming: {e}")
- yield f"【OpenAI服务响应异常: {e}】", None
+ yield f"【OpenAI Service Response Exception: {e}】", None
diff --git a/main/xiaozhi-server/core/providers/llm/system_prompt.py b/main/xiaozhi-server/core/providers/llm/system_prompt.py
index 606f0e4b9..a0171809e 100644
--- a/main/xiaozhi-server/core/providers/llm/system_prompt.py
+++ b/main/xiaozhi-server/core/providers/llm/system_prompt.py
@@ -1,8 +1,8 @@
def get_system_prompt_for_function(functions: str) -> str:
"""
- 生成系统提示信息
- :param functions: 可用的函数列表
- :return: 系统提示信息
+ Generate system prompt info
+ :param functions: Available functions list
+ :return: System prompt info
"""
SYSTEM_PROMPT = f"""
@@ -36,13 +36,13 @@ if you got tool as follow
"type": "function",
"function": {{
"name": "handle_exit_intent",
- "description": "当用户想结束对话或需要退出系统时调用",
+ "description": "Called when user wants to end conversation or exit system",
"parameters": {{
"type": "object",
"properties": {{
"say_goodbye": {{
"type": "string",
- "description": "和用户友好结束对话的告别语",
+ "description": "Farewell message to end conversation friendlily",
}}
}},
"required": ["say_goodbye"],
@@ -56,7 +56,7 @@ you should respond with the following format:
{{
"name": "handle_exit_intent",
"arguments": {{
- "say_goodbye": "再见,祝您生活愉快!"
+ "say_goodbye": "Goodbye, have a nice day!"
}}
}}
diff --git a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py
index a4e9a5e6c..6e1edabcc 100644
--- a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py
+++ b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py
@@ -12,7 +12,7 @@ class LLMProvider(LLMProviderBase):
self.model_name = config.get("model_name")
self.base_url = config.get("base_url", "http://localhost:9997")
# Initialize OpenAI client with Xinference base URL
- # 如果没有v1,增加v1
+ # If no v1, add v1
if not self.base_url.endswith("/v1"):
self.base_url = f"{self.base_url}/v1"
@@ -61,7 +61,7 @@ class LLMProvider(LLMProviderBase):
except Exception as e:
logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}")
- yield "【Xinference服务响应异常】"
+ yield "【Xinference Service Response Exception】"
def response_with_functions(self, session_id, dialogue, functions=None):
try:
@@ -94,5 +94,5 @@ class LLMProvider(LLMProviderBase):
logger.bind(tag=TAG).error(f"Error in Xinference function call: {e}")
yield {
"type": "content",
- "content": f"【Xinference服务响应异常: {str(e)}】",
+ "content": f"【Xinference Service Response Exception: {str(e)}】",
}
diff --git a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py
index 7156ab727..2c998f260 100644
--- a/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py
+++ b/main/xiaozhi-server/core/providers/memory/mem0ai/mem0ai.py
@@ -22,10 +22,10 @@ class MemoryProvider(MemoryProviderBase):
try:
self.client = MemoryClient(api_key=self.api_key)
- logger.bind(tag=TAG).info("成功连接到 Mem0ai 服务")
+ logger.bind(tag=TAG).info("Successfully connected to Mem0ai service")
except Exception as e:
- logger.bind(tag=TAG).error(f"连接到 Mem0ai 服务时发生错误: {str(e)}")
- logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
+ logger.bind(tag=TAG).error(f"Error connecting to Mem0ai service: {str(e)}")
+ logger.bind(tag=TAG).error(f"Detailed error: {traceback.format_exc()}")
self.use_mem0 = False
async def save_memory(self, msgs, session_id=None):
@@ -44,7 +44,7 @@ class MemoryProvider(MemoryProviderBase):
result = self.client.add(messages, user_id=self.role_id)
logger.bind(tag=TAG).debug(f"Save memory result: {result}")
except Exception as e:
- logger.bind(tag=TAG).error(f"保存记忆失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to save memory: {str(e)}")
return None
async def query_memory(self, query: str) -> str:
@@ -84,5 +84,5 @@ class MemoryProvider(MemoryProviderBase):
logger.bind(tag=TAG).debug(f"Query results: {memories_str}")
return memories_str
except Exception as e:
- logger.bind(tag=TAG).error(f"查询记忆失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to query memory: {str(e)}")
return ""
diff --git a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py
index 5904d440d..ceb3c1a22 100644
--- a/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py
+++ b/main/xiaozhi-server/core/providers/memory/mem_local_short/mem_local_short.py
@@ -10,66 +10,66 @@ from core.utils.util import check_model_key
short_term_memory_prompt = """
-# 时空记忆编织者
+# Time-Space Memory Weaver
-## 核心使命
-构建可生长的动态记忆网络,在有限空间内保留关键信息的同时,智能维护信息演变轨迹
-根据对话记录,总结user的重要信息,以便在未来的对话中提供更个性化的服务
+## Core Mission
+Construct a growable dynamic memory network that retains key information within limited space while intelligently maintaining the trajectory of information evolution.
+Summarize important user information from dialogue records to provide more personalized services in future conversations.
-## 记忆法则
-### 1. 三维度记忆评估(每次更新必执行)
-| 维度 | 评估标准 | 权重分 |
-|------------|---------------------------|--------|
-| 时效性 | 信息新鲜度(按对话轮次) | 40% |
-| 情感强度 | 含💖标记/重复提及次数 | 35% |
-| 关联密度 | 与其他信息的连接数量 | 25% |
+## Memory Laws
+### 1. Three-Dimensional Memory Assessment (Executed on every update)
+| Dimension | Assessment Criteria | Weight |
+|---|---|---|
+| Timeliness | Information Freshness (by dialogue turns) | 40% |
+| Emotional Intensity | Containing 💖 markers/Repetition frequency | 35% |
+| Association Density | Number of connections with other information | 25% |
-### 2. 动态更新机制
-**名字变更处理示例:**
-原始记忆:"曾用名": ["张三"], "现用名": "张三丰"
-触发条件:当检测到「我叫X」「称呼我Y」等命名信号时
-操作流程:
-1. 将旧名移入"曾用名"列表
-2. 记录命名时间轴:"2024-02-15 14:32:启用张三丰"
-3. 在记忆立方追加:「从张三到张三丰的身份蜕变」
+### 2. Dynamic Update Mechanism
+**Name Change Handling Example:**
+Original Memory: "Former Name": ["John Doe"], "Current Name": "John Smith"
+Trigger Condition: When detection signals like "My name is X", "Call me Y" appear
+Operation Flow:
+1. Move old name to "Former Name" list
+2. Record naming timeline: "2024-02-15 14:32: Enable John Smith"
+3. Append to Memory Cube: "Identity transformation from John Doe to John Smith"
-### 3. 空间优化策略
-- **信息压缩术**:用符号体系提升密度
- - ✅"张三丰[北/软工/🐱]"
- - ❌"北京软件工程师,养猫"
-- **淘汰预警**:当总字数≥900时触发
- 1. 删除权重分<60且3轮未提及的信息
- 2. 合并相似条目(保留时间戳最近的)
+### 3. Space Optimization Strategy
+- **Information Compression**: Use symbol system to increase density
+ - ✅"John Smith[North/SE/🐱]"
+ - ❌"Beijing Software Engineer, raises a cat"
+- **Elimination Warning**: Triggered when total character count ≥ 900
+ 1. Delete information with weight score < 60 and not mentioned in 3 turns
+ 2. Merge similar entries (keep the one with latest timestamp)
-## 记忆结构
-输出格式必须为可解析的json字符串,不需要解释、注释和说明,保存记忆时仅从对话提取信息,不要混入示例内容
+## Memory Structure
+Output format must be a parsable JSON string, no explanation, comments or descriptions needed. Only extract information from dialogue when saving memory, do not mix in example content.
```json
{
- "时空档案": {
- "身份图谱": {
- "现用名": "",
- "特征标记": []
+ "TimeSpaceArchives": {
+ "IdentityGraph": {
+ "CurrentName": "",
+ "FeatureTags": []
},
- "记忆立方": [
+ "MemoryCube": [
{
- "事件": "入职新公司",
- "时间戳": "2024-03-20",
- "情感值": 0.9,
- "关联项": ["下午茶"],
- "保鲜期": 30
+ "Event": "Joined new company",
+ "Timestamp": "2024-03-20",
+ "EmotionalValue": 0.9,
+ "RelatedItems": ["Afternoon Tea"],
+ "ShelfLife": 30
}
]
},
- "关系网络": {
- "高频话题": {"职场": 12},
- "暗线联系": [""]
+ "RelationshipNetwork": {
+ "HighFreqTopics": {"Work": 12},
+ "HiddenConnections": [""]
},
- "待响应": {
- "紧急事项": ["需立即处理的任务"],
- "潜在关怀": ["可主动提供的帮助"]
+ "PendingResponse": {
+ "UrgentMatters": ["Tasks needing immediate attention"],
+ "PotentialCare": ["Help that can be proactively offered"]
},
- "高光语录": [
- "最打动人心的瞬间,强烈的情感表达,user的原话"
+ "HighlightQuotes": [
+ "Most touching moments, strong emotional expressions, user's original words"
]
}
```
@@ -78,7 +78,7 @@ short_term_memory_prompt = """
def extract_json_data(json_code):
start = json_code.find("```json")
- # 从start开始找到下一个```结束
+ # Find next ``` end from start
end = json_code.find("```", start + 1)
# print("start:", start, "end:", end)
if start == -1 or end == -1:
@@ -111,7 +111,7 @@ class MemoryProvider(MemoryProviderBase):
self.load_memory(summary_memory)
def load_memory(self, summary_memory):
- # api获取到总结记忆后直接返回
+ # Return directly after API gets summary memory
if summary_memory or not self.save_to_file:
self.short_memory = summary_memory
return
@@ -133,11 +133,11 @@ class MemoryProvider(MemoryProviderBase):
yaml.dump(all_memory, f, allow_unicode=True)
async def save_memory(self, msgs, session_id=None):
- # 打印使用的模型信息
+ # Print model info used
model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__))
- logger.bind(tag=TAG).debug(f"使用记忆保存模型: {model_info}")
+ logger.bind(tag=TAG).debug(f"Using memory save model: {model_info}")
api_key = getattr(self.llm, "api_key", None)
- memory_key_msg = check_model_key("记忆总结专用LLM", api_key)
+ memory_key_msg = check_model_key("Memory Summary LLM", api_key)
if memory_key_msg:
logger.bind(tag=TAG).error(memory_key_msg)
if self.llm is None:
@@ -154,12 +154,12 @@ class MemoryProvider(MemoryProviderBase):
elif msg.role == "assistant":
msgStr += f"Assistant: {msg.content}\n"
if self.short_memory and len(self.short_memory) > 0:
- msgStr += "历史记忆:\n"
+ msgStr += "History Memory:\n"
msgStr += self.short_memory
- # 当前时间
+ # Current Time
time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
- msgStr += f"当前时间:{time_str}"
+ msgStr += f"Current Time: {time_str}"
if self.save_to_file:
result = self.llm.response_no_stream(
@@ -170,13 +170,13 @@ class MemoryProvider(MemoryProviderBase):
)
json_str = extract_json_data(result)
try:
- json.loads(json_str) # 检查json格式是否正确
+ json.loads(json_str) # Check if json format is correct
self.short_memory = json_str
self.save_memory_to_file()
except Exception as e:
print("Error:", e)
else:
- # 当save_to_file为False时,调用Java端的聊天记录总结接口
+ # When save_to_file is False, call chat record summary interface on Java side
summary_id = session_id if session_id else self.role_id
await generate_and_save_chat_summary(summary_id)
logger.bind(tag=TAG).info(
diff --git a/main/xiaozhi-server/core/providers/memory/nomem/nomem.py b/main/xiaozhi-server/core/providers/memory/nomem/nomem.py
index 6fe0a2be9..4cdc14ee9 100644
--- a/main/xiaozhi-server/core/providers/memory/nomem/nomem.py
+++ b/main/xiaozhi-server/core/providers/memory/nomem/nomem.py
@@ -1,5 +1,5 @@
"""
-不使用记忆,可以选择此模块
+This module can be selected if no memory is used
"""
from ..base import MemoryProviderBase, logger
diff --git a/main/xiaozhi-server/core/providers/tools/base/tool_executor.py b/main/xiaozhi-server/core/providers/tools/base/tool_executor.py
index 7685e7c2d..562e6f0ee 100644
--- a/main/xiaozhi-server/core/providers/tools/base/tool_executor.py
+++ b/main/xiaozhi-server/core/providers/tools/base/tool_executor.py
@@ -1,4 +1,4 @@
-"""工具执行器基类定义"""
+"""Tool executor base class definition"""
from abc import ABC, abstractmethod
from typing import Dict, Any
@@ -7,21 +7,21 @@ from plugins_func.register import ActionResponse
class ToolExecutor(ABC):
- """工具执行器抽象基类"""
+ """Tool executor abstract base class"""
@abstractmethod
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行工具调用"""
+ """Execute tool call"""
pass
@abstractmethod
def get_tools(self) -> Dict[str, ToolDefinition]:
- """获取该执行器管理的所有工具"""
+ """Get all tools managed by this executor"""
pass
@abstractmethod
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定工具"""
+ """Check if specified tool exists"""
pass
diff --git a/main/xiaozhi-server/core/providers/tools/base/tool_types.py b/main/xiaozhi-server/core/providers/tools/base/tool_types.py
index 91466fad9..dad79b420 100644
--- a/main/xiaozhi-server/core/providers/tools/base/tool_types.py
+++ b/main/xiaozhi-server/core/providers/tools/base/tool_types.py
@@ -1,4 +1,4 @@
-"""工具系统的类型定义"""
+"""Type definitions for the tool system"""
from enum import Enum
@@ -8,20 +8,20 @@ from plugins_func.register import Action
class ToolType(Enum):
- """工具类型枚举"""
+ """Tool type enumeration"""
- SERVER_PLUGIN = "server_plugin" # 服务端插件
- SERVER_MCP = "server_mcp" # 服务端MCP
- DEVICE_IOT = "device_iot" # 设备端IoT
- DEVICE_MCP = "device_mcp" # 设备端MCP
- MCP_ENDPOINT = "mcp_endpoint" # MCP接入点
+ SERVER_PLUGIN = "server_plugin" # Server Plugin
+ SERVER_MCP = "server_mcp" # Server MCP
+ DEVICE_IOT = "device_iot" # Device IoT
+ DEVICE_MCP = "device_mcp" # Device MCP
+ MCP_ENDPOINT = "mcp_endpoint" # MCP Endpoint
@dataclass
class ToolDefinition:
- """工具定义"""
+ """Tool definition"""
- name: str # 工具名称
- description: Dict[str, Any] # 工具描述(OpenAI函数调用格式)
- tool_type: ToolType # 工具类型
- parameters: Optional[Dict[str, Any]] = None # 额外参数
+ name: str # Tool name
+ description: Dict[str, Any] # Tool description (OpenAI function definition format)
+ tool_type: ToolType # Tool type
+ parameters: Optional[Dict[str, Any]] = None # Extra parameters
diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py b/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py
index 81df02ad3..eecfb863c 100644
--- a/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py
+++ b/main/xiaozhi-server/core/providers/tools/device_iot/iot_descriptor.py
@@ -1,4 +1,4 @@
-"""IoT设备描述符定义"""
+"""IoT device descriptor definition"""
from config.logger import setup_logging
@@ -7,7 +7,7 @@ logger = setup_logging()
class IotDescriptor:
- """IoT设备描述符"""
+ """IoT device descriptor"""
def __init__(self, name, description, properties, methods):
self.name = name
@@ -15,7 +15,7 @@ class IotDescriptor:
self.properties = []
self.methods = []
- # 根据描述创建属性
+ # Create properties from description
if properties is not None:
for key, value in properties.items():
property_item = {}
@@ -29,13 +29,13 @@ class IotDescriptor:
property_item["value"] = ""
self.properties.append(property_item)
- # 根据描述创建方法
+ # Create methods from description
if methods is not None:
for key, value in methods.items():
method = {}
method["description"] = value["description"]
method["name"] = key
- # 检查方法是否有参数
+ # Check if method has parameters
if "parameters" in value:
method["parameters"] = {}
for k, v in value["parameters"].items():
diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py b/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py
index 7be9e1123..855b5ecd3 100644
--- a/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py
+++ b/main/xiaozhi-server/core/providers/tools/device_iot/iot_executor.py
@@ -1,4 +1,4 @@
-"""设备端IoT工具执行器"""
+"""IoT Device Tool Executor"""
import json
import asyncio
@@ -8,7 +8,7 @@ from plugins_func.register import Action, ActionResponse
class DeviceIoTExecutor(ToolExecutor):
- """设备端IoT工具执行器"""
+ """IoT Device Tool Executor"""
def __init__(self, conn):
self.conn = conn
@@ -17,16 +17,16 @@ class DeviceIoTExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行设备端IoT工具"""
+ """Execute IoT Device Tool"""
if not self.has_tool(tool_name):
return ActionResponse(
- action=Action.NOTFOUND, response=f"IoT工具 {tool_name} 不存在"
+ action=Action.NOTFOUND, response=f"IoT tool {tool_name} not found"
)
try:
- # 解析工具名称,获取设备名和操作类型
+ # Parse tool name to get device name and operation type
if tool_name.startswith("get_"):
- # 查询操作:get_devicename_property
+ # Query operation: get_devicename_property
parts = tool_name.split("_", 2)
if len(parts) >= 3:
device_name = parts[1]
@@ -34,9 +34,9 @@ class DeviceIoTExecutor(ToolExecutor):
value = await self._get_iot_status(device_name, property_name)
if value is not None:
- # 处理响应模板
+ # Handle response template
response_success = arguments.get(
- "response_success", "查询成功:{value}"
+ "response_success", "Query successful: {value}"
)
response = response_success.replace("{value}", str(value))
@@ -46,36 +46,36 @@ class DeviceIoTExecutor(ToolExecutor):
)
else:
response_failure = arguments.get(
- "response_failure", f"无法获取{device_name}的状态"
+ "response_failure", f"Cannot get status for {device_name}"
)
return ActionResponse(
action=Action.ERROR, response=response_failure
)
else:
- # 控制操作:devicename_method
+ # Control operation: devicename_method
parts = tool_name.split("_", 1)
if len(parts) >= 2:
device_name = parts[0]
method_name = parts[1]
- # 提取控制参数(排除响应参数)
+ # Extract control parameters (exclude response parameters)
control_params = {
k: v
for k, v in arguments.items()
if k not in ["response_success", "response_failure"]
}
- # 发送IoT控制命令
+ # Send IoT control command
await self._send_iot_command(
device_name, method_name, control_params
)
- # 等待状态更新
+ # Wait for status update
await asyncio.sleep(0.1)
- response_success = arguments.get("response_success", "操作成功")
+ response_success = arguments.get("response_success", "Operation successful")
- # 处理响应中的占位符
+ # Handle placeholders in response
for param_name, param_value in control_params.items():
placeholder = "{" + param_name + "}"
if placeholder in response_success:
@@ -93,14 +93,14 @@ class DeviceIoTExecutor(ToolExecutor):
result=response_success,
)
- return ActionResponse(action=Action.ERROR, response="无法解析IoT工具名称")
+ return ActionResponse(action=Action.ERROR, response="Cannot parse IoT tool name")
except Exception as e:
- response_failure = arguments.get("response_failure", "操作失败")
+ response_failure = arguments.get("response_failure", "Operation failed")
return ActionResponse(action=Action.ERROR, response=response_failure)
async def _get_iot_status(self, device_name: str, property_name: str):
- """获取IoT设备状态"""
+ """Get IoT device status"""
for key, value in self.conn.iot_descriptors.items():
if key.lower() == device_name.lower():
for property_item in value.properties:
@@ -111,7 +111,7 @@ class DeviceIoTExecutor(ToolExecutor):
async def _send_iot_command(
self, device_name: str, method_name: str, parameters: Dict[str, Any]
):
- """发送IoT控制命令"""
+ """Send IoT control command"""
for key, value in self.conn.iot_descriptors.items():
if key.lower() == device_name.lower():
for method in value.methods:
@@ -130,15 +130,15 @@ class DeviceIoTExecutor(ToolExecutor):
await self.conn.websocket.send(send_message)
return
- raise Exception(f"未找到设备{device_name}的方法{method_name}")
+ raise Exception(f"Method {method_name} not found for device {device_name}")
def register_iot_tools(self, descriptors: list):
- """注册IoT工具"""
+ """Register IoT Tools"""
for descriptor in descriptors:
device_name = descriptor["name"]
device_desc = descriptor["description"]
- # 注册查询工具
+ # Register query tool
if "properties" in descriptor:
for prop_name, prop_info in descriptor["properties"].items():
tool_name = f"get_{device_name.lower()}_{prop_name.lower()}"
@@ -147,17 +147,17 @@ class DeviceIoTExecutor(ToolExecutor):
"type": "function",
"function": {
"name": tool_name,
- "description": f"查询{device_desc}的{prop_info['description']}",
+ "description": f"Query {prop_info['description']} of {device_desc}",
"parameters": {
"type": "object",
"properties": {
"response_success": {
"type": "string",
- "description": f"查询成功时的友好回复,必须使用{{value}}作为占位符表示查询到的值",
+ "description": f"Friendly response when query succeeds, must use {{value}} as placeholder for the value",
},
"response_failure": {
"type": "string",
- "description": f"查询失败时的友好回复",
+ "description": f"Friendly response when query fails",
},
},
"required": ["response_success", "response_failure"],
@@ -171,16 +171,16 @@ class DeviceIoTExecutor(ToolExecutor):
tool_type=ToolType.DEVICE_IOT,
)
- # 注册控制工具
+ # Register control tool
if "methods" in descriptor:
for method_name, method_info in descriptor["methods"].items():
tool_name = f"{device_name.lower()}_{method_name.lower()}"
- # 构建参数
+ # Build parameters
parameters = {}
required_params = []
- # 添加方法的原始参数
+ # Add original method parameters
if "parameters" in method_info:
parameters.update(
{
@@ -195,16 +195,16 @@ class DeviceIoTExecutor(ToolExecutor):
)
required_params.extend(method_info["parameters"].keys())
- # 添加响应参数
+ # Add response parameters
parameters.update(
{
"response_success": {
"type": "string",
- "description": "操作成功时的友好回复",
+ "description": "Friendly response when operation succeeds",
},
"response_failure": {
"type": "string",
- "description": "操作失败时的友好回复",
+ "description": "Friendly response when operation fails",
},
}
)
@@ -230,9 +230,9 @@ class DeviceIoTExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
- """获取所有设备端IoT工具"""
+ """Get all IoT device tools"""
return self.iot_tools.copy()
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定的设备端IoT工具"""
+ """Check if specified IoT device tool exists"""
return tool_name in self.iot_tools
diff --git a/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py b/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py
index 63992f273..8f7d65b38 100644
--- a/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py
+++ b/main/xiaozhi-server/core/providers/tools/device_iot/iot_handler.py
@@ -1,4 +1,4 @@
-"""IoT设备支持模块,提供IoT设备描述符和状态处理"""
+"""IoT device support module, provides IoT device descriptor and status handling"""
import asyncio
from config.logger import setup_logging
@@ -9,7 +9,7 @@ logger = setup_logging()
async def handleIotDescriptors(conn, descriptors):
- """处理物联网描述"""
+ """Handle IoT descriptors"""
wait_max_time = 5
while (
not hasattr(conn, "func_handler")
@@ -19,31 +19,31 @@ async def handleIotDescriptors(conn, descriptors):
await asyncio.sleep(1)
wait_max_time -= 1
if wait_max_time <= 0:
- logger.bind(tag=TAG).debug("连接对象没有func_handler")
+ logger.bind(tag=TAG).debug("Connection object has no func_handler")
return
functions_changed = False
for descriptor in descriptors:
- # 如果descriptor没有properties和methods,则直接跳过
+ # If descriptor has no properties and methods, skip it
if "properties" not in descriptor and "methods" not in descriptor:
continue
- # 处理缺失properties的情况
+ # Handle missing properties
if "properties" not in descriptor:
descriptor["properties"] = {}
- # 从methods中提取所有参数作为properties
+ # Extract all parameters from methods as properties
if "methods" in descriptor:
for method_name, method_info in descriptor["methods"].items():
if "parameters" in method_info:
for param_name, param_info in method_info["parameters"].items():
- # 将参数信息转换为属性信息
+ # Convert parameter information to property information
descriptor["properties"][param_name] = {
"description": param_info["description"],
"type": param_info["type"],
}
- # 创建IOT设备描述符
+ # Create IOT device descriptor
iot_descriptor = IotDescriptor(
descriptor["name"],
descriptor["description"],
@@ -53,16 +53,16 @@ async def handleIotDescriptors(conn, descriptors):
conn.iot_descriptors[descriptor["name"]] = iot_descriptor
functions_changed = True
- # 如果注册了新函数,更新function描述列表
+ # If new functions are registered, update function description list
if functions_changed and hasattr(conn, "func_handler"):
- # 注册IoT工具到统一工具处理器
+ # Register IoT tools to unified tool handler
await conn.func_handler.register_iot_tools(descriptors)
conn.func_handler.current_support_functions()
async def handleIotStatus(conn, states):
- """处理物联网状态"""
+ """Handle IoT status"""
for state in states:
for key, value in conn.iot_descriptors.items():
if key == state["name"]:
@@ -71,13 +71,13 @@ async def handleIotStatus(conn, states):
if property_item["name"] == k:
if type(v) != type(property_item["value"]):
logger.bind(tag=TAG).error(
- f"属性{property_item['name']}的值类型不匹配"
+ f"Property {property_item['name']} value type mismatch"
)
break
else:
property_item["value"] = v
logger.bind(tag=TAG).info(
- f"物联网状态更新: {key} , {property_item['name']} = {v}"
+ f"IoT status updated: {key} , {property_item['name']} = {v}"
)
break
break
diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py
index 75aa22b55..32b6680da 100644
--- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py
+++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_client.py
@@ -1,4 +1,4 @@
-"""设备端MCP客户端定义"""
+"""Device end MCP client definition"""
import asyncio
from concurrent.futures import Future
@@ -10,7 +10,7 @@ logger = setup_logging()
class MCPClient:
- """设备端MCP客户端,用于管理MCP状态和工具"""
+ """Device end MCP client, used to manage MCP status and tools"""
def __init__(self):
self.tools = {} # sanitized_name -> tool_data
diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py
index 9f4be061f..0b4f01306 100644
--- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py
+++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_executor.py
@@ -1,4 +1,4 @@
-"""设备端MCP工具执行器"""
+"""Device end MCP tool executor"""
from typing import Dict, Any
from ..base import ToolType, ToolDefinition, ToolExecutor
@@ -7,7 +7,7 @@ from .mcp_handler import call_mcp_tool
class DeviceMCPExecutor(ToolExecutor):
- """设备端MCP工具执行器"""
+ """Device end MCP tool executor"""
def __init__(self, conn):
self.conn = conn
@@ -15,26 +15,26 @@ class DeviceMCPExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行设备端MCP工具"""
+ """Execute device end MCP tool"""
if not hasattr(conn, "mcp_client") or not conn.mcp_client:
return ActionResponse(
action=Action.ERROR,
- response="设备端MCP客户端未初始化",
+ response="Device end MCP client not initialized",
)
if not await conn.mcp_client.is_ready():
return ActionResponse(
action=Action.ERROR,
- response="设备端MCP客户端未准备就绪",
+ response="Device end MCP client not ready",
)
try:
- # 转换参数为JSON字符串
+ # Convert parameters to JSON string
import json
args_str = json.dumps(arguments) if arguments else "{}"
- # 调用设备端MCP工具
+ # Call device end MCP tool
result = await call_mcp_tool(conn, conn.mcp_client, tool_name, args_str)
resultJson = None
@@ -44,7 +44,7 @@ class DeviceMCPExecutor(ToolExecutor):
except Exception as e:
pass
- # 视觉大模型不经过二次LLM处理
+ # Visual large models do not go through secondary LLM processing
if (
resultJson is not None
and isinstance(resultJson, dict)
@@ -63,7 +63,7 @@ class DeviceMCPExecutor(ToolExecutor):
return ActionResponse(action=Action.ERROR, response=str(e))
def get_tools(self) -> Dict[str, ToolDefinition]:
- """获取所有设备端MCP工具"""
+ """Get all device end MCP tools"""
if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client:
return {}
@@ -82,7 +82,7 @@ class DeviceMCPExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定的设备端MCP工具"""
+ """Check if there is a specified device end MCP tool"""
if not hasattr(self.conn, "mcp_client") or not self.conn.mcp_client:
return False
diff --git a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py
index 457b22fc8..43853184b 100644
--- a/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py
+++ b/main/xiaozhi-server/core/providers/tools/device_mcp/mcp_handler.py
@@ -1,8 +1,10 @@
-"""设备端MCP客户端支持模块"""
+"""Device-side MCP Client Support Module"""
import json
import asyncio
import re
+import re
+from datetime import datetime
from concurrent.futures import Future
from core.utils.util import get_vision_url, sanitize_tool_name
from core.utils.auth import AuthToken
@@ -13,7 +15,7 @@ logger = setup_logging()
class MCPClient:
- """设备端MCP客户端,用于管理MCP状态和工具"""
+ """Device-side MCP Client for managing state and tools"""
def __init__(self):
self.tools = {} # sanitized_name -> tool_data
@@ -28,11 +30,9 @@ class MCPClient:
return name in self.tools
def get_available_tools(self) -> list:
- # Check if the cache is valid
if self._cached_available_tools is not None:
return self._cached_available_tools
- # If cache is not valid, regenerate the list
result = []
for tool_name, tool_data in self.tools.items():
function_def = {
@@ -46,7 +46,7 @@ class MCPClient:
}
result.append({"type": "function", "function": function_def})
- self._cached_available_tools = result # Store the generated list in cache
+ self._cached_available_tools = result
return result
async def is_ready(self) -> bool:
@@ -62,9 +62,8 @@ class MCPClient:
sanitized_name = sanitize_tool_name(tool_data["name"])
self.tools[sanitized_name] = tool_data
self.name_mapping[sanitized_name] = tool_data["name"]
- self._cached_available_tools = (
- None # Invalidate the cache when a tool is added
- )
+ logger.bind(tag=TAG).debug(f"Registered MCP tool: {sanitized_name} (original: {tool_data['name']})")
+ self._cached_available_tools = None # Invalidate cache
async def get_next_id(self) -> int:
async with self.lock:
@@ -96,64 +95,68 @@ class MCPClient:
self.call_results.pop(id)
+async def _background_tool_refresh(conn):
+ """Refreshes LLM tools in a separate thread to prevent blocking the network"""
+ try:
+ # Offload synchronous work to threads
+ await asyncio.to_thread(conn.func_handler.tool_manager.refresh_tools)
+ await asyncio.to_thread(conn.func_handler.current_support_functions)
+ logger.bind(tag=TAG).info("LLM tool definitions refreshed in background.")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Background tool refresh failed: {e}")
+
+
async def send_mcp_message(conn, payload: dict):
- """Helper to send MCP messages, encapsulating common logic."""
+ """Helper to send MCP messages"""
if not conn.features.get("mcp"):
- logger.bind(tag=TAG).warning("客户端不支持MCP,无法发送MCP消息")
+ logger.bind(tag=TAG).warning("Client does not support MCP, skipping message")
return
message = json.dumps({"type": "mcp", "payload": payload})
try:
await conn.websocket.send(message)
- logger.bind(tag=TAG).debug(f"成功发送MCP消息: {message}")
+ logger.bind(tag=TAG).debug(f"MCP message sent: {payload.get('method', 'response')}")
except Exception as e:
- logger.bind(tag=TAG).error(f"发送MCP消息失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to send MCP message: {e}")
async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
- """处理MCP消息,包括初始化、工具列表和工具调用响应等"""
- logger.bind(tag=TAG).debug(f"处理MCP消息: {str(payload)[:100]}")
+ """Process incoming MCP messages"""
+ logger.bind(tag=TAG).debug("Processing incoming MCP payload...")
if not isinstance(payload, dict):
- logger.bind(tag=TAG).error("MCP消息缺少payload字段或格式错误")
+ logger.bind(tag=TAG).error("MCP message missing payload or has invalid format")
return
- # Handle result
+ # Handle result payloads
if "result" in payload:
result = payload["result"]
msg_id = int(payload.get("id", 0))
- # Check for tool call response first
if msg_id in mcp_client.call_results:
- logger.bind(tag=TAG).debug(
- f"收到工具调用响应,ID: {msg_id}, 结果: {result}"
- )
+ logger.bind(tag=TAG).debug(f"Received tool call response for ID: {msg_id}")
await mcp_client.resolve_call_result(msg_id, result)
return
if msg_id == 1: # mcpInitializeID
- logger.bind(tag=TAG).debug("收到MCP初始化响应")
+ logger.bind(tag=TAG).debug("Received MCP initialization response")
server_info = result.get("serverInfo")
if isinstance(server_info, dict):
name = server_info.get("name")
version = server_info.get("version")
- logger.bind(tag=TAG).debug(
- f"客户端MCP服务器信息: name={name}, version={version}"
- )
+ logger.bind(tag=TAG).info(f"Client MCP Server: {name} v{version}")
return
elif msg_id == 2: # mcpToolsListID
- logger.bind(tag=TAG).debug("收到MCP工具列表响应")
+ logger.bind(tag=TAG).debug("Received MCP tools list response")
if isinstance(result, dict) and "tools" in result:
tools_data = result["tools"]
if not isinstance(tools_data, list):
- logger.bind(tag=TAG).error("工具列表格式错误")
+ logger.bind(tag=TAG).error("Tool list format is invalid")
return
- logger.bind(tag=TAG).info(
- f"客户端设备支持的工具数量: {len(tools_data)}"
- )
+ logger.bind(tag=TAG).info(f"Client device supports {len(tools_data)} tools")
for i, tool in enumerate(tools_data):
if not isinstance(tool, dict):
@@ -177,175 +180,155 @@ async def handle_mcp_message(conn, mcp_client: MCPClient, payload: dict):
"inputSchema": input_schema,
}
await mcp_client.add_tool(new_tool)
- logger.bind(tag=TAG).debug(f"客户端工具 #{i+1}: {name}")
- # 替换所有工具描述中的工具名称
+ # Replace tool names in descriptions for consistency
for tool_data in mcp_client.tools.values():
if "description" in tool_data:
description = tool_data["description"]
- # 遍历所有工具名称进行替换
- for (
- sanitized_name,
- original_name,
- ) in mcp_client.name_mapping.items():
- description = description.replace(
- original_name, sanitized_name
- )
+ for sanitized_name, original_name in mcp_client.name_mapping.items():
+ description = description.replace(original_name, sanitized_name)
tool_data["description"] = description
next_cursor = result.get("nextCursor", "")
if next_cursor:
- logger.bind(tag=TAG).debug(f"有更多工具,nextCursor: {next_cursor}")
+ logger.bind(tag=TAG).debug(f"Paginating tools, nextCursor: {next_cursor}")
await send_mcp_tools_list_continue_request(conn, next_cursor)
else:
await mcp_client.set_ready(True)
- logger.bind(tag=TAG).debug("所有工具已获取,MCP客户端准备就绪")
+ logger.bind(tag=TAG).info(f"All tools retrieved, MCP client ready. Available tools: {list(mcp_client.tools.keys())}")
- # 刷新工具缓存,确保MCP工具被包含在函数列表中
+ # Launch tool refresh in background to prevent blocking
if hasattr(conn, "func_handler") and conn.func_handler:
- conn.func_handler.tool_manager.refresh_tools()
- conn.func_handler.current_support_functions()
+ asyncio.create_task(_background_tool_refresh(conn))
return
- # Handle method calls (requests from the client)
+ # Handle incoming method requests from client
elif "method" in payload:
method = payload["method"]
- logger.bind(tag=TAG).info(f"收到MCP客户端请求: {method}")
+ logger.bind(tag=TAG).info(f"Received MCP client request: {method}")
+ # Handle error payloads
elif "error" in payload:
error_data = payload["error"]
- error_msg = error_data.get("message", "未知错误")
- logger.bind(tag=TAG).error(f"收到MCP错误响应: {error_msg}")
+ error_msg = error_data.get("message", "Unknown error")
+ logger.bind(tag=TAG).error(f"Received MCP error response: {error_msg}")
msg_id = int(payload.get("id", 0))
if msg_id in mcp_client.call_results:
- await mcp_client.reject_call_result(
- msg_id, Exception(f"MCP错误: {error_msg}")
- )
+ await mcp_client.reject_call_result(msg_id, Exception(f"MCP Error: {error_msg}"))
+#async def send_mcp_initialize_message(conn):
+# """Send MCP initialization message"""
+# vision_url = get_vision_url(conn.config)
+# auth = AuthToken(conn.config["server"]["auth_key"])
+# token = auth.generate_token(conn.headers.get("device-id"))
+#
+# vision = {"url": vision_url, "token": token}
+#
+# payload = {
+# "jsonrpc": "2.0",
+# "id": 1,
+# "method": "initialize",
+# "params": {
+# "protocolVersion": "2024-11-05",
+# "capabilities": {
+# "roots": {"listChanged": True},
+# "sampling": {},
+# "vision": vision,
+# },
+# "clientInfo": {"name": "XiaozhiClient", "version": "1.0.0"},
+# },
+# }
+# logger.bind(tag=TAG).debug("Sending MCP initialize message...")
+# await send_mcp_message(conn, payload)
+
async def send_mcp_initialize_message(conn):
- """发送MCP初始化消息"""
-
- vision_url = get_vision_url(conn.config)
-
- # 密钥生成token
- auth = AuthToken(conn.config["server"]["auth_key"])
- token = auth.generate_token(conn.headers.get("device-id"))
-
- vision = {
- "url": vision_url,
- "token": token,
- }
-
+ """Simplified MCP initialization to prevent DNS/Auth hangs"""
+ # We are skipping get_vision_url and AuthToken generation for now
payload = {
"jsonrpc": "2.0",
- "id": 1, # mcpInitializeID
+ "id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"roots": {"listChanged": True},
"sampling": {},
- "vision": vision,
- },
- "clientInfo": {
- "name": "XiaozhiClient",
- "version": "1.0.0",
+ # Vision and Auth are omitted to test for network hangs
},
+ "clientInfo": {"name": "XiaozhiClient", "version": "1.0.0"},
},
}
- logger.bind(tag=TAG).debug("发送MCP初始化消息")
+ logger.bind(tag=TAG).debug("Sending simplified MCP initialize message...")
await send_mcp_message(conn, payload)
-
async def send_mcp_tools_list_request(conn):
- """发送MCP工具列表请求"""
- payload = {
- "jsonrpc": "2.0",
- "id": 2, # mcpToolsListID
- "method": "tools/list",
- }
- logger.bind(tag=TAG).debug("发送MCP工具列表请求")
+ """Send MCP tools list request"""
+ payload = {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
+ logger.bind(tag=TAG).debug("Requesting MCP tool list...")
await send_mcp_message(conn, payload)
async def send_mcp_tools_list_continue_request(conn, cursor: str):
- """发送带有cursor的MCP工具列表请求"""
+ """Send continuation request for tools list"""
payload = {
"jsonrpc": "2.0",
- "id": 2, # mcpToolsListID (same ID for continuation)
+ "id": 2,
"method": "tools/list",
"params": {"cursor": cursor},
}
- logger.bind(tag=TAG).info(f"发送带cursor的MCP工具列表请求: {cursor}")
+ logger.bind(tag=TAG).info(f"Continuing tool list request with cursor: {cursor}")
await send_mcp_message(conn, payload)
-async def call_mcp_tool(
- conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30
-):
- """
- 调用指定的工具,并等待响应
- """
+async def call_mcp_tool(conn, mcp_client: MCPClient, tool_name: str, args: str = "{}", timeout: int = 30):
+ """Call a specified MCP tool and await response"""
if not await mcp_client.is_ready():
- raise RuntimeError("MCP客户端尚未准备就绪")
+ raise RuntimeError("MCP client is not ready yet")
if not mcp_client.has_tool(tool_name):
- raise ValueError(f"工具 {tool_name} 不存在")
+ raise ValueError(f"Tool {tool_name} does not exist")
tool_call_id = await mcp_client.get_next_id()
result_future = asyncio.Future()
await mcp_client.register_call_result_future(tool_call_id, result_future)
- # 处理参数
try:
if isinstance(args, str):
- # 确保字符串是有效的JSON
if not args.strip():
arguments = {}
else:
try:
- # 尝试直接解析
arguments = json.loads(args)
except json.JSONDecodeError:
- # 如果解析失败,尝试合并多个JSON对象
- try:
- # 使用正则表达式匹配所有JSON对象
- json_objects = re.findall(r"\{[^{}]*\}", args)
- if len(json_objects) > 1:
- # 合并所有JSON对象
- merged_dict = {}
- for json_str in json_objects:
- try:
- obj = json.loads(json_str)
- if isinstance(obj, dict):
- merged_dict.update(obj)
- except json.JSONDecodeError:
- continue
- if merged_dict:
- arguments = merged_dict
- else:
- raise ValueError(f"无法解析任何有效的JSON对象: {args}")
+ json_objects = re.findall(r"\{[^{}]*\}", args)
+ if len(json_objects) > 1:
+ merged_dict = {}
+ for json_str in json_objects:
+ try:
+ obj = json.loads(json_str)
+ if isinstance(obj, dict):
+ merged_dict.update(obj)
+ except json.JSONDecodeError:
+ continue
+ if merged_dict:
+ arguments = merged_dict
else:
- raise ValueError(f"参数JSON解析失败: {args}")
- except Exception as e:
- logger.bind(tag=TAG).error(
- f"参数JSON解析失败: {str(e)}, 原始参数: {args}"
- )
- raise ValueError(f"参数JSON解析失败: {str(e)}")
+ raise ValueError(f"Could not parse valid JSON from: {args}")
+ else:
+ raise ValueError(f"JSON parsing failed for args: {args}")
elif isinstance(args, dict):
arguments = args
else:
- raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}")
+ raise ValueError(f"Invalid args type: {type(args)}")
- # 确保参数是字典类型
if not isinstance(arguments, dict):
- raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}")
+ raise ValueError(f"Arguments must be a dictionary, got: {type(arguments)}")
except Exception as e:
if not isinstance(e, ValueError):
- raise ValueError(f"参数处理失败: {str(e)}")
+ raise ValueError(f"Argument processing failed: {str(e)}")
raise e
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
@@ -356,33 +339,78 @@ async def call_mcp_tool(
"params": {"name": actual_name, "arguments": arguments},
}
- logger.bind(tag=TAG).info(f"发送客户端mcp工具调用请求: {actual_name},参数: {args}")
+ logger.bind(tag=TAG).info(f"Initiating tool call: {actual_name} with args: {args}")
await send_mcp_message(conn, payload)
try:
- # Wait for response or timeout
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
- logger.bind(tag=TAG).info(
- f"客户端mcp工具调用 {actual_name} 成功,原始结果: {raw_result}"
- )
+ logger.bind(tag=TAG).info(f"Tool call {actual_name} successful")
if isinstance(raw_result, dict):
if raw_result.get("isError") is True:
- error_msg = raw_result.get(
- "error", "工具调用返回错误,但未提供具体错误信息"
- )
- raise RuntimeError(f"工具调用错误: {error_msg}")
+ error_msg = raw_result.get("error", "No detailed error provided")
+ raise RuntimeError(f"Tool execution error: {error_msg}")
content = raw_result.get("content")
if isinstance(content, list) and len(content) > 0:
if isinstance(content[0], dict) and "text" in content[0]:
- # 直接返回文本内容,不进行JSON解析
- return content[0]["text"]
- # 如果结果不是预期的格式,将其转换为字符串
+ result_text = content[0]["text"]
+
+ # Inject server time if this is the device status tool
+ if "get_device_status" in actual_name:
+ try:
+ status_data = json.loads(result_text)
+ if isinstance(status_data, dict):
+ status_data["server_timestamp"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
+ status_data["server_weekday"] = datetime.now().strftime("%A")
+ result_text = json.dumps(status_data, ensure_ascii=False)
+ except:
+ pass
+
+ return result_text
return str(raw_result)
except asyncio.TimeoutError:
await mcp_client.cleanup_call_result(tool_call_id)
- raise TimeoutError("工具调用请求超时")
+ raise TimeoutError("The tool call request timed out")
except Exception as e:
await mcp_client.cleanup_call_result(tool_call_id)
raise e
+
+async def sync_device_hardware_status(conn, tool_name="get_device_status"):
+ """Helper to fetch hardware status (battery, volume, charging, brightness) via MCP"""
+ try:
+ logger.bind(tag=TAG).info(f"Initiating MCP hardware sync via {tool_name}...")
+ res = await call_mcp_tool(conn, conn.mcp_client, tool_name)
+ data = json.loads(res)
+ if isinstance(data, dict):
+ # 1. Battery Sync
+ battery_data = data.get("battery") or data
+ bat = battery_data.get("level") if isinstance(battery_data, dict) else battery_data
+ if bat is not None:
+ conn.mcp_battery = str(bat)
+ logger.bind(tag=TAG).info(f"MCP hardware sync - battery: {bat}%")
+
+ charging = battery_data.get("charging") if isinstance(battery_data, dict) else None
+ if charging is not None:
+ conn.mcp_charging = "charging" if charging else "not charging"
+ logger.bind(tag=TAG).info(f"MCP hardware sync - charging: {conn.mcp_charging}")
+
+ # 2. Volume Sync
+ audio_data = data.get("audio_speaker") or data.get("audio") or data
+ vol = audio_data.get("volume") if isinstance(audio_data, dict) else audio_data
+ if vol is not None:
+ conn.mcp_volume = str(vol)
+ logger.bind(tag=TAG).info(f"MCP hardware sync - volume: {vol}%")
+
+ # 3. Brightness Sync
+ screen_data = data.get("screen") or data
+ bright = screen_data.get("brightness") if isinstance(screen_data, dict) else None
+ if bright is not None:
+ conn.mcp_brightness = str(bright)
+ logger.bind(tag=TAG).info(f"MCP hardware sync - brightness: {bright}%")
+
+ if bat is None and vol is None:
+ logger.bind(tag=TAG).warning(f"MCP hardware sync - no primary data found in response: {data}")
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"MCP hardware status sync failed: {e}")
+
diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py
index 4e9e5303f..16d4f9d8f 100644
--- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py
+++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_client.py
@@ -1,4 +1,4 @@
-"""MCP接入点客户端定义"""
+"""MCP endpoint client definition"""
import asyncio
from concurrent.futures import Future
@@ -10,7 +10,7 @@ logger = setup_logging()
class MCPEndpointClient:
- """MCP接入点客户端,用于管理MCP接入点状态和工具"""
+ """MCP endpoint client, used to manage MCP endpoint status and tools"""
def __init__(self, conn=None):
self.conn = conn
@@ -21,7 +21,7 @@ class MCPEndpointClient:
self.next_id = 1
self.lock = asyncio.Lock()
self._cached_available_tools = None # Cache for get_available_tools
- self.websocket = None # WebSocket连接
+ self.websocket = None # WebSocket connection
def has_tool(self, name: str) -> bool:
return name in self.tools
@@ -95,18 +95,18 @@ class MCPEndpointClient:
self.call_results.pop(id)
def set_websocket(self, websocket):
- """设置WebSocket连接"""
+ """Set WebSocket connection"""
self.websocket = websocket
async def send_message(self, message: str):
- """发送消息到MCP接入点"""
+ """Send message to MCP endpoint"""
if self.websocket:
await self.websocket.send(message)
else:
- raise RuntimeError("WebSocket连接未建立")
+ raise RuntimeError("WebSocket connection not established")
async def close(self):
- """关闭WebSocket连接"""
+ """Close WebSocket connection"""
if self.websocket:
await self.websocket.close()
self.websocket = None
diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py
index f2c9bac15..2c0b1b719 100644
--- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py
+++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_executor.py
@@ -1,4 +1,4 @@
-"""MCP接入点工具执行器"""
+"""MCP endpoint tool executor"""
from typing import Dict, Any
from ..base import ToolType, ToolDefinition, ToolExecutor
@@ -7,7 +7,7 @@ from .mcp_endpoint_handler import call_mcp_endpoint_tool
class MCPEndpointExecutor(ToolExecutor):
- """MCP接入点工具执行器"""
+ """MCP endpoint tool executor"""
def __init__(self, conn):
self.conn = conn
@@ -15,26 +15,26 @@ class MCPEndpointExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行MCP接入点工具"""
+ """Execute MCP endpoint tool"""
if not hasattr(conn, "mcp_endpoint_client") or not conn.mcp_endpoint_client:
return ActionResponse(
action=Action.ERROR,
- response="MCP接入点客户端未初始化",
+ response="MCP endpoint client not initialized",
)
if not await conn.mcp_endpoint_client.is_ready():
return ActionResponse(
action=Action.ERROR,
- response="MCP接入点客户端未准备就绪",
+ response="MCP endpoint client not ready",
)
try:
- # 转换参数为JSON字符串
+ # Convert parameters to JSON string
import json
args_str = json.dumps(arguments) if arguments else "{}"
- # 调用MCP接入点工具
+ # Call MCP endpoint tool
result = await call_mcp_endpoint_tool(
conn.mcp_endpoint_client, tool_name, args_str
)
@@ -46,7 +46,7 @@ class MCPEndpointExecutor(ToolExecutor):
except Exception as e:
pass
- # 视觉大模型不经过二次LLM处理
+ # Visual large models do not go through secondary LLM processing
if (
resultJson is not None
and isinstance(resultJson, dict)
@@ -65,7 +65,7 @@ class MCPEndpointExecutor(ToolExecutor):
return ActionResponse(action=Action.ERROR, response=str(e))
def get_tools(self) -> Dict[str, ToolDefinition]:
- """获取所有MCP接入点工具"""
+ """Get all MCP endpoint tools"""
if (
not hasattr(self.conn, "mcp_endpoint_client")
or not self.conn.mcp_endpoint_client
@@ -87,7 +87,7 @@ class MCPEndpointExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定的MCP接入点工具"""
+ """Check if there is a specified MCP endpoint tool"""
if (
not hasattr(self.conn, "mcp_endpoint_client")
or not self.conn.mcp_endpoint_client
diff --git a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py
index 8d9921cda..94b00865f 100644
--- a/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py
+++ b/main/xiaozhi-server/core/providers/tools/mcp_endpoint/mcp_endpoint_handler.py
@@ -1,4 +1,4 @@
-"""MCP接入点处理器"""
+"""MCP endpoint handler"""
import json
import asyncio
@@ -12,8 +12,8 @@ logger = setup_logging()
async def connect_mcp_endpoint(mcp_endpoint_url: str, conn=None) -> MCPEndpointClient:
- """连接到MCP接入点"""
- if not mcp_endpoint_url or "你的" in mcp_endpoint_url or mcp_endpoint_url == "null":
+ """Connect to MCP endpoint"""
+ if not mcp_endpoint_url or "your" in mcp_endpoint_url or mcp_endpoint_url == "null":
return None
try:
@@ -22,82 +22,82 @@ async def connect_mcp_endpoint(mcp_endpoint_url: str, conn=None) -> MCPEndpointC
mcp_client = MCPEndpointClient(conn)
mcp_client.set_websocket(websocket)
- # 启动消息监听器
+ # Start message listener
asyncio.create_task(_message_listener(mcp_client))
- # 发送初始化消息
+ # Send initialization message
await send_mcp_endpoint_initialize(mcp_client)
- # 发送初始化完成通知
+ # Send initialization completion notification
await send_mcp_endpoint_notification(mcp_client, "notifications/initialized")
- # 获取工具列表
+ # Get tools list
await send_mcp_endpoint_tools_list(mcp_client)
- logger.bind(tag=TAG).info("MCP接入点连接成功")
+ logger.bind(tag=TAG).info("MCP endpoint connection successful")
return mcp_client
except Exception as e:
- logger.bind(tag=TAG).error(f"连接MCP接入点失败: {e}")
+ logger.bind(tag=TAG).error(f"Connect to MCP endpoint failed: {e}")
return None
async def _message_listener(mcp_client: MCPEndpointClient):
- """监听MCP接入点消息"""
+ """Listen to MCP endpoint messages"""
try:
async for message in mcp_client.websocket:
await handle_mcp_endpoint_message(mcp_client, message)
except websockets.exceptions.ConnectionClosed:
- logger.bind(tag=TAG).info("MCP接入点连接已关闭")
+ logger.bind(tag=TAG).info("MCP endpoint connection closed")
except Exception as e:
- logger.bind(tag=TAG).error(f"MCP接入点消息监听器错误: {e}")
+ logger.bind(tag=TAG).error(f"MCP endpoint message listener error: {e}")
finally:
await mcp_client.set_ready(False)
async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: str):
- """处理MCP接入点消息"""
+ """Handle MCP endpoint message"""
try:
payload = json.loads(message)
- logger.bind(tag=TAG).debug(f"收到MCP接入点消息: {payload}")
+ logger.bind(tag=TAG).debug(f"Received MCP endpoint message: {payload}")
if not isinstance(payload, dict):
- logger.bind(tag=TAG).error("MCP接入点消息格式错误")
+ logger.bind(tag=TAG).error("MCP endpoint message format error")
return
# Handle result
if "result" in payload:
result = payload["result"]
- # 安全地获取消息ID,如果为None则使用0
+ # Safely get message ID, use 0 if None
msg_id_raw = payload.get("id")
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
# Check for tool call response first
if msg_id in mcp_client.call_results:
logger.bind(tag=TAG).debug(
- f"收到工具调用响应,ID: {msg_id}, 结果: {result}"
+ f"Received tool call response, ID: {msg_id}, result: {result}"
)
await mcp_client.resolve_call_result(msg_id, result)
return
if msg_id == 1: # mcpInitializeID
- logger.bind(tag=TAG).debug("收到MCP接入点初始化响应")
+ logger.bind(tag=TAG).debug("Received MCP endpoint initialization response")
if result is not None and isinstance(result, dict):
server_info = result.get("serverInfo")
if isinstance(server_info, dict):
name = server_info.get("name")
version = server_info.get("version")
logger.bind(tag=TAG).info(
- f"MCP接入点服务器信息: name={name}, version={version}"
+ f"MCP endpoint server information: name={name}, version={version}"
)
else:
logger.bind(tag=TAG).warning(
- "MCP接入点初始化响应结果为空或格式错误"
+ "MCP endpoint initialization response result is empty or format error"
)
return
elif msg_id == 2: # mcpToolsListID
- logger.bind(tag=TAG).debug("收到MCP接入点工具列表响应")
+ logger.bind(tag=TAG).debug("Received MCP endpoint tools list response")
if (
result is not None
and isinstance(result, dict)
@@ -105,11 +105,11 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
):
tools_data = result["tools"]
if not isinstance(tools_data, list):
- logger.bind(tag=TAG).error("工具列表格式错误")
+ logger.bind(tag=TAG).error("Tools list format error")
return
logger.bind(tag=TAG).info(
- f"MCP接入点支持的工具数量: {len(tools_data)}"
+ f"MCP endpoint supports {len(tools_data)} tools"
)
for i, tool in enumerate(tools_data):
@@ -142,13 +142,13 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
"inputSchema": input_schema,
}
await mcp_client.add_tool(new_tool)
- logger.bind(tag=TAG).debug(f"MCP接入点工具 #{i+1}: {name}")
+ logger.bind(tag=TAG).debug(f"MCP endpoint tool #{i+1}: {name}")
- # 替换所有工具描述中的工具名称
+ # Replace all tool names in tool descriptions
for tool_data in mcp_client.tools.values():
if "description" in tool_data:
description = tool_data["description"]
- # 遍历所有工具名称进行替换
+ # Iterate through all tool names for replacement
for (
sanitized_name,
original_name,
@@ -163,7 +163,7 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
)
if next_cursor:
logger.bind(tag=TAG).info(
- f"有更多工具,nextCursor: {next_cursor}"
+ f"More tools available, nextCursor: {next_cursor}"
)
await send_mcp_endpoint_tools_list_continue(
mcp_client, next_cursor
@@ -171,10 +171,10 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
else:
await mcp_client.set_ready(True)
logger.bind(tag=TAG).info(
- "所有MCP接入点工具已获取,客户端准备就绪"
+ "All MCP endpoint tools have been retrieved, client is ready"
)
- # 刷新工具缓存,确保MCP接入点工具被包含在函数列表中
+ # Refresh tool cache to ensure MCP endpoint tools are included in the function list
if (
hasattr(mcp_client, "conn")
and mcp_client.conn
@@ -185,44 +185,44 @@ async def handle_mcp_endpoint_message(mcp_client: MCPEndpointClient, message: st
mcp_client.conn.func_handler.current_support_functions()
logger.bind(tag=TAG).info(
- f"MCP接入点工具获取完成,共 {len(mcp_client.tools)} 个工具"
+ f"MCP endpoint tools retrieved, total {len(mcp_client.tools)} tools"
)
else:
logger.bind(tag=TAG).warning(
- "MCP接入点工具列表响应结果为空或格式错误"
+ "MCP endpoint tools list response result is empty or format error"
)
return
# Handle method calls (requests from the endpoint)
elif "method" in payload:
method = payload["method"]
- logger.bind(tag=TAG).info(f"收到MCP接入点请求: {method}")
+ logger.bind(tag=TAG).info(f"Received MCP endpoint request: {method}")
elif "error" in payload:
error_data = payload["error"]
- error_msg = error_data.get("message", "未知错误")
- logger.bind(tag=TAG).error(f"收到MCP接入点错误响应: {error_msg}")
+ error_msg = error_data.get("message", "Unknown error")
+ logger.bind(tag=TAG).error(f"Received MCP endpoint error response: {error_msg}")
- # 安全地获取消息ID,如果为None则使用0
+ # Safely get message ID, use 0 if None
msg_id_raw = payload.get("id")
msg_id = int(msg_id_raw) if msg_id_raw is not None else 0
if msg_id in mcp_client.call_results:
await mcp_client.reject_call_result(
- msg_id, Exception(f"MCP接入点错误: {error_msg}")
+ msg_id, Exception(f"MCP endpoint error: {error_msg}")
)
except json.JSONDecodeError as e:
- logger.bind(tag=TAG).error(f"MCP接入点消息JSON解析失败: {e}")
+ logger.bind(tag=TAG).error(f"MCP endpoint message JSON parsing failed: {e}")
except Exception as e:
- logger.bind(tag=TAG).error(f"处理MCP接入点消息时出错: {e}")
+ logger.bind(tag=TAG).error(f"Error processing MCP endpoint message: {e}")
import traceback
- logger.bind(tag=TAG).error(f"错误详情: {traceback.format_exc()}")
+ logger.bind(tag=TAG).error(f"Error details: {traceback.format_exc()}")
async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
- """发送MCP接入点初始化消息"""
+ """Send MCP endpoint initialization message"""
payload = {
"jsonrpc": "2.0",
"id": 1, # mcpInitializeID
@@ -240,38 +240,38 @@ async def send_mcp_endpoint_initialize(mcp_client: MCPEndpointClient):
},
}
message = json.dumps(payload)
- logger.bind(tag=TAG).info("发送MCP接入点初始化消息")
+ logger.bind(tag=TAG).info("Sending MCP endpoint initialization message")
await mcp_client.send_message(message)
async def send_mcp_endpoint_notification(mcp_client: MCPEndpointClient, method: str):
- """发送MCP接入点通知消息"""
+ """Send MCP endpoint notification message"""
payload = {
"jsonrpc": "2.0",
"method": method,
"params": {},
}
message = json.dumps(payload)
- logger.bind(tag=TAG).debug(f"发送MCP接入点通知: {method}")
+ logger.bind(tag=TAG).debug(f"Sending MCP endpoint notification: {method}")
await mcp_client.send_message(message)
async def send_mcp_endpoint_tools_list(mcp_client: MCPEndpointClient):
- """发送MCP接入点工具列表请求"""
+ """Send MCP endpoint tools list request"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID
"method": "tools/list",
}
message = json.dumps(payload)
- logger.bind(tag=TAG).debug("发送MCP接入点工具列表请求")
+ logger.bind(tag=TAG).debug("Sending MCP endpoint tools list request")
await mcp_client.send_message(message)
async def send_mcp_endpoint_tools_list_continue(
mcp_client: MCPEndpointClient, cursor: str
):
- """发送带有cursor的MCP接入点工具列表请求"""
+ """Send MCP endpoint tools list request with cursor"""
payload = {
"jsonrpc": "2.0",
"id": 2, # mcpToolsListID (same ID for continuation)
@@ -279,7 +279,7 @@ async def send_mcp_endpoint_tools_list_continue(
"params": {"cursor": cursor},
}
message = json.dumps(payload)
- logger.bind(tag=TAG).info(f"发送带cursor的MCP接入点工具列表请求: {cursor}")
+ logger.bind(tag=TAG).info(f"Sending MCP endpoint tools list request with cursor: {cursor}")
await mcp_client.send_message(message)
@@ -287,35 +287,35 @@ async def call_mcp_endpoint_tool(
mcp_client: MCPEndpointClient, tool_name: str, args: str = "{}", timeout: int = 30
):
"""
- 调用指定的MCP接入点工具,并等待响应
+ Call the specified MCP endpoint tool and wait for the response
"""
if not await mcp_client.is_ready():
- raise RuntimeError("MCP接入点客户端尚未准备就绪")
+ raise RuntimeError("MCP endpoint client is not ready")
if not mcp_client.has_tool(tool_name):
- raise ValueError(f"工具 {tool_name} 不存在")
+ raise ValueError(f"Tool {tool_name} does not exist")
tool_call_id = await mcp_client.get_next_id()
result_future = asyncio.Future()
await mcp_client.register_call_result_future(tool_call_id, result_future)
- # 处理参数
+ # Process arguments
try:
if isinstance(args, str):
- # 确保字符串是有效的JSON
+ # Ensure the string is a valid JSON
if not args.strip():
arguments = {}
else:
try:
- # 尝试直接解析
+ # Try direct parsing
arguments = json.loads(args)
except json.JSONDecodeError:
- # 如果解析失败,尝试合并多个JSON对象
+ # If parsing fails, try merging multiple JSON objects
try:
- # 使用正则表达式匹配所有JSON对象
+ # Use regex to match all JSON objects
json_objects = re.findall(r"\{[^{}]*\}", args)
if len(json_objects) > 1:
- # 合并所有JSON对象
+ # Merge all JSON objects
merged_dict = {}
for json_str in json_objects:
try:
@@ -327,26 +327,26 @@ async def call_mcp_endpoint_tool(
if merged_dict:
arguments = merged_dict
else:
- raise ValueError(f"无法解析任何有效的JSON对象: {args}")
+ raise ValueError(f"Unable to parse any valid JSON objects: {args}")
else:
- raise ValueError(f"参数JSON解析失败: {args}")
+ raise ValueError(f"Parameter JSON parsing failed: {args}")
except Exception as e:
logger.bind(tag=TAG).error(
- f"参数JSON解析失败: {str(e)}, 原始参数: {args}"
+ f"Parameter JSON parsing failed: {str(e)}, original parameter: {args}"
)
- raise ValueError(f"参数JSON解析失败: {str(e)}")
+ raise ValueError(f"Parameter JSON parsing failed: {str(e)}")
elif isinstance(args, dict):
arguments = args
else:
- raise ValueError(f"参数类型错误,期望字符串或字典,实际类型: {type(args)}")
+ raise ValueError(f"Parameter type error, expected string or dictionary, actual type: {type(args)}")
- # 确保参数是字典类型
+ # Ensure parameters are dictionary type
if not isinstance(arguments, dict):
- raise ValueError(f"参数必须是字典类型,实际类型: {type(arguments)}")
+ raise ValueError(f"Parameters must be dictionary type, actual type: {type(arguments)}")
except Exception as e:
if not isinstance(e, ValueError):
- raise ValueError(f"参数处理失败: {str(e)}")
+ raise ValueError(f"Parameter processing failed: {str(e)}")
raise e
actual_name = mcp_client.name_mapping.get(tool_name, tool_name)
@@ -359,7 +359,7 @@ async def call_mcp_endpoint_tool(
message = json.dumps(payload)
logger.bind(tag=TAG).info(
- f"发送MCP接入点工具调用请求: {actual_name},参数: {json.dumps(arguments, ensure_ascii=False)}"
+ f"Sending MCP endpoint tool call request: {actual_name}, parameters: {json.dumps(arguments, ensure_ascii=False)}"
)
await mcp_client.send_message(message)
@@ -367,26 +367,26 @@ async def call_mcp_endpoint_tool(
# Wait for response or timeout
raw_result = await asyncio.wait_for(result_future, timeout=timeout)
logger.bind(tag=TAG).info(
- f"MCP接入点工具调用 {actual_name} 成功,原始结果: {raw_result}"
+ f"MCP endpoint tool call {actual_name} successful, raw result: {raw_result}"
)
if isinstance(raw_result, dict):
if raw_result.get("isError") is True:
error_msg = raw_result.get(
- "error", "工具调用返回错误,但未提供具体错误信息"
+ "error", "Tool call returned error, but no specific error information provided"
)
- raise RuntimeError(f"工具调用错误: {error_msg}")
+ raise RuntimeError(f"Tool call error: {error_msg}")
content = raw_result.get("content")
if isinstance(content, list) and len(content) > 0:
if isinstance(content[0], dict) and "text" in content[0]:
- # 直接返回文本内容,不进行JSON解析
+ # Directly return text content, no JSON parsing
return content[0]["text"]
- # 如果结果不是预期的格式,将其转换为字符串
+ # If the result is not in the expected format, convert it to a string
return str(raw_result)
except asyncio.TimeoutError:
- await mcp_client.cleanup_call_result(tool_call_id)
- raise TimeoutError("工具调用请求超时")
+ await mcp_client.cleanup_call_result(tool_call_id) # Clean up call result
+ raise TimeoutError("Tool call request timed out")
except Exception as e:
await mcp_client.cleanup_call_result(tool_call_id)
raise e
diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py
index c8c42d79b..272641b32 100644
--- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py
+++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_client.py
@@ -1,4 +1,4 @@
-"""服务端MCP客户端"""
+"""Server MCP client"""
from __future__ import annotations
@@ -24,13 +24,13 @@ TAG = __name__
class ServerMCPClient:
- """服务端MCP客户端,用于连接和管理MCP服务"""
+ """Server MCP client, used to connect and manage MCP services"""
def __init__(self, config: Dict[str, Any]):
- """初始化服务端MCP客户端
+ """Initialize the server MCP client
Args:
- config: MCP服务配置字典
+ config: MCP server configuration dictionary
"""
self.logger = setup_logging()
self.config = config
@@ -51,7 +51,7 @@ class ServerMCPClient:
logging_callback: LoggingFnT | None = None,
message_handler: MessageHandlerFnT | None = None,
client_info: Implementation | None = None):
- """初始化MCP客户端连接"""
+ """Initialize the MCP client connection"""
if self._worker_task:
return
@@ -67,11 +67,10 @@ class ServerMCPClient:
await self._ready_evt.wait()
self.logger.bind(tag=TAG).info(
- f"服务端MCP客户端已连接,可用工具: {[name for name in self.name_mapping.values()]}"
- )
+ f"Server MCP client connected, available tools: {[name for name in self.name_mapping.values()]}")
async def cleanup(self):
- """清理MCP客户端资源"""
+ """Cleanup MCP client resources"""
if not self._worker_task:
return
@@ -79,26 +78,26 @@ class ServerMCPClient:
try:
await asyncio.wait_for(self._worker_task, timeout=20)
except (asyncio.TimeoutError, Exception) as e:
- self.logger.bind(tag=TAG).error(f"服务端MCP客户端关闭错误: {e}")
+ self.logger.bind(tag=TAG).error(f"Server MCP client shutdown error: {e}")
finally:
self._worker_task = None
def has_tool(self, name: str) -> bool:
- """检查是否包含指定工具
+ """Check if the specified tool exists
Args:
- name: 工具名称
+ name: Tool name
Returns:
- bool: 是否包含该工具
+ bool: Whether the tool exists
"""
return name in self.tools_dict
def get_available_tools(self) -> List[Dict[str, Any]]:
- """获取所有可用工具的定义
+ """Get the definition of all available tools
Returns:
- List[Dict[str, Any]]: 工具定义列表
+ List[Dict[str, Any]]: List of tool definitions
"""
return [
{
@@ -113,23 +112,23 @@ class ServerMCPClient:
]
async def call_tool(self, name: str, arguments: dict, read_timeout_seconds: timedelta | None = None, progress_callback: ProgressFnT | None = None, *, meta: dict[str, Any] | None = None) -> Any:
- """调用指定工具
+ """Call the specified tool
Args:
- name: 工具名称
- arguments: 工具参数
+ name: Tool name
+ arguments: Tool arguments
read_timeout_seconds:
- progress_callback: 进度回调函数
+ progress_callback: Progress callback function
meta:
Returns:
- Any: 工具执行结果
+ Any: Tool execution result
Raises:
- RuntimeError: 客户端未初始化时抛出
+ RuntimeError: When the client is not initialized
"""
if not self.session:
- raise RuntimeError("服务端MCP客户端未初始化")
+ raise RuntimeError("Server MCP client not initialized")
real_name = self.name_mapping.get(name, name)
loop = self._worker_task.get_loop()
@@ -142,24 +141,24 @@ class ServerMCPClient:
return await asyncio.wrap_future(fut)
def is_connected(self) -> bool:
- """检查MCP客户端是否连接正常
+ """Check if the MCP client is connected normally
Returns:
- bool: 如果客户端已连接并正常工作,返回True,否则返回False
+ bool: If the client is connected and working normally, return True, otherwise return False
"""
- # 检查工作任务是否存在
+ # Check if the worker task exists
if self._worker_task is None:
return False
- # 检查工作任务是否已经完成或取消
+ # Check if the worker task is done or cancelled
if self._worker_task.done():
return False
- # 检查会话是否存在
+ # Check if the session exists
if self.session is None:
return False
- # 所有检查都通过,连接正常
+ # All checks passed, connection is normal
return True
async def _worker(self, read_timeout_seconds: timedelta | None = None,
@@ -169,10 +168,10 @@ class ServerMCPClient:
logging_callback: LoggingFnT | None = None,
message_handler: MessageHandlerFnT | None = None,
client_info: Implementation | None = None):
- """MCP客户端工作协程"""
+ """MCP client worker coroutine"""
async with AsyncExitStack() as stack:
try:
- # 建立 StdioClient
+ # Create StdioClient
if "command" in self.config:
cmd = (
shutil.which("npx")
@@ -190,19 +189,19 @@ class ServerMCPClient:
)
read_stream, write_stream = stdio_r, stdio_w
- # 建立SSEClient
+ # Create SSEClient
elif "url" in self.config:
headers = dict(self.config.get("headers", {}))
- # TODO 兼容旧版本
+ # TODO: compatibility with old version
if "API_ACCESS_TOKEN" in self.config:
headers["Authorization"] = f"Bearer {self.config['API_ACCESS_TOKEN']}"
- self.logger.bind(tag=TAG).warning(f"你正在使用旧过时的配置 API_ACCESS_TOKEN ,请在.mcp_server_settings.json中将API_ACCESS_TOKEN直接设置在headers中,例如 'Authorization': 'Bearer API_ACCESS_TOKEN'")
+ self.logger.bind(tag=TAG).warning(f"You are using the deprecated configuration API_ACCESS_TOKEN, please set API_ACCESS_TOKEN directly in headers in .mcp_server_settings.json, for example 'Authorization': 'Bearer API_ACCESS_TOKEN'")
- # 根据transport类型选择不同的客户端,默认为SSE
+ # Select different clients based on transport type, default is SSE
transport_type = self.config.get("transport", "sse")
if transport_type == "streamable-http" or transport_type == "http":
- # 使用 Streamable HTTP 传输
+ # Use Streamable HTTP transport
http_r, http_w, get_session_id = await stack.enter_async_context(
streamablehttp_client(
url=self.config["url"],
@@ -214,7 +213,7 @@ class ServerMCPClient:
)
read_stream, write_stream = http_r, http_w
else:
- # 使用传统的 SSE 传输
+ # Use traditional SSE transport
sse_r, sse_w = await stack.enter_async_context(
sse_client(
url=self.config["url"],
@@ -226,7 +225,7 @@ class ServerMCPClient:
read_stream, write_stream = sse_r, sse_w
else:
- raise ValueError("MCP客户端配置必须包含'command'或'url'")
+ raise ValueError("MCP client configuration must contain 'command' or 'url'")
self.session = await stack.enter_async_context(
ClientSession(
@@ -243,7 +242,7 @@ class ServerMCPClient:
)
await self.session.initialize()
- # 获取工具
+ # Get tools
self.tools = (await self.session.list_tools()).tools
for t in self.tools:
sanitized = sanitize_tool_name(t.name)
@@ -252,10 +251,10 @@ class ServerMCPClient:
self._ready_evt.set()
- # 挂起等待关闭
+ # Suspend and wait for shutdown
await self._shutdown_evt.wait()
except Exception as e:
- self.logger.bind(tag=TAG).error(f"服务端MCP客户端工作协程错误: {e}")
+ self.logger.bind(tag=TAG).error(f"MCP client worker coroutine error: {e}")
self._ready_evt.set()
raise
diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py
index ee0bcb2a2..5e45ed1f9 100644
--- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py
+++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_executor.py
@@ -1,4 +1,4 @@
-"""服务端MCP工具执行器"""
+"""Server MCP tool executor"""
from typing import Dict, Any, Optional
from ..base import ToolType, ToolDefinition, ToolExecutor
@@ -7,7 +7,7 @@ from .mcp_manager import ServerMCPManager
class ServerMCPExecutor(ToolExecutor):
- """服务端MCP工具执行器"""
+ """Server MCP tool executor"""
def __init__(self, conn):
self.conn = conn
@@ -15,7 +15,7 @@ class ServerMCPExecutor(ToolExecutor):
self._initialized = False
async def initialize(self):
- """初始化MCP管理器"""
+ """Initialize MCP manager"""
if not self._initialized:
self.mcp_manager = ServerMCPManager(self.conn)
self._initialized = True
@@ -24,15 +24,15 @@ class ServerMCPExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行服务端MCP工具"""
+ """Execute server MCP tool"""
if not self._initialized or not self.mcp_manager:
return ActionResponse(
action=Action.ERROR,
- response="MCP管理器未初始化",
+ response="MCP manager not initialized",
)
try:
- # 移除mcp_前缀(如果有)
+ # Remove mcp_ prefix (if any)
actual_tool_name = tool_name
if tool_name.startswith("mcp_"):
actual_tool_name = tool_name[4:]
@@ -53,7 +53,7 @@ class ServerMCPExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
- """获取所有服务端MCP工具"""
+ """Get all server MCP tools"""
if not self._initialized or not self.mcp_manager:
return {}
@@ -72,11 +72,11 @@ class ServerMCPExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定的服务端MCP工具"""
+ """Check if there is a specified server MCP tool"""
if not self._initialized or not self.mcp_manager:
return False
- # 移除mcp_前缀(如果有)
+ # Remove mcp_ prefix (if any)
actual_tool_name = tool_name
if tool_name.startswith("mcp_"):
actual_tool_name = tool_name[4:]
@@ -84,6 +84,6 @@ class ServerMCPExecutor(ToolExecutor):
return self.mcp_manager.is_mcp_tool(actual_tool_name)
async def cleanup(self):
- """清理MCP连接"""
+ """Cleanup MCP connection"""
if self.mcp_manager:
await self.mcp_manager.cleanup_all()
diff --git a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py
index b1fc0aa34..b4a9615c7 100644
--- a/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py
+++ b/main/xiaozhi-server/core/providers/tools/server_mcp/mcp_manager.py
@@ -1,4 +1,4 @@
-"""服务端MCP管理器"""
+"""Server MCP manager"""
import asyncio
import os
@@ -16,23 +16,23 @@ logger = setup_logging()
class ServerMCPManager:
- """管理多个服务端MCP服务的集中管理器"""
+ """Manage multiple server MCP services"""
def __init__(self, conn) -> None:
- """初始化MCP管理器"""
+ """Initialize MCP manager"""
self.conn = conn
self.config_path = get_project_dir() + "data/.mcp_server_settings.json"
if not os.path.exists(self.config_path):
self.config_path = ""
logger.bind(tag=TAG).warning(
- f"请检查mcp服务配置文件:data/.mcp_server_settings.json"
+ f"MCP server config file not found: {self.config_path}"
)
self.clients: Dict[str, ServerMCPClient] = {}
self.tools = []
self._init_lock = asyncio.Lock()
def load_config(self) -> Dict[str, Any]:
- """加载MCP服务配置"""
+ """Load MCP server config"""
if len(self.config_path) == 0:
return {}
@@ -47,16 +47,16 @@ class ServerMCPManager:
return {}
async def _init_server(self, name: str, srv_config: Dict[str, Any]):
- """初始化单个MCP服务"""
+ """Initialize single MCP server"""
client = None
try:
- # 初始化服务端MCP客户端
- logger.bind(tag=TAG).info(f"初始化服务端MCP客户端: {name}")
+ # Initialize server MCP client
+ logger.bind(tag=TAG).info(f"Initialize server MCP client: {name}")
client = ServerMCPClient(srv_config)
- # 设置超时时间10秒
+ # Set timeout to 10 seconds
await asyncio.wait_for(client.initialize(logging_callback=self.logging_callback), timeout=10)
- # 使用锁保护共享状态的修改
+ # Use lock to protect shared state modification
async with self._init_lock:
self.clients[name] = client
client_tools = client.get_available_tools()
@@ -76,7 +76,7 @@ class ServerMCPManager:
await client.cleanup()
async def initialize_servers(self) -> None:
- """初始化所有MCP服务"""
+ """Initialize all MCP servers"""
config = self.load_config()
tasks = []
for name, srv_config in config.items():
@@ -91,19 +91,19 @@ class ServerMCPManager:
if tasks:
await asyncio.gather(*tasks)
- # 输出当前支持的服务端MCP工具列表
+ # Output the list of supported server MCP tools
if hasattr(self.conn, "func_handler") and self.conn.func_handler:
- # 刷新工具缓存以确保服务端MCP工具被正确加载
+ # Refresh tool cache to ensure server MCP tools are correctly loaded
if hasattr(self.conn.func_handler, "tool_manager"):
self.conn.func_handler.tool_manager.refresh_tools()
self.conn.func_handler.current_support_functions()
def get_all_tools(self) -> List[Dict[str, Any]]:
- """获取所有服务的工具function定义"""
+ """Get all tools function definitions"""
return self.tools
def is_mcp_tool(self, tool_name: str) -> bool:
- """检查是否是MCP工具"""
+ """Check if it is an MCP tool"""
for tool in self.tools:
if (
tool.get("function") is not None
@@ -113,13 +113,13 @@ class ServerMCPManager:
return False
async def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> Any:
- """执行工具调用,失败时会尝试重新连接"""
- logger.bind(tag=TAG).info(f"执行服务端MCP工具 {tool_name},参数: {arguments}")
+ """Execute tool call, retry when failed"""
+ logger.bind(tag=TAG).info(f"Execute server MCP tool {tool_name}, arguments: {arguments}")
- max_retries = 3 # 最大重试次数
- retry_interval = 2 # 重试间隔(秒)
+ max_retries = 3 # Maximum retry times
+ retry_interval = 2 # Retry interval (seconds)
- # 找到对应的客户端
+ # Find the corresponding client
client_name = None
target_client = None
for name, client in self.clients.items():
@@ -129,30 +129,30 @@ class ServerMCPManager:
break
if not target_client:
- raise ValueError(f"工具 {tool_name} 在任意MCP服务中未找到")
+ raise ValueError(f"Tool {tool_name} not found in any MCP server")
- # 带重试机制的工具调用
+ # Tool call with retry mechanism
for attempt in range(max_retries):
try:
return await target_client.call_tool(tool_name, arguments, progress_callback=self.progress_callback)
except Exception as e:
- # 最后一次尝试失败时直接抛出异常
+ # If the last attempt fails, throw the exception directly
if attempt == max_retries - 1:
raise
logger.bind(tag=TAG).warning(
- f"执行工具 {tool_name} 失败 (尝试 {attempt+1}/{max_retries}): {e}"
+ f"Failed to execute tool {tool_name} (attempt {attempt+1}/{max_retries}): {e}"
)
- # 尝试重新连接
+ # Try to reconnect before retry
logger.bind(tag=TAG).info(
- f"重试前尝试重新连接 MCP 客户端 {client_name}"
+ f"Before retry, try to reconnect MCP client {client_name}"
)
try:
- # 关闭旧的连接
+ # Close the old connection
await target_client.cleanup()
- # 重新初始化客户端
+ # Reinitialize the client
config = self.load_config()
if client_name in config:
client = ServerMCPClient(config[client_name])
@@ -160,7 +160,7 @@ class ServerMCPManager:
self.clients[client_name] = client
target_client = client
logger.bind(tag=TAG).info(
- f"成功重新连接 MCP 客户端: {client_name}"
+ f"Successfully reconnected MCP client: {client_name}"
)
else:
logger.bind(tag=TAG).error(
@@ -171,21 +171,21 @@ class ServerMCPManager:
f"Failed to reconnect MCP client {client_name}: {reconnect_error}"
)
- # 等待一段时间再重试
+ # Wait for a while before retrying
await asyncio.sleep(retry_interval)
async def cleanup_all(self) -> None:
- """关闭所有 MCP客户端"""
+ """Close all MCP clients"""
for name, client in list(self.clients.items()):
try:
if hasattr(client, "cleanup"):
await asyncio.wait_for(client.cleanup(), timeout=20)
- logger.bind(tag=TAG).info(f"服务端MCP客户端已关闭: {name}")
+ logger.bind(tag=TAG).info(f"Server MCP client closed: {name}")
except (asyncio.TimeoutError, Exception) as e:
- logger.bind(tag=TAG).error(f"关闭服务端MCP客户端 {name} 时出错: {e}")
+ logger.bind(tag=TAG).error(f"Failed to close MCP client {name}: {e}")
self.clients.clear()
- # 可选回调方法
+ # Optional callback methods
async def logging_callback(self, params: LoggingMessageNotificationParams):
logger.bind(tag=TAG).info(f"[Server Log - {params.level.upper()}] {params.data}")
diff --git a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py
index 6c61eacd1..392f18dcd 100644
--- a/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py
+++ b/main/xiaozhi-server/core/providers/tools/server_plugins/plugin_executor.py
@@ -1,4 +1,4 @@
-"""服务端插件工具执行器"""
+"""Server plugin tool executor"""
from typing import Dict, Any
from ..base import ToolType, ToolDefinition, ToolExecutor
@@ -6,7 +6,7 @@ from plugins_func.register import all_function_registry, Action, ActionResponse
class ServerPluginExecutor(ToolExecutor):
- """服务端插件工具执行器"""
+ """Server plugin tool executor"""
def __init__(self, conn):
self.conn = conn
@@ -15,18 +15,18 @@ class ServerPluginExecutor(ToolExecutor):
async def execute(
self, conn, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行服务端插件工具"""
+ """Execute server plugin tool"""
func_item = all_function_registry.get(tool_name)
if not func_item:
return ActionResponse(
- action=Action.NOTFOUND, response=f"插件函数 {tool_name} 不存在"
+ action=Action.NOTFOUND, response=f"Plugin function {tool_name} does not exist"
)
try:
- # 根据工具类型决定如何调用
+ # Decide how to call based on tool type
if hasattr(func_item, "type"):
func_type = func_item.type
- if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (需要conn参数)
+ if func_type.code in [4, 5]: # SYSTEM_CTL, IOT_CTL (needs conn argument)
result = func_item.func(conn, **arguments)
elif func_type.code == 2: # WAIT
result = func_item.func(**arguments)
@@ -35,7 +35,7 @@ class ServerPluginExecutor(ToolExecutor):
else:
result = func_item.func(**arguments)
else:
- # 默认不传conn参数
+ # Default: do not pass conn argument
result = func_item.func(**arguments)
return result
@@ -47,31 +47,31 @@ class ServerPluginExecutor(ToolExecutor):
)
def get_tools(self) -> Dict[str, ToolDefinition]:
- """获取所有注册的服务端插件工具"""
+ """Get all registered server plugin tools"""
tools = {}
- # 获取必要的函数
+ # Get necessary functions
necessary_functions = ["handle_exit_intent", "get_lunar"]
- # 获取配置中的函数
+ # Get functions in config
config_functions = self.config["Intent"][
self.config["selected_module"]["Intent"]
].get("functions", [])
- # 转换为列表
+ # Convert to list
if not isinstance(config_functions, list):
try:
config_functions = list(config_functions)
except TypeError:
config_functions = []
- # 合并所有需要的函数
+ # Merge all required functions
all_required_functions = list(set(necessary_functions + config_functions))
for func_name in all_required_functions:
func_item = all_function_registry.get(func_name)
if func_item:
- # 从函数注册中获取描述
+ # Get description from function registry
fun_description = (
self.config.get("plugins", {})
.get(func_name, {})
@@ -93,5 +93,5 @@ class ServerPluginExecutor(ToolExecutor):
return tools
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定的服务端插件工具"""
+ """Check if specified server plugin tool exists"""
return tool_name in all_function_registry
diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py b/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py
index 6f2896325..33785ef09 100644
--- a/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py
+++ b/main/xiaozhi-server/core/providers/tools/unified_tool_handler.py
@@ -1,4 +1,4 @@
-"""统一工具处理器"""
+"""Unified Tool Handler"""
import json
from typing import Dict, List, Any, Optional
@@ -16,24 +16,24 @@ from .mcp_endpoint import MCPEndpointExecutor
class UnifiedToolHandler:
- """统一工具处理器"""
+ """Unified Tool Handler"""
def __init__(self, conn):
self.conn = conn
self.config = conn.config
self.logger = setup_logging()
- # 创建工具管理器
+ # Create tool manager
self.tool_manager = ToolManager(conn)
- # 创建各类执行器
+ # Create various executors
self.server_plugin_executor = ServerPluginExecutor(conn)
self.server_mcp_executor = ServerMCPExecutor(conn)
self.device_iot_executor = DeviceIoTExecutor(conn)
self.device_mcp_executor = DeviceMCPExecutor(conn)
self.mcp_endpoint_executor = MCPEndpointExecutor(conn)
- # 注册执行器
+ # Register executors
self.tool_manager.register_executor(
ToolType.SERVER_PLUGIN, self.server_plugin_executor
)
@@ -50,97 +50,97 @@ class UnifiedToolHandler:
ToolType.MCP_ENDPOINT, self.mcp_endpoint_executor
)
- # 初始化标志
+ # Initialize flag
self.finish_init = False
async def _initialize(self):
- """异步初始化"""
+ """Asynchronous initialization"""
try:
- # 自动导入插件模块
+ # Automatically import plugin modules
auto_import_modules("plugins_func.functions")
- # 初始化服务端MCP
+ # Initialize server MCP
await self.server_mcp_executor.initialize()
- # 初始化MCP接入点
+ # Initialize MCP endpoint
await self._initialize_mcp_endpoint()
- # 初始化Home Assistant(如果需要)
+ # Initialize Home Assistant (if needed)
self._initialize_home_assistant()
self.finish_init = True
- self.logger.debug("统一工具处理器初始化完成")
+ self.logger.debug("Unified tool handler init completed")
- # 输出当前支持的所有工具列表
+ # Output the list of currently supported tools
self.current_support_functions()
except Exception as e:
- self.logger.error(f"统一工具处理器初始化失败: {e}")
+ self.logger.error(f"Unified tool handler init failed: {e}")
async def _initialize_mcp_endpoint(self):
- """初始化MCP接入点"""
+ """Initialize MCP endpoint"""
try:
from .mcp_endpoint import connect_mcp_endpoint
- # 从配置中获取MCP接入点URL
+ # Get MCP endpoint URL from configuration
mcp_endpoint_url = self.config.get("mcp_endpoint", "")
if (
mcp_endpoint_url
- and "你的" not in mcp_endpoint_url
+ and "your" not in mcp_endpoint_url
and mcp_endpoint_url != "null"
):
- self.logger.info(f"正在初始化MCP接入点: {mcp_endpoint_url}")
+ self.logger.info(f"Initializing MCP endpoint: {mcp_endpoint_url}")
mcp_endpoint_client = await connect_mcp_endpoint(
mcp_endpoint_url, self.conn
)
if mcp_endpoint_client:
- # 将MCP接入点客户端保存到连接对象中
+ # Save MCP endpoint client to connection object
self.conn.mcp_endpoint_client = mcp_endpoint_client
- self.logger.info("MCP接入点初始化成功")
+ self.logger.info("MCP endpoint init success")
else:
- self.logger.warning("MCP接入点初始化失败")
+ self.logger.warning("MCP endpoint init failed")
except Exception as e:
- self.logger.error(f"初始化MCP接入点失败: {e}")
+ self.logger.error(f"Failed to init MCP endpoint: {e}")
def _initialize_home_assistant(self):
- """初始化Home Assistant提示词"""
+ """Initialize Home Assistant prompt"""
try:
from plugins_func.functions.hass_init import append_devices_to_prompt
append_devices_to_prompt(self.conn)
except ImportError:
- pass # 忽略导入错误
+ pass # Ignore import error
except Exception as e:
- self.logger.error(f"初始化Home Assistant失败: {e}")
+ self.logger.error(f"Failed to init Home Assistant: {e}")
def get_functions(self) -> List[Dict[str, Any]]:
- """获取所有工具的函数描述"""
+ """Get function descriptions of all tools"""
return self.tool_manager.get_function_descriptions()
def current_support_functions(self) -> List[str]:
- """获取当前支持的函数名称列表"""
+ """Get the list of currently supported functions"""
func_names = self.tool_manager.get_supported_tool_names()
- self.logger.info(f"当前支持的函数列表: {func_names}")
+ self.logger.info(f"Currently supported functions: {func_names}")
return func_names
def upload_functions_desc(self):
- """刷新函数描述列表"""
+ """Refresh function description list"""
self.tool_manager.refresh_tools()
- self.logger.info("函数描述列表已刷新")
+ self.logger.info("Function descriptions refreshed")
def has_tool(self, tool_name: str) -> bool:
- """检查是否有指定工具"""
+ """Check if a specified tool exists"""
return self.tool_manager.has_tool(tool_name)
async def handle_llm_function_call(
self, conn, function_call_data: Dict[str, Any]
) -> Optional[ActionResponse]:
- """处理LLM函数调用"""
+ """Handle LLM function call"""
try:
- # 处理多函数调用
+ # Handle multiple function calls
if "function_calls" in function_call_data:
responses = []
for call in function_call_data["function_calls"]:
@@ -150,42 +150,42 @@ class UnifiedToolHandler:
responses.append(result)
return self._combine_responses(responses)
- # 处理单函数调用
+ # Handle single function call
function_name = function_call_data["name"]
arguments = function_call_data.get("arguments", {})
- # 如果arguments是字符串,尝试解析为JSON
+ # If arguments is a string, try to parse it as JSON
if isinstance(arguments, str):
try:
arguments = json.loads(arguments) if arguments else {}
except json.JSONDecodeError:
- self.logger.error(f"无法解析函数参数: {arguments}")
+ self.logger.error(f"Cannot parse function args: {arguments}")
return ActionResponse(
action=Action.ERROR,
- response="无法解析函数参数",
+ response="Cannot parse function args",
)
- self.logger.debug(f"调用函数: {function_name}, 参数: {arguments}")
+ self.logger.debug(f"Call function: {function_name}, args: {arguments}")
- # 执行工具调用
+ # Execute tool call
result = await self.tool_manager.execute_tool(function_name, arguments)
return result
except Exception as e:
- self.logger.error(f"处理function call错误: {e}")
+ self.logger.error(f"Handle function call error: {e}")
return ActionResponse(action=Action.ERROR, response=str(e))
def _combine_responses(self, responses: List[ActionResponse]) -> ActionResponse:
- """合并多个函数调用的响应"""
+ """Combine responses from multiple function calls"""
if not responses:
- return ActionResponse(action=Action.NONE, response="无响应")
+ return ActionResponse(action=Action.NONE, response="No response")
- # 如果有任何错误,返回第一个错误
+ # If any error, return the first error
for response in responses:
if response.action == Action.ERROR:
return response
- # 合并所有成功的响应
+ # Combine all successful responses
contents = []
responses_text = []
@@ -195,7 +195,7 @@ class UnifiedToolHandler:
if response.response:
responses_text.append(response.response)
- # 确定最终的动作类型
+ # Determine the final action type
final_action = Action.RESPONSE
for response in responses:
if response.action == Action.REQLLM:
@@ -209,27 +209,27 @@ class UnifiedToolHandler:
)
async def register_iot_tools(self, descriptors: List[Dict[str, Any]]):
- """注册IoT设备工具"""
+ """Register IoT device tools"""
self.device_iot_executor.register_iot_tools(descriptors)
self.tool_manager.refresh_tools()
- self.logger.info(f"注册了{len(descriptors)}个IoT设备的工具")
+ self.logger.info(f"Registered {len(descriptors)} IoT device tools")
def get_tool_statistics(self) -> Dict[str, int]:
- """获取工具统计信息"""
+ """Get tool statistics"""
return self.tool_manager.get_tool_statistics()
async def cleanup(self):
- """清理资源"""
+ """Cleanup resources"""
try:
await self.server_mcp_executor.cleanup()
- # 清理MCP接入点连接
+ # Cleanup MCP endpoint connection
if (
hasattr(self.conn, "mcp_endpoint_client")
and self.conn.mcp_endpoint_client
):
await self.conn.mcp_endpoint_client.close()
- self.logger.info("工具处理器清理完成")
+ self.logger.info("Tool handler cleanup completed")
except Exception as e:
- self.logger.error(f"工具处理器清理失败: {e}")
+ self.logger.error(f"Tool handler cleanup failed: {e}")
diff --git a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py
index f69a6dc39..3074497bf 100644
--- a/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py
+++ b/main/xiaozhi-server/core/providers/tools/unified_tool_manager.py
@@ -1,4 +1,4 @@
-"""统一工具管理器"""
+"""Unified Tool Manager"""
from typing import Dict, List, Optional, Any
from config.logger import setup_logging
@@ -7,7 +7,7 @@ from .base import ToolType, ToolDefinition, ToolExecutor
class ToolManager:
- """统一工具管理器,管理所有类型的工具"""
+ """Unified Tool Manager, manages all types of tools"""
def __init__(self, conn):
self.conn = conn
@@ -17,18 +17,18 @@ class ToolManager:
self._cached_function_descriptions: Optional[List[Dict[str, Any]]] = None
def register_executor(self, tool_type: ToolType, executor: ToolExecutor):
- """注册工具执行器"""
+ """Register tool executor"""
self.executors[tool_type] = executor
self._invalidate_cache()
- self.logger.debug(f"注册工具执行器: {tool_type.value}")
+ self.logger.debug(f"Register tool executor: {tool_type.value}")
def _invalidate_cache(self):
- """使缓存失效"""
+ """Invalidate cache"""
self._cached_tools = None
self._cached_function_descriptions = None
def get_all_tools(self) -> Dict[str, ToolDefinition]:
- """获取所有工具定义"""
+ """Get all tool definitions"""
if self._cached_tools is not None:
return self._cached_tools
@@ -38,16 +38,16 @@ class ToolManager:
tools = executor.get_tools()
for name, definition in tools.items():
if name in all_tools:
- self.logger.warning(f"工具名称冲突: {name}")
+ self.logger.warning(f"Tool name conflict: {name}")
all_tools[name] = definition
except Exception as e:
- self.logger.error(f"获取{tool_type.value}工具时出错: {e}")
+ self.logger.error(f"Error getting {tool_type.value} tools: {e}")
self._cached_tools = all_tools
return all_tools
def get_function_descriptions(self) -> List[Dict[str, Any]]:
- """获取所有工具的函数描述(OpenAI格式)"""
+ """Get all tool function descriptions (OpenAI format)"""
if self._cached_function_descriptions is not None:
return self._cached_function_descriptions
@@ -60,12 +60,12 @@ class ToolManager:
return descriptions
def has_tool(self, tool_name: str) -> bool:
- """检查是否存在指定工具"""
+ """Check if a specified tool exists"""
tools = self.get_all_tools()
return tool_name in tools
def get_tool_type(self, tool_name: str) -> Optional[ToolType]:
- """获取工具类型"""
+ """Get tool type"""
tools = self.get_all_tools()
tool_def = tools.get(tool_name)
return tool_def.tool_type if tool_def else None
@@ -73,14 +73,14 @@ class ToolManager:
async def execute_tool(
self, tool_name: str, arguments: Dict[str, Any]
) -> ActionResponse:
- """执行工具调用"""
+ """Execute tool call"""
try:
- # 查找工具类型
+ # Find tool type
tool_type = self.get_tool_type(tool_name)
if not tool_type:
return ActionResponse(
action=Action.NOTFOUND,
- response=f"工具 {tool_name} 不存在",
+ response=f"Tool {tool_name} not found",
)
# 获取对应的执行器
@@ -88,37 +88,37 @@ class ToolManager:
if not executor:
return ActionResponse(
action=Action.ERROR,
- response=f"工具类型 {tool_type.value} 的执行器未注册",
+ response=f"Executor for tool type {tool_type.value} not registered",
)
# 执行工具
- self.logger.info(f"执行工具: {tool_name},参数: {arguments}")
+ self.logger.info(f"Execute tool: {tool_name}, args: {arguments}")
result = await executor.execute(self.conn, tool_name, arguments)
- self.logger.debug(f"工具执行结果: {result}")
+ self.logger.debug(f"Tool execution result: {result}")
return result
except Exception as e:
- self.logger.error(f"执行工具 {tool_name} 时出错: {e}")
+ self.logger.error(f"Error executing tool {tool_name}: {e}")
return ActionResponse(action=Action.ERROR, response=str(e))
def get_supported_tool_names(self) -> List[str]:
- """获取所有支持的工具名称"""
+ """Get all supported tool names"""
tools = self.get_all_tools()
return list(tools.keys())
def refresh_tools(self):
- """刷新工具缓存"""
+ """Refresh tool cache"""
self._invalidate_cache()
- self.logger.debug("工具缓存已刷新")
+ self.logger.debug("Tool cache refreshed")
def get_tool_statistics(self) -> Dict[str, int]:
- """获取工具统计信息"""
+ """Get tool statistics"""
stats = {}
for tool_type, executor in self.executors.items():
try:
tools = executor.get_tools()
stats[tool_type.value] = len(tools)
except Exception as e:
- self.logger.error(f"获取{tool_type.value}工具统计时出错: {e}")
+ self.logger.error(f"Error getting {tool_type.value} tool stats: {e}")
stats[tool_type.value] = 0
return stats
diff --git a/main/xiaozhi-server/core/providers/tts/aliyun.py b/main/xiaozhi-server/core/providers/tts/aliyun.py
index 1a4cab885..dda2e17df 100644
--- a/main/xiaozhi-server/core/providers/tts/aliyun.py
+++ b/main/xiaozhi-server/core/providers/tts/aliyun.py
@@ -41,10 +41,10 @@ class AccessToken:
"Timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
"Version": "2019-02-28",
}
- # 构造规范化的请求字符串
+ # Construct normalized request string
query_string = AccessToken._encode_dict(parameters)
- # print('规范化的请求字符串: %s' % query_string)
- # 构造待签名字符串
+ # print('Normalized request string: %s' % query_string)
+ # Construct string to sign
string_to_sign = (
"GET"
+ "&"
@@ -52,25 +52,25 @@ class AccessToken:
+ "&"
+ AccessToken._encode_text(query_string)
)
- # print('待签名的字符串: %s' % string_to_sign)
- # 计算签名
+ # print('String to sign: %s' % string_to_sign)
+ # Calculate signature
secreted_string = hmac.new(
bytes(access_key_secret + "&", encoding="utf-8"),
bytes(string_to_sign, encoding="utf-8"),
hashlib.sha1,
).digest()
signature = base64.b64encode(secreted_string)
- # print('签名: %s' % signature)
- # 进行URL编码
+ # print('Signature: %s' % signature)
+ # Perform URL encoding
signature = AccessToken._encode_text(signature)
- # print('URL编码后的签名: %s' % signature)
- # 调用服务
+ # print('URL encoded signature: %s' % signature)
+ # Call service
full_url = "http://nls-meta.cn-shanghai.aliyuncs.com/?Signature=%s&%s" % (
signature,
query_string,
)
# print('url: %s' % full_url)
- # 提交HTTP GET请求
+ # Submit HTTP GET request
response = requests.get(full_url)
if response.ok:
root_obj = response.json()
@@ -88,7 +88,7 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
- # 新增空值判断逻辑
+ # Add null value check logic
self.access_key_id = config.get("access_key_id")
self.access_key_secret = config.get("access_key_secret")
@@ -117,24 +117,24 @@ class TTSProvider(TTSProviderBase):
self.header = {"Content-Type": "application/json"}
if self.access_key_id and self.access_key_secret:
- # 使用密钥对生成临时token
+ # Generate temporary token using key pair
self._refresh_token()
else:
- # 直接使用预生成的长期token
+ # Use pre-generated long-term token directly
self.token = config.get("token")
self.expire_time = None
def _refresh_token(self):
- """刷新Token并记录过期时间"""
+ """Refresh Token and record expiration time"""
if self.access_key_id and self.access_key_secret:
self.token, expire_time_str = AccessToken.create_token(
self.access_key_id, self.access_key_secret
)
if not expire_time_str:
- raise ValueError("无法获取有效的Token过期时间")
+ raise ValueError("Cannot get valid Token expiration time")
try:
- # 统一转换为字符串处理
+ # Unified conversion to string processing
expire_str = str(expire_time_str).strip()
if expire_str.isdigit():
@@ -143,29 +143,29 @@ class TTSProvider(TTSProviderBase):
expire_time = datetime.strptime(expire_str, "%Y-%m-%dT%H:%M:%SZ")
self.expire_time = expire_time.timestamp() - 60
except Exception as e:
- raise ValueError(f"无效的过期时间格式: {expire_str}") from e
+ raise ValueError(f"Invalid expiration time format: {expire_str}") from e
else:
self.expire_time = None
if not self.token:
- raise ValueError("无法获取有效的访问Token")
+ raise ValueError("Cannot get valid access Token")
def _is_token_expired(self):
- """检查Token是否过期"""
+ """Check if Token is expired"""
if not self.expire_time:
- return False # 长期Token不过期
- # 新增调试日志
+ return False # Long-term Token does not expire
+ # Add debug log
# current_time = time.time()
# remaining = self.expire_time - current_time
- # print(f"Token过期检查: 当前时间 {datetime.fromtimestamp(current_time)} | "
- # f"过期时间 {datetime.fromtimestamp(self.expire_time)} | "
- # f"剩余 {remaining:.2f}秒")
+ # print(f"Token expiration check: Current time {datetime.fromtimestamp(current_time)} | "
+ # f"Expiration time {datetime.fromtimestamp(self.expire_time)} | "
+ # f"Remaining {remaining:.2f}s")
return time.time() > self.expire_time
async def text_to_speak(self, text, output_file):
if self._is_token_expired():
- logger.warning("Token已过期,正在自动刷新...")
+ logger.warning("Token expired, refreshing automatically...")
self._refresh_token()
request_json = {
"appkey": self.appkey,
@@ -184,12 +184,12 @@ class TTSProvider(TTSProviderBase):
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
- if resp.status_code == 401: # Token过期特殊处理
+ if resp.status_code == 401: # Special handling for Token expiration
self._refresh_token()
resp = requests.post(
self.api_url, json.dumps(request_json), headers=self.header
)
- # 检查返回请求数据的mime类型是否是audio/***,是则保存到指定路径下;返回的是binary格式的
+ # Check if response mime type is audio/***, if so save; response is binary
if resp.headers["Content-Type"].startswith("audio/"):
if output_file:
with open(output_file, "wb") as f:
diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py
index 018215d5a..1a004f756 100644
--- a/main/xiaozhi-server/core/providers/tts/base.py
+++ b/main/xiaozhi-server/core/providers/tts/base.py
@@ -38,6 +38,7 @@ class TTSProviderBase(ABC):
self.tts_text_queue = queue.Queue()
self.tts_audio_queue = queue.Queue()
self.tts_audio_first_sentence = True
+ self._is_first_segment = True
self.before_stop_play_files = []
self.tts_text_buff = []
@@ -69,14 +70,28 @@ class TTSProviderBase(ABC):
self.processed_chars = 0
self.is_first_sentence = True
- def generate_filename(self, extension=".wav"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
+ def generate_filename(self, extension=None):
+ if extension is None:
+ extension = f".{self.audio_file_type}"
+ client_id = getattr(self.conn, "client_id", None) if self.conn else None
+
+ if client_id:
+ # Client-specific directory: data/{client_id}/
+ client_dir = os.path.join("data", client_id)
+ if not os.path.exists(client_dir):
+ os.makedirs(client_dir, exist_ok=True)
+
+ # Timestamp suffix: YYMMDD-hhmmss-ffffff (microseconds)
+ timestamp = datetime.now().strftime("%Y%m%d-%H%M%S-%f")
+ return os.path.join(client_dir, f"TTS_{timestamp}{extension}")
+ else:
+ return os.path.join(
+ self.output_file,
+ f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
+ )
def handle_opus(self, opus_data: bytes):
- logger.bind(tag=TAG).debug(f"推送数据到队列里面帧数~~ {len(opus_data)}")
+ logger.bind(tag=TAG).debug(f"Pushing data to queue, frame count ~~ {len(opus_data)}")
self.tts_audio_queue.put((SentenceType.MIDDLE, opus_data, None))
def handle_audio_file(self, file_audio: bytes, text):
@@ -86,12 +101,14 @@ class TTSProviderBase(ABC):
text = MarkdownCleaner.clean_markdown(text)
max_repeat_time = 5
if self.delete_audio_file:
- # 需要删除文件的直接转为音频数据
+ # Convert to audio data directly if file needs deletion
while max_repeat_time > 0:
try:
audio_bytes = asyncio.run(self.text_to_speak(text, None))
if audio_bytes:
- self.tts_audio_queue.put((SentenceType.FIRST, None, text))
+ marker_type = SentenceType.FIRST if self._is_first_segment else SentenceType.MIDDLE
+ self._is_first_segment = False
+ self.tts_audio_queue.put((marker_type, None, text))
audio_bytes_to_data_stream(
audio_bytes,
file_type=self.audio_file_type,
@@ -103,16 +120,16 @@ class TTSProviderBase(ABC):
max_repeat_time -= 1
except Exception as e:
logger.bind(tag=TAG).warning(
- f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
+ f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
- f"语音生成成功: {text},重试{5 - max_repeat_time}次"
+ f"TTS generation success: {text}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
- f"语音生成失败: {text},请检查网络或服务是否正常"
+ f"TTS generation failed: {text}, please check network or service"
)
return None
else:
@@ -123,22 +140,30 @@ class TTSProviderBase(ABC):
asyncio.run(self.text_to_speak(text, tmp_file))
except Exception as e:
logger.bind(tag=TAG).warning(
- f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
+ f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
- # 未执行成功,删除文件
+ # Execution failed, delete file
if os.path.exists(tmp_file):
os.remove(tmp_file)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
- f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
+ f"TTS generation success: {text}:{tmp_file}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
- f"语音生成失败: {text},请检查网络或服务是否正常"
+ f"TTS generation failed: {text}, please check network or service"
)
- self.tts_audio_queue.put((SentenceType.FIRST, None, text))
+ # Put a marker so the audio thread knows this sentence finished (even if empty)
+ marker_type = SentenceType.FIRST if self._is_first_segment else SentenceType.MIDDLE
+ self._is_first_segment = False
+ self.tts_audio_queue.put((marker_type, None, text))
+ return None
+
+ marker_type = SentenceType.FIRST if self._is_first_segment else SentenceType.MIDDLE
+ self._is_first_segment = False
+ self.tts_audio_queue.put((marker_type, None, text))
self._process_audio_file_stream(tmp_file, callback=opus_handler)
except Exception as e:
logger.bind(tag=TAG).error(f"Failed to generate TTS file: {e}")
@@ -148,7 +173,7 @@ class TTSProviderBase(ABC):
text = MarkdownCleaner.clean_markdown(text)
max_repeat_time = 5
if self.delete_audio_file:
- # 需要删除文件的直接转为音频数据
+ # Convert to audio data directly if file needs deletion
while max_repeat_time > 0:
try:
audio_bytes = asyncio.run(self.text_to_speak(text, None))
@@ -165,16 +190,16 @@ class TTSProviderBase(ABC):
max_repeat_time -= 1
except Exception as e:
logger.bind(tag=TAG).warning(
- f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
+ f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
- f"语音生成成功: {text},重试{5 - max_repeat_time}次"
+ f"TTS generation success: {text}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
- f"语音生成失败: {text},请检查网络或服务是否正常"
+ f"TTS generation failed: {text}, please check network or service"
)
return None
else:
@@ -185,20 +210,20 @@ class TTSProviderBase(ABC):
asyncio.run(self.text_to_speak(text, tmp_file))
except Exception as e:
logger.bind(tag=TAG).warning(
- f"语音生成失败{5 - max_repeat_time + 1}次: {text},错误: {e}"
+ f"TTS generation failed {5 - max_repeat_time + 1} times: {text}, Error: {e}"
)
- # 未执行成功,删除文件
+ # Execution failed, delete file
if os.path.exists(tmp_file):
os.remove(tmp_file)
max_repeat_time -= 1
if max_repeat_time > 0:
logger.bind(tag=TAG).info(
- f"语音生成成功: {text}:{tmp_file},重试{5 - max_repeat_time}次"
+ f"TTS generation success: {text}:{tmp_file}, Retried {5 - max_repeat_time} times"
)
else:
logger.bind(tag=TAG).error(
- f"语音生成失败: {text},请检查网络或服务是否正常"
+ f"TTS generation failed: {text}, please check network or service"
)
return tmp_file
@@ -213,13 +238,13 @@ class TTSProviderBase(ABC):
def audio_to_pcm_data_stream(
self, audio_file_path, callback: Callable[[Any], Any] = None
):
- """音频文件转换为PCM编码"""
+ """Convert audio file to PCM encoding"""
return audio_to_data_stream(audio_file_path, is_opus=False, callback=callback)
def audio_to_opus_data_stream(
self, audio_file_path, callback: Callable[[Any], Any] = None
):
- """音频文件转换为Opus编码"""
+ """Convert audio file to Opus encoding"""
return audio_to_data_stream(audio_file_path, is_opus=True, callback=callback)
def tts_one_sentence(
@@ -230,14 +255,14 @@ class TTSProviderBase(ABC):
content_file=None,
sentence_id=None,
):
- """发送一句话"""
+ """Send a sentence"""
if not sentence_id:
if conn.sentence_id:
sentence_id = conn.sentence_id
else:
sentence_id = str(uuid.uuid4().hex)
conn.sentence_id = sentence_id
- # 对于单句的文本,进行分段处理
+ # For single sentence text, process in segments
segments = re.split(r"([。!?!?;;\n])", content_detail)
for seg in segments:
self.tts_text_queue.put(
@@ -252,20 +277,20 @@ class TTSProviderBase(ABC):
async def open_audio_channels(self, conn):
self.conn = conn
- # tts 消化线程
+ # TTS consumer thread
self.tts_priority_thread = threading.Thread(
target=self.tts_text_priority_thread, daemon=True
)
self.tts_priority_thread.start()
- # 音频播放 消化线程
+ # Audio playback consumer thread
self.audio_play_priority_thread = threading.Thread(
target=self._audio_play_priority_thread, daemon=True
)
self.audio_play_priority_thread.start()
- # 这里默认是非流式的处理方式
- # 流式处理方式请在子类中重写
+ # Default is non-streaming processing
+ # Override in subclass for streaming processing
def tts_text_priority_thread(self):
while not self.conn.stop_event.is_set():
try:
@@ -273,19 +298,20 @@ class TTSProviderBase(ABC):
if message.sentence_type == SentenceType.FIRST:
self.conn.client_abort = False
if self.conn.client_abort:
- logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
+ logger.bind(tag=TAG).info("Received interrupt signal, terminating TTS text processing thread")
continue
if message.sentence_type == SentenceType.FIRST:
- # 初始化参数
+ # Initialize parameters
self.tts_stop_request = False
self.processed_chars = 0
self.tts_text_buff = []
self.is_first_sentence = True
self.tts_audio_first_sentence = True
+ self._is_first_segment = True
elif ContentType.TEXT == message.content_type:
self.tts_text_buff.append(message.content_detail)
segment_text = self._get_segment_text()
- if segment_text:
+ if segment_text and segment_text.strip():
self.to_tts_stream(segment_text, opus_handler=self.handle_opus)
elif ContentType.FILE == message.content_type:
self._process_remaining_text_stream(opus_handler=self.handle_opus)
@@ -304,12 +330,12 @@ class TTSProviderBase(ABC):
continue
except Exception as e:
logger.bind(tag=TAG).error(
- f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
continue
def _audio_play_priority_thread(self):
- # 需要上报的文本和音频列表
+ # List of text and audio to report
enqueue_text = None
enqueue_audio = None
while not self.conn.stop_event.is_set():
@@ -325,30 +351,30 @@ class TTSProviderBase(ABC):
continue
if self.conn.client_abort:
- logger.bind(tag=TAG).debug("收到打断信号,跳过当前音频数据")
+ logger.bind(tag=TAG).debug("Received interrupt signal, skipping current audio data")
enqueue_text, enqueue_audio = None, []
continue
- # 收到下一个文本开始或会话结束时进行上报
+ # Report when next text starts or session ends
if sentence_type is not SentenceType.MIDDLE:
- # 上报TTS数据
+ # Report TTS data
if enqueue_text is not None and enqueue_audio is not None:
enqueue_tts_report(self.conn, enqueue_text, enqueue_audio)
enqueue_audio = []
enqueue_text = text
- # 收集上报音频数据
+ # Collect audio data for reporting
if isinstance(audio_datas, bytes) and enqueue_audio is not None:
enqueue_audio.append(audio_datas)
- # 发送音频
+ # Send audio
future = asyncio.run_coroutine_threadsafe(
sendAudioMessage(self.conn, sentence_type, audio_datas, text),
self.conn.loop,
)
future.result()
- # 记录输出和报告
+ # Record output and report
if self.conn.max_output_size > 0 and text:
add_device_output(self.conn.headers.get("device-id"), len(text))
@@ -362,17 +388,17 @@ class TTSProviderBase(ABC):
pass
async def close(self):
- """资源清理方法"""
+ """Resource cleanup method"""
if hasattr(self, "ws") and self.ws:
await self.ws.close()
def _get_segment_text(self):
- # 合并当前全部文本并处理未分割部分
+ # Merge all current text and process unsplit parts
full_text = "".join(self.tts_text_buff)
- current_text = full_text[self.processed_chars :] # 从未处理的位置开始
+ current_text = full_text[self.processed_chars :] # Start from unprocessed position
last_punct_pos = -1
- # 根据是否是第一句话选择不同的标点符号集合
+ # Select punctuation set based on whether it is the first sentence
punctuations_to_use = (
self.first_sentence_punctuations
if self.is_first_sentence
@@ -391,16 +417,16 @@ class TTSProviderBase(ABC):
segment_text = textUtils.get_string_no_punctuation_or_emoji(
segment_text_raw
)
- self.processed_chars += len(segment_text_raw) # 更新已处理字符位置
+ self.processed_chars += len(segment_text_raw) # Update processed char position
- # 如果是第一句话,在找到第一个逗号后,将标志设置为False
+ # If it is the first sentence, set flag to False after finding the first comma
if self.is_first_sentence:
self.is_first_sentence = False
return segment_text
elif self.tts_stop_request and current_text:
segment_text = current_text
- self.is_first_sentence = True # 重置标志
+ self.is_first_sentence = True # Reset flag
return segment_text
else:
return None
@@ -408,11 +434,11 @@ class TTSProviderBase(ABC):
def _process_audio_file_stream(
self, tts_file, callback: Callable[[Any], Any]
) -> None:
- """处理音频文件并转换为指定格式
+ """Process audio file and convert to specified format
Args:
- tts_file: 音频文件路径
- callback: 文件处理函数
+ tts_file: Audio file path
+ callback: File processing function
"""
if tts_file.endswith(".p3"):
p3.decode_opus_from_file_stream(tts_file, callback=callback)
@@ -438,10 +464,10 @@ class TTSProviderBase(ABC):
def _process_remaining_text_stream(
self, opus_handler: Callable[[bytes], None] = None
):
- """处理剩余的文本并生成语音
+ """Process remaining text and generate speech
Returns:
- bool: 是否成功处理了文本
+ bool: Whether text was successfully processed
"""
full_text = "".join(self.tts_text_buff)
remaining_text = full_text[self.processed_chars :]
diff --git a/main/xiaozhi-server/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py
index ffa1c3aa7..71b90848a 100644
--- a/main/xiaozhi-server/core/providers/tts/edge.py
+++ b/main/xiaozhi-server/core/providers/tts/edge.py
@@ -4,6 +4,7 @@ import edge_tts
from datetime import datetime
from core.providers.tts.base import TTSProviderBase
+TAG = __name__
class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
@@ -14,33 +15,53 @@ class TTSProvider(TTSProviderBase):
self.voice = config.get("voice")
self.audio_file_type = config.get("format", "mp3")
- def generate_filename(self, extension=".mp3"):
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}",
- )
-
async def text_to_speak(self, text, output_file):
try:
- communicate = edge_tts.Communicate(text, voice=self.voice)
- if output_file:
- # 确保目录存在并创建空文件
- os.makedirs(os.path.dirname(output_file), exist_ok=True)
- with open(output_file, "wb") as f:
- pass
-
- # 流式写入音频数据
- with open(output_file, "ab") as f: # 改为追加模式避免覆盖
- async for chunk in communicate.stream():
- if chunk["type"] == "audio": # 只处理音频数据块
- f.write(chunk["data"])
- else:
- # 返回音频二进制数据
- audio_bytes = b""
- async for chunk in communicate.stream():
- if chunk["type"] == "audio":
- audio_bytes += chunk["data"]
- return audio_bytes
+ # Detect if text contains Chinese but voice is English-based
+ # Regular expression for CJK characters
+ has_chinese = any('\u4e00' <= char <= '\u9fff' for char in text)
+
+ target_voice = self.voice
+ if has_chinese and not any(v in self.voice.lower() for v in ["chinese", "mandarin", "zh-cn"]):
+ from config.logger import setup_logging
+ logger = setup_logging()
+ logger.bind(tag=TAG).info(f"Detected Chinese content with English voice {self.voice}, using fallback zh-CN-XiaoxiaoNeural")
+ target_voice = "zh-CN-XiaoxiaoNeural"
+
+ return await self._do_communicate(text, target_voice, output_file)
except Exception as e:
- error_msg = f"Edge TTS请求失败: {e}"
- raise Exception(error_msg) # 抛出异常,让调用方捕获
\ No newline at end of file
+ # General fallback for generic failure
+ fallback_voice = "en-US-AndrewMultilingualNeural"
+ if self.voice == fallback_voice:
+ raise e
+
+ from config.logger import setup_logging
+ logger = setup_logging()
+ logger.bind(tag=TAG).warning(f"Edge TTS failed with {target_voice if 'target_voice' in locals() else self.voice}, trying fallback {fallback_voice}: {e}")
+ try:
+ return await self._do_communicate(text, fallback_voice, output_file)
+ except Exception as e2:
+ error_msg = f"Edge TTS fallback failed: {e2}"
+ raise Exception(error_msg)
+
+ async def _do_communicate(self, text, voice, output_file):
+ communicate = edge_tts.Communicate(text, voice=voice)
+ if output_file:
+ # 确保目录存在并创建空文件
+ os.makedirs(os.path.dirname(output_file), exist_ok=True)
+ with open(output_file, "wb") as f:
+ pass
+
+ # 流式写入音频数据
+ with open(output_file, "ab") as f: # 改为追加模式避免覆盖
+ async for chunk in communicate.stream():
+ if chunk["type"] == "audio": # 只处理音频数据块
+ f.write(chunk["data"])
+ return True
+ else:
+ # 返回音频二进制数据
+ audio_bytes = b""
+ async for chunk in communicate.stream():
+ if chunk["type"] == "audio":
+ audio_bytes += chunk["data"]
+ return audio_bytes
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py
index d7829e35b..649ac190e 100644
--- a/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py
+++ b/main/xiaozhi-server/core/providers/tts/huoshan_double_stream.py
@@ -45,27 +45,27 @@ EVENT_Start_Connection = 1
EVENT_FinishConnection = 2
-EVENT_ConnectionStarted = 50 # 成功建连
+EVENT_ConnectionStarted = 50 # Connection successful
-EVENT_ConnectionFailed = 51 # 建连失败(可能是无法通过权限认证)
+EVENT_ConnectionFailed = 51 # Connection failed (possible auth failure)
-EVENT_ConnectionFinished = 52 # 连接结束
+EVENT_ConnectionFinished = 52 # Connection finished
-# 上行Session事件
+# Upstream Session Event
EVENT_StartSession = 100
EVENT_CancelSession = 101
EVENT_FinishSession = 102
-# 下行Session事件
+# Downstream Session Event
EVENT_SessionStarted = 150
EVENT_SessionCanceled = 151
EVENT_SessionFinished = 152
EVENT_SessionFailed = 153
-# 上行通用事件
+# Upstream General Event
EVENT_TaskRequest = 200
-# 下行TTS事件
+# Downstream TTS Event
EVENT_TTSSentenceStart = 350
EVENT_TTSSentenceEnd = 351
@@ -114,7 +114,7 @@ class Optional:
self.response_meta_json: str | None = None
self.sequence = sequence
- # 转成 byte 序列
+ # Convert to byte sequence
def as_bytes(self) -> bytes:
option_bytes = bytearray()
if self.event != EVENT_NONE:
@@ -144,7 +144,7 @@ class TTSProvider(TTSProviderBase):
super().__init__(config, delete_audio_file)
self.ws = None
self.interface_type = InterfaceType.DUAL_STREAM
- self._monitor_task = None # 监听任务引用
+ self._monitor_task = None # Monitoring task reference
self.appId = config.get("appid")
self.access_token = config.get("access_token")
self.cluster = config.get("cluster")
@@ -160,7 +160,7 @@ class TTSProvider(TTSProviderBase):
self.speech_rate = int(speech_rate) if speech_rate else 0
self.loudness_rate = int(loudness_rate) if loudness_rate else 0
self.pitch = int(pitch) if pitch else 0
- # 多情感音色参数
+ # Multi-emotion voice parameters
self.emotion = config.get("emotion", "neutral")
emotion_scale = config.get("emotion_scale", "4")
self.emotion_scale = int(emotion_scale) if emotion_scale else 4
@@ -187,18 +187,18 @@ class TTSProvider(TTSProviderBase):
raise
async def _ensure_connection(self):
- """建立新的WebSocket连接,并启动监听任务(仅第一次)"""
+ """Establish new WebSocket connection and start monitoring task (first time only)"""
try:
if self.ws:
if self.enable_ws_reuse:
- logger.bind(tag=TAG).info(f"使用已有链接...")
+ logger.bind(tag=TAG).info(f"Using existing connection...")
return self.ws
else:
try:
await self.finish_connection()
except:
pass
- logger.bind(tag=TAG).debug("开始建立新连接...")
+ logger.bind(tag=TAG).debug("Starting to establish new connection...")
ws_header = {
"X-Api-App-Key": self.appId,
"X-Api-Access-Key": self.access_token,
@@ -210,9 +210,9 @@ class TTSProvider(TTSProviderBase):
)
logger.bind(tag=TAG).debug("WebSocket连接建立成功")
- # 连接建立成功后,启动监听任务
+ # After connection established, start monitoring task
if self._monitor_task is None or self._monitor_task.done():
- logger.bind(tag=TAG).debug("启动监听任务...")
+ logger.bind(tag=TAG).debug("Starting monitoring task...")
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
return self.ws
@@ -222,7 +222,7 @@ class TTSProvider(TTSProviderBase):
raise
async def finish_connection(self):
- """发送 FinishConnection 事件,等待服务端返回 EVENT_ConnectionFinished"""
+ """Send FinishConnection event, wait for server to return EVENT_ConnectionFinished"""
try:
if self.ws:
logger.bind(tag=TAG).debug("开始关闭连接...")
@@ -238,12 +238,12 @@ class TTSProvider(TTSProviderBase):
pass
def tts_text_priority_thread(self):
- """火山引擎双流式TTS的文本处理线程"""
+ """Volcengine dual-stream TTS text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
- f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
+ f"Received TTS task | {message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}"
)
if message.sentence_type == SentenceType.FIRST:
@@ -251,7 +251,7 @@ class TTSProvider(TTSProviderBase):
if self.conn.client_abort:
try:
- logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
+ logger.bind(tag=TAG).info("Received interrupt info, terminating TTS text processing thread")
if self.enable_ws_reuse:
asyncio.run_coroutine_threadsafe(
self.cancel_session(self.conn.sentence_id),
@@ -264,88 +264,88 @@ class TTSProvider(TTSProviderBase):
)
continue
except Exception as e:
- logger.bind(tag=TAG).error(f"取消TTS会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to cancel TTS session: {str(e)}")
continue
if message.sentence_type == SentenceType.FIRST:
- # 初始化参数
+ # Initialize parameters
try:
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
- logger.bind(tag=TAG).debug(f"自动生成新的 会话ID: {self.conn.sentence_id}")
+ logger.bind(tag=TAG).debug(f"Automatically generated new Session ID: {self.conn.sentence_id}")
- logger.bind(tag=TAG).debug("开始启动TTS会话...")
+ logger.bind(tag=TAG).debug("Starting TTS session...")
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
self.before_stop_play_files.clear()
- logger.bind(tag=TAG).debug("TTS会话启动成功")
+ logger.bind(tag=TAG).debug("TTS session started successfully")
except Exception as e:
- logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to start TTS session: {str(e)}")
continue
elif ContentType.TEXT == message.content_type:
if message.content_detail:
try:
logger.bind(tag=TAG).debug(
- f"开始发送TTS文本: {message.content_detail}"
+ f"Starting to send TTS text: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
loop=self.conn.loop,
)
future.result()
- logger.bind(tag=TAG).debug("TTS文本发送成功")
+ logger.bind(tag=TAG).debug("TTS text sent successfully")
except Exception as e:
- logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
continue
elif ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
- f"添加音频文件到待播放列表: {message.content_file}"
+ f"Adding audio file to playlist: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
- # 先处理文件音频数据
+ # Process file audio data first
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
if message.sentence_type == SentenceType.LAST:
try:
- logger.bind(tag=TAG).debug("开始结束TTS会话...")
+ logger.bind(tag=TAG).debug("Starting to end TTS session...")
future = asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
except Exception as e:
- logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to end TTS session: {str(e)}")
continue
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
- f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
continue
async def text_to_speak(self, text, _):
- """发送文本到TTS服务"""
+ """Send text to TTS service"""
try:
- # 建立新连接
+ # Establish new connection
if self.ws is None:
- logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
+ logger.bind(tag=TAG).warning(f"WebSocket connection does not exist, stop sending text")
return
- # 过滤Markdown
+ # Filter Markdown
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
- # 发送文本
+ # Send text
await self.send_text(self.voice, filtered_text, self.conn.sentence_id)
return
except Exception as e:
- logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
if self.ws:
try:
await self.ws.close()
@@ -355,23 +355,23 @@ class TTSProvider(TTSProviderBase):
raise
async def start_session(self, session_id):
- logger.bind(tag=TAG).debug(f"开始会话~~{session_id}")
+ logger.bind(tag=TAG).debug(f"Starting session~~{session_id}")
try:
- # 等待上一个会话结束,最多等待3次
+ # Wait for previous session to end, max 3 times
for _ in range(3):
if not self.activate_session:
break
- logger.bind(tag=TAG).debug(f"等待上一个会话结束...")
+ logger.bind(tag=TAG).debug(f"Waiting for previous session to end...")
await asyncio.sleep(0.1)
else:
- # 等待超时,强制清除连接状态
- logger.bind(tag=TAG).debug("等待上一个会话超时,清除连接状态...")
+ # Wait timeout, force clear connection state
+ logger.bind(tag=TAG).debug("Wait for previous session timeout, clearing connection state...")
await self.close()
- # 设置会话激活标志
+ # Set session activation flag
self.activate_session = True
- # 确保连接建立
+ # Ensure connection established
await self._ensure_connection()
header = Header(
@@ -386,15 +386,15 @@ class TTSProvider(TTSProviderBase):
event=EVENT_StartSession, speaker=self.voice
)
await self.send_event(self.ws, header, optional, payload)
- logger.bind(tag=TAG).debug("会话启动请求已发送")
+ logger.bind(tag=TAG).debug("Session start request sent")
except Exception as e:
- logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}")
# 确保清理资源
await self.close()
raise
async def finish_session(self, session_id):
- logger.bind(tag=TAG).debug(f"关闭会话~~{session_id}")
+ logger.bind(tag=TAG).debug(f"Closing session~~{session_id}")
try:
if self.ws:
header = Header(
@@ -407,16 +407,16 @@ class TTSProvider(TTSProviderBase):
).as_bytes()
payload = str.encode("{}")
await self.send_event(self.ws, header, optional, payload)
- logger.bind(tag=TAG).debug("会话结束请求已发送")
+ logger.bind(tag=TAG).debug("Session end request sent")
except Exception as e:
- logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
- # 确保清理资源
+ logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}")
+ # Ensure resources are cleaned up
await self.close()
raise
async def cancel_session(self,session_id):
- logger.bind(tag=TAG).debug(f"取消会话,释放服务端资源~~{session_id}")
+ logger.bind(tag=TAG).debug(f"Cancelling session, releasing server resources~~{session_id}")
try:
if self.ws:
header = Header(
@@ -429,15 +429,15 @@ class TTSProvider(TTSProviderBase):
).as_bytes()
payload = str.encode("{}")
await self.send_event(self.ws, header, optional, payload)
- logger.bind(tag=TAG).debug("会话取消请求已发送")
+ logger.bind(tag=TAG).debug("Session cancel request sent")
except Exception as e:
- logger.bind(tag=TAG).error(f"取消会话失败: {str(e)}")
- # 确保清理资源
+ logger.bind(tag=TAG).error(f"Failed to cancel session: {str(e)}")
+ # Ensure resources are cleaned up
await self.close()
raise
async def close(self):
- """资源清理方法"""
+ """Resource cleanup method"""
self.activate_session = False
# 取消监听任务
if self._monitor_task:
@@ -447,7 +447,7 @@ class TTSProvider(TTSProviderBase):
except asyncio.CancelledError:
pass
except Exception as e:
- logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
+ logger.bind(tag=TAG).warning(f"Error cancelling monitoring task during close: {e}")
self._monitor_task = None
if self.ws:
@@ -458,35 +458,35 @@ class TTSProvider(TTSProviderBase):
self.ws = None
async def _start_monitor_tts_response(self):
- """监听TTS响应 - 长期运行"""
+ """Monitor TTS response - Long running"""
try:
while not self.conn.stop_event.is_set():
try:
- # 确保 `recv()` 运行在同一个 event loop
+ # Ensure recv() runs in same event loop
msg = await self.ws.recv()
res = self.parser_response(msg)
self.print_response(res, "send_text res:")
- # 优先处理连接级别事件
+ # prioritize connection level events
if res.optional.event == EVENT_ConnectionFinished:
- logger.bind(tag=TAG).debug(f"链接关闭成功~~")
+ logger.bind(tag=TAG).debug(f"Connection closed successfully~~")
break
- # 只处理当前活跃会话的响应
+ # Only process response for current active session
if res.optional.sessionId and self.conn.sentence_id != res.optional.sessionId:
- # 如果是会话结束相关事件,即使会话ID不匹配也要重置状态
+ # If session end related event, reset state even if session ID mismatch
if res.optional.event in [EVENT_SessionCanceled, EVENT_SessionFailed, EVENT_SessionFinished]:
- logger.bind(tag=TAG).debug(f"收到残余下行结束响应重置会话状态~~")
+ logger.bind(tag=TAG).debug(f"Received residual downstream end response, resetting session state~~")
self.activate_session = False
continue
if res.optional.event == EVENT_SessionCanceled:
- logger.bind(tag=TAG).debug(f"释放服务端资源成功~~")
+ logger.bind(tag=TAG).debug(f"Released server resources successfully~~")
self.activate_session = False
elif res.optional.event == EVENT_TTSSentenceStart:
json_data = json.loads(res.payload.decode("utf-8"))
self.tts_text = json_data.get("text", "")
- logger.bind(tag=TAG).debug(f"句子语音生成开始: {self.tts_text}")
+ logger.bind(tag=TAG).debug(f"Sentence voice generation start: {self.tts_text}")
self.tts_audio_queue.put(
(SentenceType.FIRST, [], self.tts_text)
)
@@ -496,16 +496,16 @@ class TTSProvider(TTSProviderBase):
):
self.wav_to_opus_data_audio_raw_stream(res.payload, callback=self.handle_opus)
elif res.optional.event == EVENT_TTSSentenceEnd:
- logger.bind(tag=TAG).info(f"句子语音生成成功:{self.tts_text}")
+ logger.bind(tag=TAG).info(f"Sentence voice generation successful: {self.tts_text}")
elif res.optional.event == EVENT_SessionFinished:
- logger.bind(tag=TAG).debug(f"会话结束~~")
+ logger.bind(tag=TAG).debug(f"Session ended~~")
self.activate_session = False
self._process_before_stop_play_files()
- # 非复用模式下,会话结束后发送 FinishConnection
+ # In non-reuse mode, send FinishConnection after session ends
if not self.enable_ws_reuse:
await self.finish_connection()
except websockets.ConnectionClosed:
- logger.bind(tag=TAG).warning("WebSocket连接已关闭")
+ logger.bind(tag=TAG).warning("WebSocket connection closed")
break
except Exception as e:
logger.bind(tag=TAG).error(
@@ -513,14 +513,14 @@ class TTSProvider(TTSProviderBase):
)
traceback.print_exc()
break
- # 连接异常时关闭WebSocket
+ # Close WebSocket on connection exception
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
- # 监听任务退出时清理引用
+ # Clean up reference when monitoring task exits
finally:
self.activate_session = False
self._monitor_task = None
@@ -557,7 +557,7 @@ class TTSProvider(TTSProviderBase):
)
return await self.send_event(self.ws, header, optional, payload)
- # 读取 res 数组某段 字符串内容
+ # Read string content from res array segment
def read_res_content(self, res: bytes, offset: int):
content_size = int.from_bytes(res[offset : offset + 4], "big", signed=True)
offset += 4
@@ -565,7 +565,7 @@ class TTSProvider(TTSProviderBase):
offset += content_size
return content, offset
- # 读取 payload
+ # Read payload
def read_res_payload(self, res: bytes, offset: int):
payload_size = int.from_bytes(res[offset : offset + 4], "big", signed=True)
offset += 4
@@ -577,7 +577,7 @@ class TTSProvider(TTSProviderBase):
if isinstance(res, str):
raise RuntimeError(res)
response = Response(Header(), Optional())
- # 解析结果
+ # Parse result
# header
header = response.header
num = 0b00001111
@@ -655,7 +655,7 @@ class TTSProvider(TTSProviderBase):
"loudness_rate": self.loudness_rate
}
- # 如果是多情感音色,添加情感参数
+ # If multi-emotion voice, add emotion parameters
if '_emo_' in self.voice:
if self.emotion:
audio_params["emotion"] = self.emotion
@@ -686,25 +686,25 @@ class TTSProvider(TTSProviderBase):
return self.opus_encoder.encode_pcm_to_opus_stream(raw_data_var, is_end, callback=callback)
def to_tts(self, text: str) -> list:
- """非流式生成音频数据,用于生成音频及测试场景
+ """Non-streaming audio generation, used for generating audio and testing scenarios
Args:
- text: 要转换的文本
+ text: Text to convert
Returns:
- list: 音频数据列表
+ list: Audio data list
"""
try:
- # 创建事件循环
+ # Create event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
- # 生成会话ID
+ # Generate Session ID
session_id = uuid.uuid4().__str__().replace("-", "")
- # 存储音频数据
+ # Store audio data
audio_data = []
async def _generate_audio():
- # 创建新的WebSocket连接
+ # Create new WebSocket connection
ws_header = {
"X-Api-App-Key": self.appId,
"X-Api-Access-Key": self.access_token,
@@ -716,7 +716,7 @@ class TTSProvider(TTSProviderBase):
)
try:
- # 启动会话
+ # Start session
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@@ -730,7 +730,7 @@ class TTSProvider(TTSProviderBase):
)
await self.send_event(ws, header, optional, payload)
- # 发送文本
+ # Send text
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@@ -744,7 +744,7 @@ class TTSProvider(TTSProviderBase):
)
await self.send_event(ws, header, optional, payload)
- # 发送结束会话请求
+ # Send end session request
header = Header(
message_type=FULL_CLIENT_REQUEST,
message_type_specific_flags=MsgTypeFlagWithEvent,
@@ -756,7 +756,7 @@ class TTSProvider(TTSProviderBase):
payload = str.encode("{}")
await self.send_event(ws, header, optional, payload)
- # 接收音频数据
+ # Receive audio data
while True:
msg = await ws.recv()
res = self.parser_response(msg)
@@ -770,18 +770,18 @@ class TTSProvider(TTSProviderBase):
break
finally:
- # 清理资源
+ # Clean up resources
try:
await ws.close()
except:
pass
- # 运行异步任务
+ # Run async task
loop.run_until_complete(_generate_audio())
loop.close()
return audio_data
except Exception as e:
- logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to generate audio data: {str(e)}")
return []
diff --git a/main/xiaozhi-server/core/providers/tts/paddle_speech.py b/main/xiaozhi-server/core/providers/tts/paddle_speech.py
index 864cf505c..625eccc4a 100644
--- a/main/xiaozhi-server/core/providers/tts/paddle_speech.py
+++ b/main/xiaozhi-server/core/providers/tts/paddle_speech.py
@@ -51,17 +51,19 @@ class TTSProvider(TTSProviderBase):
else:
self.save_path = None
+ async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1,
+ bits_per_sample: int = 16) -> bytes:
async def pcm_to_wav(self, pcm_data: bytes, sample_rate: int = 24000, num_channels: int = 1,
bits_per_sample: int = 16) -> bytes:
"""
- 将 PCM 数据转换为 WAV 文件并返回字节数据
- :param pcm_data: PCM 数据(原始字节流)
- :param sample_rate: 音频采样率,默认为24000
- :param num_channels: 声道数,默认为单声道
- :param bits_per_sample: 每个样本的位数,默认为16
- :return: WAV 格式的字节数据
+ Convert PCM data to WAV file and return byte data
+ :param pcm_data: PCM data (raw byte stream)
+ :param sample_rate: Audio sampling rate, default is 24000
+ :param num_channels: Number of channels, default is mono
+ :param bits_per_sample: Bits per sample, default is 16
+ :return: WAV format byte data
"""
- byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16位PCM
+ byte_data = np.frombuffer(pcm_data, dtype=np.int16) # 16-bit PCM
wav_io = io.BytesIO()
with wave.open(wav_io, "wb") as wav_file:
@@ -80,24 +82,24 @@ class TTSProvider(TTSProviderBase):
async def text_streaming(self, text, output_file):
try:
- # 使用 websockets 异步连接到 WebSocket 服务器
+ # Connect to WebSocket server asynchronously using websockets
async with websockets.connect(self.url) as ws:
- # 发送开始请求
+ # Send start request
start_request = {
"task": "tts",
"signal": "start"
}
await ws.send(json.dumps(start_request))
- # 接收开始响应并提取 session_id
+ # Receive start response and extract session_id
start_response = await ws.recv()
- start_response = json.loads(start_response) # 解析 JSON 响应
+ start_response = json.loads(start_response) # Parse JSON response
if start_response.get("status") != 0:
- raise Exception(f"连接失败: {start_response.get('signal')}")
+ raise Exception(f"Connection failed: {start_response.get('signal')}")
session_id = start_response.get("session")
- # 发送待合成的文本数据
+ # Send text data to be synthesized
data_request = {
"text": text,
"spk_id": self.spk_id,
@@ -105,42 +107,42 @@ class TTSProvider(TTSProviderBase):
await ws.send(json.dumps(data_request))
audio_chunks = b""
- timeout_seconds = 60 # 设置超时
+ timeout_seconds = 60 # Set timeout
try:
while True:
response = await asyncio.wait_for(ws.recv(), timeout=timeout_seconds)
- response = json.loads(response) # 解析 JSON 响应
+ response = json.loads(response) # Parse JSON response
status = response.get("status")
- if status == 2: # 最后一个数据包
+ if status == 2: # Last packet
break
else:
- # 拼接音频数据(base64 编码的 PCM 数据)
+ # Concatenate audio data (base64 encoded PCM data)
audio_chunks += base64.b64decode(response.get("audio"))
except asyncio.TimeoutError:
- raise Exception(f"WebSocket 超时:等待音频数据超过 {timeout_seconds} 秒")
+ raise Exception(f"WebSocket timeout: waiting for audio data exceeded {timeout_seconds} seconds")
- # 将拼接后的 PCM 数据转换为 WAV 格式
+ # Convert concatenated PCM data to WAV format
wav_data = await self.pcm_to_wav(audio_chunks)
- # 结束请求
+ # End request
end_request = {
"task": "tts",
"signal": "end",
- "session": session_id # 会话 ID 必须与开始请求中的一致
+ "session": session_id # Session ID must match start request
}
await ws.send(json.dumps(end_request))
- # 接收结束响应避免服务抛出异常
+ # Receive end response to avoid exception
await ws.recv()
- # 根据配置决定是否保存文件
+ # Decide whether to save file based on config
if not self.delete_audio_file and self.save_path:
with open(self.save_path, "wb") as f:
f.write(wav_data)
- logger.bind(tag=TAG).info(f"音频文件已保存到: {self.save_path}")
+ logger.bind(tag=TAG).info(f"Audio file saved to: {self.save_path}")
- # 返回或保存音频数据
+ # Return or save audio data
if output_file:
with open(output_file, "wb") as file_to_save:
file_to_save.write(wav_data)
diff --git a/main/xiaozhi-server/core/providers/tts/xunfei_stream.py b/main/xiaozhi-server/core/providers/tts/xunfei_stream.py
index dc8d833f4..cb35ebd57 100644
--- a/main/xiaozhi-server/core/providers/tts/xunfei_stream.py
+++ b/main/xiaozhi-server/core/providers/tts/xunfei_stream.py
@@ -24,19 +24,19 @@ logger = setup_logging()
class XunfeiWSAuth:
@staticmethod
def create_auth_url(api_key, api_secret, api_url):
- """生成讯飞WebSocket认证URL"""
+ """Generate Xunfei WebSocket Auth URL"""
parsed_url = urlparse(api_url)
host = parsed_url.netloc
path = parsed_url.path
- # 获取UTC时间,讯飞要求使用RFC1123格式
+ # Get UTC time, Xunfei requires RFC1123 format
now = time.gmtime()
date = time.strftime('%a, %d %b %Y %H:%M:%S GMT', now)
- # 构造签名字符串
+ # Construct signature string
signature_origin = f"host: {host}\ndate: {date}\nGET {path} HTTP/1.1"
- # 计算签名
+ # Calculate signature
signature_sha = hmac.new(
api_secret.encode('utf-8'),
signature_origin.encode('utf-8'),
@@ -44,11 +44,11 @@ class XunfeiWSAuth:
).digest()
signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')
- # 构造authorization
+ # Construct authorization
authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
- # 构造最终的WebSocket URL
+ # Construct final WebSocket URL
v = {
"authorization": authorization,
"date": date,
@@ -62,23 +62,23 @@ class TTSProvider(TTSProviderBase):
def __init__(self, config, delete_audio_file):
super().__init__(config, delete_audio_file)
- # 设置为流式接口类型
+ # Set to stream interface type
self.interface_type = InterfaceType.DUAL_STREAM
- # 基础配置
+ # Basic config
self.app_id = config.get("app_id")
self.api_key = config.get("api_key")
self.api_secret = config.get("api_secret")
- # 接口地址
+ # Interface address
self.api_url = config.get("api_url", "wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/mcd9m97e6")
- # 音色配置
+ # Voice config
self.voice = config.get("voice", "x5_lingxiaoxuan_flow")
if config.get("private_voice"):
self.voice = config.get("private_voice")
- # 音频参数配置
+ # Audio parameter config
speed = config.get("speed", "50")
self.speed = int(speed) if speed else 50
@@ -88,13 +88,13 @@ class TTSProvider(TTSProviderBase):
pitch = config.get("pitch", "50")
self.pitch = int(pitch) if pitch else 50
- # 音频编码配置
+ # Audio encoding config
self.format = config.get("format", "raw")
sample_rate = config.get("sample_rate", "24000")
self.sample_rate = int(sample_rate) if sample_rate else 24000
- # 口语化配置
+ # Colloquial config
self.oral_level = config.get("oral_level", "mid")
spark_assist = config.get("spark_assist", "1")
@@ -106,28 +106,28 @@ class TTSProvider(TTSProviderBase):
remain = config.get("remain", "0")
self.remain = int(remain) if remain else 0
- # WebSocket配置
+ # WebSocket config
self.ws = None
self._monitor_task = None
- # 序列号管理
+ # Sequence number management
self.text_seq = 0
- # 创建Opus编码器
+ # Create Opus encoder
self.opus_encoder = opus_encoder_utils.OpusEncoderUtils(
sample_rate=self.sample_rate, channels=1, frame_size_ms=60
)
- # 验证必需参数
+ # Verify required parameters
if not all([self.app_id, self.api_key, self.api_secret]):
- raise ValueError("讯飞TTS需要配置app_id、api_key和api_secret")
+ raise ValueError("Xunfei TTS requires app_id, api_key and api_secret")
async def _ensure_connection(self):
- """确保WebSocket连接可用"""
+ """Ensure WebSocket connection is available"""
try:
- logger.bind(tag=TAG).info("开始建立新连接...")
+ logger.bind(tag=TAG).info("Starting to establish new connection...")
- # 生成认证URL
+ # Generate Auth URL
auth_url = XunfeiWSAuth.create_auth_url(
self.api_key, self.api_secret, self.api_url
)
@@ -138,113 +138,113 @@ class TTSProvider(TTSProviderBase):
ping_timeout=10,
close_timeout=10,
)
- logger.bind(tag=TAG).info("WebSocket连接建立成功")
+ logger.bind(tag=TAG).info("WebSocket connection established successfully")
return self.ws
except Exception as e:
- logger.bind(tag=TAG).error(f"建立连接失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Connection failed: {str(e)}")
self.ws = None
raise
def tts_text_priority_thread(self):
- """流式文本处理线程"""
+ """Streaming text processing thread"""
while not self.conn.stop_event.is_set():
try:
message = self.tts_text_queue.get(timeout=1)
logger.bind(tag=TAG).debug(
- f"收到TTS任务|{message.sentence_type.name} | {message.content_type.name} | 会话ID: {self.conn.sentence_id}"
+ f"Received TTS task | {message.sentence_type.name} | {message.content_type.name} | Session ID: {self.conn.sentence_id}"
)
if message.sentence_type == SentenceType.FIRST:
- # 重置序列号
+ # Reset sequence number
self.text_seq = 0
self.conn.client_abort = False
- # 增加序列号
+ # Increment sequence number
self.text_seq += 1
if self.conn.client_abort:
- logger.bind(tag=TAG).info("收到打断信息,终止TTS文本处理线程")
+ logger.bind(tag=TAG).info("Received interrupt info, terminating TTS text processing thread")
continue
if message.sentence_type == SentenceType.FIRST:
- # 初始化参数
+ # Initialize parameters
try:
if not getattr(self.conn, "sentence_id", None):
self.conn.sentence_id = uuid.uuid4().hex
- logger.bind(tag=TAG).info(f"自动生成新的 会话ID: {self.conn.sentence_id}")
+ logger.bind(tag=TAG).info(f"Automatically generated new Session ID: {self.conn.sentence_id}")
- logger.bind(tag=TAG).info("开始启动TTS会话...")
+ logger.bind(tag=TAG).info("Starting TTS session...")
future = asyncio.run_coroutine_threadsafe(
self.start_session(self.conn.sentence_id),
loop=self.conn.loop,
)
future.result()
self.before_stop_play_files.clear()
- logger.bind(tag=TAG).info("TTS会话启动成功")
+ logger.bind(tag=TAG).info("TTS session started successfully")
except Exception as e:
- logger.bind(tag=TAG).error(f"启动TTS会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to start TTS session: {str(e)}")
continue
- # 处理文本内容
+ # Process text content
if ContentType.TEXT == message.content_type:
if message.content_detail:
try:
logger.bind(tag=TAG).debug(
- f"开始发送TTS文本: {message.content_detail}"
+ f"Starting to send TTS text: {message.content_detail}"
)
future = asyncio.run_coroutine_threadsafe(
self.text_to_speak(message.content_detail, None),
loop=self.conn.loop,
)
future.result()
- logger.bind(tag=TAG).debug("TTS文本发送成功")
+ logger.bind(tag=TAG).debug("TTS text sent successfully")
except Exception as e:
- logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
- # 不使用continue,确保后续处理不被中断
+ logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
+ # Do not use continue, ensure subsequent processing is not interrupted
- # 处理文件内容
+ # Process file content
if ContentType.FILE == message.content_type:
logger.bind(tag=TAG).info(
- f"添加音频文件到待播放列表: {message.content_file}"
+ f"Adding audio file to playlist: {message.content_file}"
)
if message.content_file and os.path.exists(message.content_file):
- # 先处理文件音频数据
+ # Process file audio data first
self._process_audio_file_stream(message.content_file, callback=lambda audio_data: self.handle_audio_file(audio_data, message.content_detail))
- # 处理会话结束
+ # Process session end
if message.sentence_type == SentenceType.LAST:
try:
- logger.bind(tag=TAG).info("开始结束TTS会话...")
+ logger.bind(tag=TAG).info("Starting to end TTS session...")
asyncio.run_coroutine_threadsafe(
self.finish_session(self.conn.sentence_id),
loop=self.conn.loop,
)
except Exception as e:
- logger.bind(tag=TAG).error(f"结束TTS会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to end TTS session: {str(e)}")
continue
except queue.Empty:
continue
except Exception as e:
logger.bind(tag=TAG).error(
- f"处理TTS文本失败: {str(e)}, 类型: {type(e).__name__}, 堆栈: {traceback.format_exc()}"
+ f"Failed to process TTS text: {str(e)}, Type: {type(e).__name__}, Stack: {traceback.format_exc()}"
)
async def text_to_speak(self, text, _):
- """发送文本到TTS服务进行合成"""
+ """Send text to TTS service for synthesis"""
try:
if self.ws is None:
- logger.bind(tag=TAG).warning(f"WebSocket连接不存在,终止发送文本")
+ logger.bind(tag=TAG).warning(f"WebSocket connection does not exist, stop sending text")
return
filtered_text = MarkdownCleaner.clean_markdown(text)
if filtered_text:
- # 发送文本合成请求
+ # Send text synthesis request
run_request = self._build_base_request(status=1,text=filtered_text)
await self.ws.send(json.dumps(run_request))
return
except Exception as e:
- logger.bind(tag=TAG).error(f"发送TTS文本失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to send TTS text: {str(e)}")
if self.ws:
try:
await self.ws.close()
@@ -254,59 +254,59 @@ class TTSProvider(TTSProviderBase):
raise
async def start_session(self, session_id):
- logger.bind(tag=TAG).info(f"开始会话~~{session_id}")
+ logger.bind(tag=TAG).info(f"Starting session~~{session_id}")
try:
- # 会话开始时检测上个会话的监听状态
+ # Check listening status of previous session when session starts
if (
self._monitor_task is not None
and isinstance(self._monitor_task, Task)
and not self._monitor_task.done()
):
logger.bind(tag=TAG).info(
- "检测到未完成的上个会话,关闭监听任务和连接..."
+ "Detected incomplete previous session, closing monitoring task and connection..."
)
await self.close()
- # 建立新连接
+ # Establish new connection
await self._ensure_connection()
- # 启动监听任务
+ # Start monitoring task
self._monitor_task = asyncio.create_task(self._start_monitor_tts_response())
- # 发送会话启动请求
+ # Send session start request
start_request = self._build_base_request(status=0)
await self.ws.send(json.dumps(start_request))
- logger.bind(tag=TAG).info("会话启动请求已发送")
+ logger.bind(tag=TAG).info("Session start request sent")
except Exception as e:
- logger.bind(tag=TAG).error(f"启动会话失败: {str(e)}")
- # 确保清理资源
+ logger.bind(tag=TAG).error(f"Failed to start session: {str(e)}")
+ # Ensure resources are cleaned up
await self.close()
raise
async def finish_session(self, session_id):
- logger.bind(tag=TAG).info(f"关闭会话~~{session_id}")
+ logger.bind(tag=TAG).info(f"Closing session~~{session_id}")
try:
if self.ws:
- # 发送会话结束请求
+ # Send session end request
stop_request = self._build_base_request(status=2)
await self.ws.send(json.dumps(stop_request))
- logger.bind(tag=TAG).info("会话结束请求已发送")
+ logger.bind(tag=TAG).info("Session end request sent")
if self._monitor_task:
try:
await self._monitor_task
except Exception as e:
- logger.bind(tag=TAG).error(f"等待监听任务完成时发生错误: {str(e)}")
+ logger.bind(tag=TAG).error(f"Error waiting for monitoring task to complete: {str(e)}")
finally:
self._monitor_task = None
except Exception as e:
- logger.bind(tag=TAG).error(f"关闭会话失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to close session: {str(e)}")
await self.close()
raise
async def close(self):
- """资源清理"""
+ """Resource cleanup"""
if self._monitor_task:
try:
self._monitor_task.cancel()
@@ -314,7 +314,7 @@ class TTSProvider(TTSProviderBase):
except asyncio.CancelledError:
pass
except Exception as e:
- logger.bind(tag=TAG).warning(f"关闭时取消监听任务错误: {e}")
+ logger.bind(tag=TAG).warning(f"Error cancelling monitoring task during close: {e}")
self._monitor_task = None
if self.ws:
@@ -325,15 +325,15 @@ class TTSProvider(TTSProviderBase):
self.ws = None
async def _start_monitor_tts_response(self):
- """监听TTS响应"""
+ """Monitor TTS response"""
try:
while not self.conn.stop_event.is_set():
try:
msg = await self.ws.recv()
- # 检查客户端是否中止
+ # Check if client aborted
if self.conn.client_abort:
- logger.bind(tag=TAG).info("收到打断信息,终止监听TTS响应")
+ logger.bind(tag=TAG).info("Received interrupt info, stop monitoring TTS response")
break
try:
@@ -349,18 +349,18 @@ class TTSProvider(TTSProviderBase):
status = audio_payload.get("status", 0)
audio_data = audio_payload.get("audio", "")
if status == 0:
- logger.bind(tag=TAG).debug("TTS合成已启动")
+ logger.bind(tag=TAG).debug("TTS synthesis started")
self.tts_audio_queue.put(
(SentenceType.FIRST, [], None)
)
elif status == 2:
- logger.bind(tag=TAG).debug("收到结束状态的音频数据,TTS合成完成")
+ logger.bind(tag=TAG).debug("Received end status audio data, TTS synthesis completed")
self._process_before_stop_play_files()
break
else:
if self.conn.tts_MessageText:
logger.bind(tag=TAG).info(
- f"句子语音生成成功: {self.conn.tts_MessageText}"
+ f"Sentence voice generation successful: {self.conn.tts_MessageText}"
)
self.tts_audio_queue.put(
(SentenceType.FIRST, [], self.conn.tts_MessageText)
@@ -373,54 +373,54 @@ class TTSProvider(TTSProviderBase):
)
except Exception as e:
- logger.bind(tag=TAG).error(f"处理音频数据失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to process audio data: {e}")
else:
- message = header.get("message", "未知错误")
- logger.bind(tag=TAG).error(f"TTS合成错误: {code} - {message}")
+ message = header.get("message", "Unknown error")
+ logger.bind(tag=TAG).error(f"TTS synthesis error: {code} - {message}")
break
except json.JSONDecodeError:
- logger.bind(tag=TAG).warning("收到无效的JSON消息")
+ logger.bind(tag=TAG).warning("Received invalid JSON message")
except websockets.ConnectionClosed:
- logger.bind(tag=TAG).warning("WebSocket连接已关闭")
+ logger.bind(tag=TAG).warning("WebSocket connection closed")
break
except Exception as e:
logger.bind(tag=TAG).error(
- f"处理TTS响应时出错: {e}\n{traceback.format_exc()}"
+ f"Error processing TTS response: {e}\n{traceback.format_exc()}"
)
break
- # 链接不可复用
+ # Connection not reusable
if self.ws:
try:
await self.ws.close()
except:
pass
self.ws = None
- # 监听任务退出时清理引用
+ # Clean up reference when monitoring task exits
finally:
self._monitor_task = None
def to_tts(self, text: str) -> list:
- """非流式TTS处理,用于测试及保存音频文件的场景"""
+ """Non-streaming TTS processing, used for testing and saving audio files"""
try:
- # 创建新的事件循环
+ # Create new event loop
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
- # 存储音频数据
+ # Store audio data
audio_data = []
async def _generate_audio():
- # 生成认证URL
+ # Generate Auth URL
auth_url = XunfeiWSAuth.create_auth_url(
self.api_key, self.api_secret, self.api_url
)
- # 建立WebSocket连接
+ # Establish WebSocket connection
ws = await websockets.connect(
auth_url,
ping_interval=30,
@@ -458,17 +458,17 @@ class TTSProvider(TTSProviderBase):
callback=lambda opus: audio_data.append(opus)
)
except Exception as e:
- logger.bind(tag=TAG).error(f"处理音频数据失败: {e}")
+ logger.bind(tag=TAG).error(f"Failed to process audio data: {e}")
elif status == 2:
task_finished = True
- logger.bind(tag=TAG).debug("TTS任务完成")
+ logger.bind(tag=TAG).debug("TTS task completed")
else:
- message = header.get("message", "未知错误")
- raise Exception(f"合成失败: {code} - {message}")
+ message = header.get("message", "Unknown error")
+ raise Exception(f"Synthesis failed: {code} - {message}")
finally:
- # 清理资源
+ # Clean up resources
try:
await ws.close()
except:
@@ -479,11 +479,11 @@ class TTSProvider(TTSProviderBase):
return audio_data
except Exception as e:
- logger.bind(tag=TAG).error(f"生成音频数据失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Failed to generate audio data: {str(e)}")
return []
def _build_base_request(self, status,text=" "):
- """构建基础请求结构"""
+ """Build base request structure"""
return {
"header": {
"app_id": self.app_id,
diff --git a/main/xiaozhi-server/core/providers/vad/base.py b/main/xiaozhi-server/core/providers/vad/base.py
index 1d8d4c8dd..9e909e9bd 100644
--- a/main/xiaozhi-server/core/providers/vad/base.py
+++ b/main/xiaozhi-server/core/providers/vad/base.py
@@ -5,5 +5,5 @@ from typing import Optional
class VADProviderBase(ABC):
@abstractmethod
def is_vad(self, conn, data) -> bool:
- """检测音频数据中的语音活动"""
+ """Detect voice activity in audio data"""
pass
diff --git a/main/xiaozhi-server/core/providers/vad/silero.py b/main/xiaozhi-server/core/providers/vad/silero.py
index 81215681f..a5b621149 100644
--- a/main/xiaozhi-server/core/providers/vad/silero.py
+++ b/main/xiaozhi-server/core/providers/vad/silero.py
@@ -21,7 +21,7 @@ class VADProvider(VADProviderBase):
self.decoder = opuslib_next.Decoder(16000, 1)
- # 处理空字符串的情况
+ # Handle empty string case
threshold = config.get("threshold", "0.5")
threshold_low = config.get("threshold_low", "0.2")
min_silence_duration_ms = config.get("min_silence_duration_ms", "1000")
@@ -33,7 +33,7 @@ class VADProvider(VADProviderBase):
int(min_silence_duration_ms) if min_silence_duration_ms else 1000
)
- # 至少要多少帧才算有语音
+ # Minimum frames to count as voice
self.frame_window_threshold = 3
def __del__(self):
@@ -44,31 +44,31 @@ class VADProvider(VADProviderBase):
pass
def is_vad(self, conn, opus_packet):
- # 手动模式:直接返回True,不进行实时VAD检测,所有音频都缓存
+ # Manual mode: return True directly, no real-time VAD detection, buffer all audio
if conn.client_listen_mode == "manual":
return True
try:
pcm_frame = self.decoder.decode(opus_packet, 960)
- conn.client_audio_buffer.extend(pcm_frame) # 将新数据加入缓冲区
+ conn.client_audio_buffer.extend(pcm_frame) # Add new data to buffer
- # 处理缓冲区中的完整帧(每次处理512采样点)
+ # Process complete frames in buffer (512 samples each)
client_have_voice = False
while len(conn.client_audio_buffer) >= 512 * 2:
- # 提取前512个采样点(1024字节)
+ # Extract first 512 samples (1024 bytes)
chunk = conn.client_audio_buffer[: 512 * 2]
conn.client_audio_buffer = conn.client_audio_buffer[512 * 2 :]
- # 转换为模型需要的张量格式
+ # Convert to tensor format required by model
audio_int16 = np.frombuffer(chunk, dtype=np.int16)
audio_float32 = audio_int16.astype(np.float32) / 32768.0
audio_tensor = torch.from_numpy(audio_float32)
- # 检测语音活动
+ # Detect voice activity
with torch.no_grad():
speech_prob = self.model(audio_tensor, 16000).item()
- # 双阈值判断
+ # Dual threshold judgment
if speech_prob >= self.vad_threshold:
is_voice = True
elif speech_prob <= self.vad_threshold_low:
@@ -76,16 +76,16 @@ class VADProvider(VADProviderBase):
else:
is_voice = conn.last_is_voice
- # 声音没低于最低值则延续前一个状态,判断为有声音
+ # If sound not below min threshold, continue previous state, judge as voice present
conn.last_is_voice = is_voice
- # 更新滑动窗口
+ # Update sliding window
conn.client_voice_window.append(is_voice)
client_have_voice = (
conn.client_voice_window.count(True) >= self.frame_window_threshold
)
- # 如果之前有声音,但本次没有声音,且与上次有声音的时间差已经超过了静默阈值,则认为已经说完一句话
+ # If previously voice present, but now silent, and time since last voice exceeds silence threshold, sentence is finished
if conn.client_have_voice and not client_have_voice:
stop_duration = time.time() * 1000 - conn.last_activity_time
if stop_duration >= self.silence_threshold_ms:
@@ -96,6 +96,6 @@ class VADProvider(VADProviderBase):
return client_have_voice
except opuslib_next.OpusError as e:
- logger.bind(tag=TAG).info(f"解码错误: {e}")
+ logger.bind(tag=TAG).info(f"Decoding error: {e}")
except Exception as e:
logger.bind(tag=TAG).error(f"Error processing audio packet: {e}")
diff --git a/main/xiaozhi-server/core/providers/vllm/openai.py b/main/xiaozhi-server/core/providers/vllm/openai.py
index 49bef99ec..f6aba2782 100644
--- a/main/xiaozhi-server/core/providers/vllm/openai.py
+++ b/main/xiaozhi-server/core/providers/vllm/openai.py
@@ -40,7 +40,7 @@ class VLLMProvider(VLLMProviderBase):
self.client = openai.OpenAI(api_key=self.api_key, base_url=self.base_url)
def response(self, question, base64_image):
- question = question + "(请使用中文回复)"
+ question = question + "(Please reply in English)"
try:
messages = [
{
diff --git a/main/xiaozhi-server/core/utils/asr.py b/main/xiaozhi-server/core/utils/asr.py
index 983114d32..2bf2fe048 100644
--- a/main/xiaozhi-server/core/utils/asr.py
+++ b/main/xiaozhi-server/core/utils/asr.py
@@ -14,11 +14,11 @@ TAG = __name__
logger = setup_logging()
def create_instance(class_name: str, *args, **kwargs) -> ASRProviderBase:
- """工厂方法创建ASR实例"""
+ """Factory method for creating ASR instance"""
if os.path.exists(os.path.join('core', 'providers', 'asr', f'{class_name}.py')):
lib_name = f'core.providers.asr.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].ASRProvider(*args, **kwargs)
- raise ValueError(f"不支持的ASR类型: {class_name},请检查该配置的type是否设置正确")
\ No newline at end of file
+ raise ValueError(f"Unsupported ASR type: {class_name}, please check if the type in config is set correctly")
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/utils/audioRateController.py b/main/xiaozhi-server/core/utils/audioRateController.py
index 01d71b053..2b89e0dd2 100644
--- a/main/xiaozhi-server/core/utils/audioRateController.py
+++ b/main/xiaozhi-server/core/utils/audioRateController.py
@@ -9,82 +9,82 @@ logger = setup_logging()
class AudioRateController:
"""
- 音频速率控制器 - 按照60ms帧时长精确控制音频发送
- 解决高并发下的时间累积误差问题
+ Audio Rate Controller - Precisely controls audio sending based on 60ms frame duration
+ Solves time accumulation error in high concurrency
"""
def __init__(self, frame_duration=60):
"""
Args:
- frame_duration: 单个音频帧时长(毫秒),默认60ms
+ frame_duration: Duration of a single audio frame (ms), default 60ms
"""
self.frame_duration = frame_duration
self.queue = deque()
- self.play_position = 0 # 虚拟播放位置(毫秒)
- self.start_timestamp = None # 开始时间戳(只读,不修改)
+ self.play_position = 0 # Virtual playback position (ms)
+ self.start_timestamp = None # Start timestamp (read-only, not modified)
self.pending_send_task = None
self.logger = logger
- self.queue_empty_event = asyncio.Event() # 队列清空事件
- self.queue_empty_event.set() # 初始为空状态
- self.queue_has_data_event = asyncio.Event() # 队列数据事件
+ self.queue_empty_event = asyncio.Event() # Queue empty event
+ self.queue_empty_event.set() # Initial state is empty
+ self.queue_has_data_event = asyncio.Event() # Queue has data event
def reset(self):
- """重置控制器状态"""
+ """Reset controller state"""
if self.pending_send_task and not self.pending_send_task.done():
self.pending_send_task.cancel()
- # 取消任务后,任务会在下次事件循环时清理,无需阻塞等待
+ # After cancelling task, it will be cleaned up in next event loop, no need to block wait
self.queue.clear()
self.play_position = 0
- self.start_timestamp = None # 由首个音频包设置
- # 相关事件处理
+ self.start_timestamp = None # Set by the first audio packet
+ # Event handling
self.queue_empty_event.set()
self.queue_has_data_event.clear()
def add_audio(self, opus_packet):
- """添加音频包到队列"""
+ """Add audio packet to queue"""
self.queue.append(("audio", opus_packet))
- # 相关事件处理
+ # Event handling
self.queue_empty_event.clear()
self.queue_has_data_event.set()
def add_message(self, message_callback):
"""
- 添加消息到队列(立即发送,不占用播放时间)
+ Add message to queue (send immediately, does not consume playback time)
Args:
- message_callback: 消息发送回调函数 async def()
+ message_callback: Message sending callback function async def()
"""
self.queue.append(("message", message_callback))
- # 相关事件处理
+ # Event handling
self.queue_empty_event.clear()
self.queue_has_data_event.set()
def _get_elapsed_ms(self):
- """获取已经过的时间(毫秒)"""
+ """Get elapsed time (ms)"""
if self.start_timestamp is None:
return 0
return (time.monotonic() - self.start_timestamp) * 1000
async def check_queue(self, send_audio_callback):
"""
- 检查队列并按时发送音频/消息
+ Check queue and send audio/message on time
Args:
- send_audio_callback: 发送音频的回调函数 async def(opus_packet)
+ send_audio_callback: Audio sending callback function async def(opus_packet)
"""
while self.queue:
item = self.queue[0]
item_type = item[0]
if item_type == "message":
- # 消息类型:立即发送,不占用播放时间
+ # Message type: send immediately, does not consume playback time
_, message_callback = item
self.queue.popleft()
try:
await message_callback()
except Exception as e:
- self.logger.bind(tag=TAG).error(f"发送消息失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to send message: {e}")
raise
elif item_type == "audio":
@@ -93,68 +93,73 @@ class AudioRateController:
_, opus_packet = item
- # 循环等待直到时间到达
+ # Loop wait until time is up
while True:
- # 计算时间差
+ # Calculate time difference
elapsed_ms = self._get_elapsed_ms()
output_ms = self.play_position
if elapsed_ms < output_ms:
- # 还不到发送时间,计算等待时长
+ # Not time to send yet, calculate wait duration
wait_ms = output_ms - elapsed_ms
- # 等待后继续检查(允许被中断)
+ # Continue check after wait (allow interruption)
try:
await asyncio.sleep(wait_ms / 1000)
except asyncio.CancelledError:
- self.logger.bind(tag=TAG).debug("音频发送任务被取消")
+ self.logger.bind(tag=TAG).debug("Audio sending task cancelled")
raise
- # 等待结束后重新检查时间(循环回到 while True)
+ # Re-check time after wait (loop back to while True)
else:
- # 时间已到,跳出等待循环
+ # Time is up, break wait loop
break
- # 时间已到,从队列移除并发送
+ # Time is up, remove from queue and send
self.queue.popleft()
self.play_position += self.frame_duration
try:
await send_audio_callback(opus_packet)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"发送音频失败: {e}")
- raise
+ self.logger.bind(tag=TAG).error(f"Failed to send audio: {e}")
+ # Do not re-raise to prevent killing the loop
+ # raise
- # 队列处理完后清除事件
+ # Clear events after processing queue
self.queue_empty_event.set()
self.queue_has_data_event.clear()
def start_sending(self, send_audio_callback):
"""
- 启动异步发送任务
+ Start asynchronous sending task
Args:
- send_audio_callback: 发送音频的回调函数
+ send_audio_callback: Audio sending callback function
Returns:
- asyncio.Task: 发送任务
+ asyncio.Task: Sending task
"""
async def _send_loop():
try:
while True:
- # 等待队列数据事件,不轮询等待占用CPU
+ # Wait for queue data event, do not poll to save CPU
await self.queue_has_data_event.wait()
await self.check_queue(send_audio_callback)
except asyncio.CancelledError:
- self.logger.bind(tag=TAG).debug("音频发送循环已停止")
+ self.logger.bind(tag=TAG).debug("Audio sending loop stopped")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"音频发送循环异常: {e}")
+ self.logger.bind(tag=TAG).error(f"Audio send loop exception: {e}")
+ finally:
+ # Ensure event is set so waiters don't hang
+ self.queue_empty_event.set()
+ self.logger.bind(tag=TAG).debug("Audio send loop exited, queue_empty_event set")
self.pending_send_task = asyncio.create_task(_send_loop())
return self.pending_send_task
def stop_sending(self):
- """停止发送任务"""
+ """Stop sending task"""
if self.pending_send_task and not self.pending_send_task.done():
self.pending_send_task.cancel()
- self.logger.bind(tag=TAG).debug("已取消音频发送任务")
+ self.logger.bind(tag=TAG).debug("Audio sending task cancelled")
diff --git a/main/xiaozhi-server/core/utils/cache/manager.py b/main/xiaozhi-server/core/utils/cache/manager.py
index c54f7817f..f2bfea4b4 100644
--- a/main/xiaozhi-server/core/utils/cache/manager.py
+++ b/main/xiaozhi-server/core/utils/cache/manager.py
@@ -1,5 +1,5 @@
"""
-全局缓存管理器
+Global Cache Manager
"""
import time
@@ -11,7 +11,7 @@ from .config import CacheConfig, CacheType
class GlobalCacheManager:
- """全局缓存管理器"""
+ """Global Cache Manager"""
def __init__(self):
self._logger = None
@@ -24,7 +24,7 @@ class GlobalCacheManager:
@property
def logger(self):
- """延迟初始化 logger 以避免循环导入"""
+ """Delay logger initialization to avoid circular import"""
if self._logger is None:
from config.logger import setup_logging
@@ -32,7 +32,7 @@ class GlobalCacheManager:
return self._logger
def _get_cache_name(self, cache_type: CacheType, namespace: str = "") -> str:
- """生成缓存名称"""
+ """Generate cache name"""
if namespace:
return f"{cache_type.value}:{namespace}"
return cache_type.value
@@ -40,7 +40,7 @@ class GlobalCacheManager:
def _get_or_create_cache(
self, cache_name: str, config: CacheConfig
) -> Dict[str, CacheEntry]:
- """获取或创建缓存空间"""
+ """Get or create cache space"""
with self._global_lock:
if cache_name not in self._caches:
self._caches[cache_name] = (
@@ -60,28 +60,28 @@ class GlobalCacheManager:
ttl: Optional[float] = None,
namespace: str = "",
) -> None:
- """设置缓存值"""
+ """Set cache value"""
cache_name = self._get_cache_name(cache_type, namespace)
config = self._configs.get(cache_name) or CacheConfig.for_type(cache_type)
cache = self._get_or_create_cache(cache_name, config)
- # 使用配置的TTL或传入的TTL
+ # Use configured TTL or passed TTL
effective_ttl = ttl if ttl is not None else config.ttl
with self._locks[cache_name]:
- # 创建缓存条目
+ # Create cache entry
entry = CacheEntry(value=value, timestamp=time.time(), ttl=effective_ttl)
# 处理不同策略
if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]:
- # LRU策略:如果已存在则移动到末尾
+ # LRU strategy: if exists, move to end
if key in cache:
del cache[key]
cache[key] = entry
- # 检查大小限制
+ # Check size limit
if config.max_size and len(cache) > config.max_size:
- # 移除最旧的条目
+ # Remove oldest entry
oldest_key = next(iter(cache))
del cache[oldest_key]
self._stats["evictions"] += 1
@@ -89,20 +89,20 @@ class GlobalCacheManager:
else:
cache[key] = entry
- # 检查大小限制
+ # Check size limit
if config.max_size and len(cache) > config.max_size:
- # 简单策略:随机移除一个条目
+ # Simple strategy: randomly remove one entry
victim_key = next(iter(cache))
del cache[victim_key]
self._stats["evictions"] += 1
- # 定期清理过期条目
+ # Periodically clean up expired entries
self._maybe_cleanup(cache_name)
def get(
self, cache_type: CacheType, key: str, namespace: str = ""
) -> Optional[Any]:
- """获取缓存值"""
+ """Get cache value"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@@ -119,16 +119,16 @@ class GlobalCacheManager:
entry = cache[key]
- # 检查过期
+ # Check expiration
if entry.is_expired():
del cache[key]
self._stats["misses"] += 1
return None
- # 更新访问信息
+ # Update access info
entry.touch()
- # LRU策略:移动到末尾
+ # LRU strategy: move to end
if config.strategy in [CacheStrategy.LRU, CacheStrategy.TTL_LRU]:
del cache[key]
cache[key] = entry
@@ -137,7 +137,7 @@ class GlobalCacheManager:
return entry.value
def delete(self, cache_type: CacheType, key: str, namespace: str = "") -> bool:
- """删除缓存条目"""
+ """Delete cache entry"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@@ -152,7 +152,7 @@ class GlobalCacheManager:
return False
def clear(self, cache_type: CacheType, namespace: str = "") -> None:
- """清空指定缓存"""
+ """Clear specified cache"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@@ -164,7 +164,7 @@ class GlobalCacheManager:
def invalidate_pattern(
self, cache_type: CacheType, pattern: str, namespace: str = ""
) -> int:
- """按模式失效缓存条目"""
+ """Invalidate cache entries by pattern"""
cache_name = self._get_cache_name(cache_type, namespace)
if cache_name not in self._caches:
@@ -182,7 +182,7 @@ class GlobalCacheManager:
return deleted_count
def _cleanup_expired(self, cache_name: str) -> int:
- """清理过期条目"""
+ """Clean up expired entries"""
if cache_name not in self._caches:
return 0
@@ -198,7 +198,7 @@ class GlobalCacheManager:
return deleted_count
def _maybe_cleanup(self, cache_name: str):
- """定期清理检查"""
+ """Periodic cleanup check"""
config = self._configs.get(cache_name)
if not config:
return
@@ -209,8 +209,8 @@ class GlobalCacheManager:
deleted = self._cleanup_expired(cache_name)
if deleted > 0:
self._stats["cleanups"] += 1
- self.logger.debug(f"清理缓存 {cache_name}: 删除 {deleted} 个过期条目")
+ self.logger.debug(f"Cleaning cache {cache_name}: deleted {deleted} expired entries")
-# 创建全局缓存管理器实例
+# Create global cache manager instance
cache_manager = GlobalCacheManager()
diff --git a/main/xiaozhi-server/core/utils/cgm_intent.py b/main/xiaozhi-server/core/utils/cgm_intent.py
new file mode 100644
index 000000000..9102d3c0f
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/cgm_intent.py
@@ -0,0 +1,350 @@
+"""
+Context Intent Classifier
+
+Uses the fast intent LLM to determine:
+1. Which context (CGM, Pump, News) should be injected
+2. If a query can be answered directly (time, weather, location, volume, brightness, battery)
+3. Whether a diabetes question needs CGM context, pump context, or both
+
+This is a purely LLM-driven classifier for multilingual support.
+"""
+import json
+import hashlib
+import time
+import os
+import re
+from datetime import datetime
+from zoneinfo import ZoneInfo
+from config.logger import setup_logging
+from core.utils import llm as llm_utils
+
+TAG = __name__
+logger = setup_logging()
+
+# Global singleton for the classifier
+_classifier = None
+
+
+class ContextIntentClassifier:
+ """Fast classifier to determine context needs and control signals."""
+
+ SYSTEM_PROMPT = """You are a speed-optimized Intent Classifier. Output ONLY JSON.
+CRITICAL: Use the user's language for 'reply' and 'search_query'.
+IMPORTANT: Put "fast_answer" FIRST in the JSON.
+
+Schema:
+{"fast_answer": "time"|"weather"|"location"|"exit"|"volume"|"brightness"|"battery"|null, "language": "English"|"Chinese", "needs_cgm": bool, "needs_pump": bool, "needs_news": bool, "needs_search": bool, "search_query": string|null, "reply": string}
+
+Behavior Rules:
+1. 'weather' -> If user asks for current weather, set "fast_answer": "weather" (internal plugin).
+2. 'battery' -> If user asks for battery or power, set "fast_answer": "battery".
+3. 'volume' -> If user asks about volume level, set "fast_answer": "volume".
+4. 'time' -> If user asks the current time, set "fast_answer": "time".
+5. 'location' -> If user asks where they are or current location, set "fast_answer": "location".
+6. 'search_query' -> MUST be in the user's language.
+7. NO SEARCH for Chat -> Greetings ("how are you", "hello"), compliments ("you are great"), or philosophical questions must NOT trigger 'needs_search'. Leave search_query null and needs_search false.
+8. NO REDUNDANT SEARCH -> If information (news, headlines, weather) is already present in the history or current context, set 'needs_search' to false. Only search if the information is missing or outdated.
+9. NO SEARCH for Meta-Chat -> Questions about your own features, hardware capabilities, previous turns ("why didn't you answer"), or your "internal state" must NOT trigger 'needs_search'.
+10. 'needs_cgm' -> Set true when the user asks about glucose, blood sugar, readings, trends, highs, lows, time in range, glycemic control, patterns, current glucose, or diabetes status inferred from CGM.
+11. 'needs_pump' -> Set true when the user asks about insulin, bolus, basal, temp basal, carb ratio, correction, pump activity, pump profile, insulin effectiveness, or pump-delivered events.
+12. Set BOTH 'needs_cgm' and 'needs_pump' to true when the question requires joint reasoning, such as insulin response, whether a bolus worked, post-meal control, correction effectiveness, or overall diabetes management using both glucose and pump data.
+13. 'needs_news' -> Set true only for explicit news/headlines/current events requests.
+14. For ordinary diabetes coaching or status questions, do NOT set 'needs_search' unless the user is explicitly asking for external knowledge, public information, or recent news.
+15. 'reply' -> A short natural response in the user's language.
+
+Examples:
+- "how's the weather" -> {"fast_answer": "weather", "language": "English", "needs_cgm": false, "needs_pump": false, "needs_news": false, "needs_search": false, "search_query": null, "reply": "Checking the weather for you."}
+- "how are you" -> {"fast_answer": null, "language": "English", "needs_cgm": false, "needs_pump": false, "needs_news": false, "needs_search": false, "search_query": null, "reply": "I'm doing great, thanks for asking!"}
+- "who is Steve Jobs" -> {"fast_answer": null, "language": "English", "needs_cgm": false, "needs_pump": false, "needs_news": false, "needs_search": true, "search_query": "who is Steve Jobs", "reply": "Searching for Steve Jobs..."}
+- "current volume" -> {"fast_answer": "volume", "language": "English", "needs_cgm": false, "needs_pump": false, "needs_news": false, "needs_search": false, "search_query": null, "reply": "Checking the current volume level..."}
+- "How is my glucose today?" -> {"fast_answer": null, "language": "English", "needs_cgm": true, "needs_pump": false, "needs_news": false, "needs_search": false, "search_query": null, "reply": "Let me check your recent glucose data."}
+- "Did my last bolus work?" -> {"fast_answer": null, "language": "English", "needs_cgm": true, "needs_pump": true, "needs_news": false, "needs_search": false, "search_query": null, "reply": "Let me check your recent insulin and glucose response."}
+- "最近胰岛素有没有起作用" -> {"fast_answer": null, "language": "Chinese", "needs_cgm": true, "needs_pump": true, "needs_news": false, "needs_search": false, "search_query": null, "reply": "我来看看你最近的胰岛素和血糖反应。"}
+- "最近血糖控制怎么样" -> {"fast_answer": null, "language": "Chinese", "needs_cgm": true, "needs_pump": false, "needs_news": false, "needs_search": false, "search_query": null, "reply": "我来看看你最近的血糖情况。"}
+- "最近pump有没有异常" -> {"fast_answer": null, "language": "English", "needs_cgm": false, "needs_pump": true, "needs_news": false, "needs_search": false, "search_query": null, "reply": "Let me check your recent pump activity."}
+"""
+
+ def __init__(self, config):
+ self.config = config
+ self.llm = None
+ self._init_llm()
+
+ # Cache for intent results
+ from core.utils.cache.manager import cache_manager, CacheType
+ self.cache_manager = cache_manager
+ self.CacheType = CacheType
+
+ def _init_llm(self):
+ """Initialize the fast intent LLM."""
+ try:
+ llm_config = self.config.get("LLM", {})
+ if "fast_intent" in llm_config:
+ fast_config = llm_config["fast_intent"]
+ llm_type = fast_config.get("type", "openai")
+ self.llm = llm_utils.create_instance(llm_type, fast_config)
+ else:
+ main_llm_name = self.config.get("selected_module", {}).get("LLM", "openai")
+ if main_llm_name in llm_config:
+ main_config = llm_config[main_llm_name]
+ llm_type = main_config.get("type", "openai")
+ self.llm = llm_utils.create_instance(llm_type, main_config)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to initialize context classifier LLM: {e}")
+ self.llm = None
+
+ def classify(self, query: str, client_id: str, language_hint: str = None) -> dict:
+ """Classify what context is needed and if fast answer is available."""
+ if not self.llm:
+ return {
+ "language": "English",
+ "needs_cgm": False,
+ "needs_pump": False,
+ "needs_news": False,
+ "needs_search": False,
+ "search_query": None,
+ "fast_answer": None,
+ "reply": None,
+ }
+
+ start_time = time.time()
+
+ # 1. Check cache
+ cache_key = hashlib.md5(f"intent:{client_id}:{query}:{language_hint}".encode()).hexdigest()
+ cached = self.cache_manager.get(self.CacheType.INTENT, cache_key)
+ if cached is not None:
+ try:
+ return json.loads(cached)
+ except:
+ pass
+
+ try:
+ user_prompt = f"User: {query}"
+ # Format the system prompt with the language hint for stronger anchoring
+ lang_instruction = f"Strictly generate 'search_query' and 'reply' in the language matching the hint: {language_hint}" if language_hint else "Generate 'search_query' and 'reply' in the same language as the user's query."
+
+ # Increased timeout to 10s for stronger multilingual stability
+ response = self.llm.response_no_stream(
+ system_prompt=f"{self.SYSTEM_PROMPT}\n{lang_instruction}",
+ user_prompt=user_prompt,
+ response_format={"type": "json_object"},
+ timeout=10,
+ max_retries=0
+ )
+
+ response_text = response.strip()
+
+ # 1. Pre-process: Extract JSON structure if it's wrapped in text
+ json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
+ if json_match:
+ response_text = json_match.group(0)
+
+ # JSON Salvage: If we get an unterminated or slightly malformed response
+ result = {}
+ try:
+ result = json.loads(response_text)
+ except json.JSONDecodeError:
+ # Attempt to repair simple missing closures
+ repaired = response_text
+ if not repaired.endswith("}"):
+ if repaired.count('"') % 2 != 0: repaired += '"'
+ repaired += ' }'
+ try:
+ result = json.loads(repaired)
+ logger.bind(tag=TAG).debug(f"Salvaged partial JSON response: {repaired}")
+ except:
+ # Robust Regex Extraction for key fields
+ logger.bind(tag=TAG).debug(f"JSON parsing failed, using regex extraction on: {response_text}")
+
+ # Look for needs_search
+ match_search = re.search(r'"needs_search":\s*(true|false)', response_text)
+ if match_search: result["needs_search"] = match_search.group(1) == "true"
+
+ # Look for fast_answer type
+ match_fast = re.search(r'"fast_answer":\s*"([^"]+)"', response_text)
+ if match_fast: result["fast_answer"] = match_fast.group(1)
+
+ # Look for search_query strings
+ match_query = re.search(r'"search_query":\s*"([^"]+)"', response_text)
+ if match_query: result["search_query"] = match_query.group(1)
+
+ # Look for reply strings
+ match_reply = re.search(r'"reply":\s*"([^"]+)"', response_text)
+ if match_reply: result["reply"] = match_reply.group(1)
+
+ if not result:
+ raise # Rethrow if even regex fails
+
+ # Normalize result with safe defaults
+ result = {
+ "language": str(result.get("language", "English")),
+ "needs_cgm": bool(result.get("needs_cgm", False)),
+ "needs_pump": bool(result.get("needs_pump", False)),
+ "needs_news": bool(result.get("needs_news", False)),
+ "needs_search": bool(result.get("needs_search", False)),
+ "search_query": result.get("search_query"),
+ "fast_answer": result.get("fast_answer"),
+ "reply": result.get("reply")
+ }
+
+ self.cache_manager.set(self.CacheType.INTENT, cache_key, json.dumps(result))
+
+ elapsed = time.time() - start_time
+ logger.bind(tag=TAG).info(f"Intent classified in {elapsed:.2f}s: {result['fast_answer'] or 'chat'}")
+ return result
+
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"Intent LLM failed: {e}")
+
+ # Rule-based fallback
+ query_lower = query.lower()
+ needs_pump = any(kw in query_lower for kw in ["pump", "insulin", "bolus", "basal", "泵", "胰岛素"])
+ needs_cgm = any(kw in query_lower for kw in ["glucose", "sugar", "cgm", "high", "low", "血糖"])
+
+ fast_answer = None
+ if needs_pump:
+ fast_answer = "pump"
+ elif needs_cgm:
+ fast_answer = "cgm"
+
+ return {
+ "language": "English" if "a" <= query_lower[0] <= "z" else "Chinese",
+ "needs_cgm": needs_cgm,
+ "needs_pump": needs_pump,
+ "needs_news": False,
+ "needs_search": False,
+ "search_query": None,
+ "fast_answer": fast_answer,
+ "reply": None,
+ }
+
+ def get_fast_answer(self, answer_type: str, client_id: str = "", battery_level: str = None) -> str:
+ """Generate a fast answer for time/weather/location/battery."""
+ if answer_type == "time":
+ return self._get_time_answer()
+ elif answer_type == "weather":
+ return self._get_weather_answer(client_id)
+ elif answer_type == "location":
+ return self._get_location_answer(client_id)
+ elif answer_type == "battery":
+ if battery_level and battery_level != "unknown":
+ return f"The current battery level is {battery_level}%."
+ return "I couldn't retrieve the battery level from the device."
+ elif answer_type == "volume":
+ # For volume, we assume the level is passed or fetched via same lazy sync pattern
+ # If battery_level is reused for 'hardware_stat' generically or we pass volume specifically
+ # For simplicity, we'll implement _get_volume_answer separately in connection.py
+ # or handle it here if we pass it.
+ if battery_level and battery_level != "unknown":
+ return f"The current volume level is {battery_level}%."
+ return "I couldn't retrieve the volume level from the device."
+ elif answer_type == "pump":
+ return self._get_pump_answer(client_id)
+ elif answer_type == "cgm":
+ return self._get_cgm_answer(client_id)
+ return None
+
+ def _get_time_answer(self) -> str:
+ try:
+ tz_offset = self.config.get("server", {}).get("timezone_offset", 0)
+ if tz_offset == -5: tz = ZoneInfo("America/New_York")
+ elif tz_offset == -8: tz = ZoneInfo("America/Los_Angeles")
+ else:
+ from datetime import timezone, timedelta
+ tz = timezone(timedelta(hours=tz_offset))
+
+ now = datetime.now(tz)
+ time_str = now.strftime("%I:%M %p").lstrip("0")
+ day = now.strftime("%A, %B %d")
+ return f"It's {time_str} on {day}."
+ except:
+ return f"It's {datetime.now().strftime('%I:%M %p')}."
+
+ def _get_weather_answer(self, client_id: str) -> str:
+ try:
+ from plugins_func.functions.get_weather import get_weather
+ location = self.config.get("plugins", {}).get("get_weather", {}).get("default_location", "")
+ if not location: return "I don't have your location set."
+
+ import asyncio
+ class MockConn:
+ def __init__(self, config): self.config = config
+
+ mock = MockConn(self.config)
+ # get_weather is synchronous in reality
+ result = get_weather(mock, location=location)
+ if result and hasattr(result, "result"):
+ return result.result
+ return f"I couldn't get the weather for {location}."
+ except:
+ return "Weather service is currently unavailable."
+
+ def _get_location_answer(self, client_id: str) -> str:
+ try:
+ config_path = os.path.join("data", client_id, "config.json")
+ if os.path.exists(config_path):
+ with open(config_path, "r") as f:
+ location = json.load(f).get("location")
+ if location: return f"We're in {location}."
+ return "Location not set in your config."
+ except:
+ return "Unable to determine your location."
+
+ def _get_pump_answer(self, client_id: str) -> str:
+ try:
+ from core.utils.pump_manager import PumpManager
+ manager = PumpManager(data_root="data")
+ status = manager.get_realtime_status(client_id)
+ if status:
+ return status
+ return "I couldn't retrieve recent pump events."
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to get fast pump answer: {e}")
+ return "Pump data is temporarily unavailable."
+
+ def _get_cgm_answer(self, client_id: str) -> str:
+ try:
+ from core.utils.cgm_manager import CGMManager
+ manager = CGMManager(data_root="data")
+ status = manager.get_realtime_status(client_id)
+ if status:
+ return status
+ return "I couldn't retrieve recent CGM data."
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to get CGM fast answer: {e}")
+ return "CGM data is temporarily unavailable."
+
+
+def get_classifier(config):
+ global _classifier
+ if _classifier is None:
+ _classifier = ContextIntentClassifier(config)
+ return _classifier
+
+def classify_context_needs(query: str, client_id: str, config: dict, language_hint: str = None) -> dict:
+ classifier = get_classifier(config)
+ if not classifier:
+ return {
+ "language": "English",
+ "needs_cgm": False,
+ "needs_pump": False,
+ "needs_news": False,
+ "needs_search": False,
+ "search_query": None,
+ "fast_answer": None,
+ "reply": None,
+ }
+ return classifier.classify(query, client_id, language_hint=language_hint)
+
+def get_fast_answer(answer_type: str, client_id: str, config: dict, battery_level: str = None) -> str:
+ classifier = get_classifier(config)
+ return classifier.get_fast_answer(answer_type, client_id, battery_level=battery_level)
+
+
+def needs_cgm_context(query: str, client_id: str, config: dict) -> bool:
+ result = classify_context_needs(query, client_id, config)
+ return result.get("needs_cgm", False)
+
+
+def needs_pump_context(query: str, client_id: str, config: dict) -> bool:
+ result = classify_context_needs(query, client_id, config)
+ return result.get("needs_pump", False)
diff --git a/main/xiaozhi-server/core/utils/cgm_manager.py b/main/xiaozhi-server/core/utils/cgm_manager.py
new file mode 100644
index 000000000..835bf9721
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/cgm_manager.py
@@ -0,0 +1,365 @@
+import os
+import csv
+import json
+import time
+import asyncio
+import logging
+import requests
+import datetime
+from zoneinfo import ZoneInfo
+from typing import List, Dict, Any, Optional
+
+from config.settings import load_config
+from config.logger import setup_logging
+
+TAG = "cgm_manager"
+logger = setup_logging()
+
+class CGMManager:
+ def __init__(self, config=None):
+ self.config = config or load_config()
+
+ def _get_client_config(self, client_id: str) -> Optional[Dict]:
+ """Load client specific config for secrets and TZ"""
+ config_path = os.path.join("data", client_id, "config.json")
+ if not os.path.exists(config_path):
+ return None
+ try:
+ with open(config_path, "r") as f:
+ return json.load(f).get("cgm", {})
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to load config for {client_id}: {e}")
+ return None
+
+ def fetch_and_update(self, client_id: str):
+ """Fetch new data and append to CSV"""
+ cgm_config = self._get_client_config(client_id)
+ if not cgm_config or "api_secret" not in cgm_config:
+ # Client has not configured CGM
+ return
+
+ base_url = cgm_config.get("base_url")
+ if not base_url:
+ return
+
+ api_secret = cgm_config["api_secret"]
+ user_tz_str = cgm_config.get("user_tz", "US/Eastern")
+
+ csv_path = os.path.join("data", client_id, "cgm.csv")
+
+ # Determine start time
+ start_ms = 0
+ if os.path.exists(csv_path):
+ try:
+ with open(csv_path, "r") as f:
+ # Read last line to get last timestamp
+ # Using light-weight seek for large files could be better, but simple for now
+ lines = f.readlines()
+ if len(lines) > 1:
+ last_row = lines[-1].strip().split(',')
+ # Assuming unix_s column exists. Let's find its index from header
+ headers = lines[0].strip().split(',')
+ if "unix_s" in headers:
+ idx = headers.index("unix_s")
+ # +1000ms to avoid duplicate
+ start_ms = int(last_row[idx]) * 1000 + 1000
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"Error reading last time for {client_id}: {e}")
+
+ # If start_ms is 0 (new file), maybe default to 24h ago?
+ # User prompt example used explicit dates.
+ # Let's default to 24h ago if empty to fetch recent history.
+ if start_ms == 0:
+ start_ms = int((datetime.datetime.now() - datetime.timedelta(days=1)).timestamp() * 1000)
+
+ end_ms = int(datetime.datetime.now().timestamp() * 1000)
+
+ # Determine string formats for API if needed differently?
+ # User code used `find[date][$gte]` with MS.
+
+ params = {
+ "count": 1000,
+ "find[date][$gte]": start_ms,
+ "find[date][$lt]": end_ms,
+ "sort$": "date"
+ }
+
+ try:
+ r = requests.get(
+ f"{base_url.rstrip('/')}/api/v1/entries.json",
+ params=params,
+ headers={"api-secret": api_secret},
+ timeout=20
+ )
+ r.raise_for_status()
+ entries = r.json()
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Fetch failed for {client_id}: {e}")
+ return
+
+ if not entries:
+ return
+
+ # Process entries
+ tz = ZoneInfo(user_tz_str)
+ processed_data = []
+ for e in entries:
+ if not e.get("sgv"):
+ continue
+
+ # Helper for localized time string
+ dt = datetime.datetime.fromtimestamp(e["date"]/1000, tz=datetime.timezone.utc).astimezone(tz)
+
+ processed_data.append({
+ "time": dt.strftime("%Y-%m-%d %H:%M:%S"),
+ "sgv": e.get("sgv"),
+ "direction": e.get("direction"),
+ "unix_s": int(e["date"] / 1000),
+ "hour": dt.hour, # For analysis
+ "weekday": dt.weekday() # For analysis (0=Mon)
+ })
+
+ # Ensure data is sorted oldest -> newest before appending
+ processed_data.sort(key=lambda x: x["unix_s"])
+
+ self._append_to_csv(processed_data, csv_path)
+ logger.bind(tag=TAG).info(f"Fetched {len(processed_data)} new CGM entries for {client_id}")
+
+ def _append_to_csv(self, data: List[Dict], filename: str):
+ if not data:
+ return
+
+ file_exists = os.path.isfile(filename)
+ with open(filename, 'a', newline='') as f:
+ writer = csv.DictWriter(f, fieldnames=data[0].keys())
+ if not file_exists:
+ writer.writeheader()
+ writer.writerows(data)
+
+ def get_latest_reading(self, client_id: str) -> Optional[Dict[str, Any]]:
+ """Return the most recent CGM reading as a dict with 'glucose' and 'direction'."""
+ csv_path = os.path.join("data", client_id, "cgm.csv")
+ if not os.path.exists(csv_path):
+ return None
+
+ try:
+ with open(csv_path, "r") as f:
+ header_line = f.readline()
+ if not header_line:
+ return None
+ header = header_line.strip().split(",")
+
+ # Seek to end to read last lines
+ f.seek(0, os.SEEK_END)
+ file_size = f.tell()
+ seek_pos = max(0, file_size - 1024)
+ f.seek(seek_pos)
+
+ content = f.read()
+ lines = content.splitlines()
+
+ if seek_pos > 0 and len(lines) > 0:
+ lines.pop(0)
+
+ if not lines:
+ return None
+
+ last_row_str = lines[-1]
+ parts = last_row_str.split(",")
+
+ if len(parts) != len(header) and len(lines) > 1:
+ last_row_str = lines[-2]
+ parts = last_row_str.split(",")
+
+ if len(parts) != len(header):
+ return None
+
+ last = dict(zip(header, parts))
+ return {
+ "glucose": int(last.get("sgv", 0)),
+ "direction": last.get("direction", "Unknown"),
+ "unix_s": int(last.get("unix_s", 0))
+ }
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to get latest reading: {e}")
+ return None
+
+ def get_realtime_status(self, client_id: str) -> str:
+ """Return a short string summary of current state"""
+ csv_path = os.path.join("data", client_id, "cgm.csv")
+ if not os.path.exists(csv_path):
+ return ""
+
+ try:
+ with open(csv_path, "r") as f:
+ # Read header
+ header_line = f.readline()
+ if not header_line: return ""
+ header = header_line.strip().split(",")
+
+ # Seek to end to read last lines
+ f.seek(0, os.SEEK_END)
+ file_size = f.tell()
+
+ # Read last 1024 bytes (enough for several rows)
+ seek_pos = max(0, file_size - 1024)
+ f.seek(seek_pos)
+
+ content = f.read()
+ lines = content.splitlines()
+
+ # If we started in middle of a line, discard first
+ if seek_pos > 0 and len(lines) > 0:
+ lines.pop(0)
+
+ if not lines: return ""
+
+ # Get last valid row
+ last_row_str = lines[-1]
+ parts = last_row_str.split(",")
+
+ # Basic validation
+ if len(parts) != len(header):
+ # fallback to previous line if last is incomplete
+ if len(lines) > 1:
+ last_row_str = lines[-2]
+ parts = last_row_str.split(",")
+
+ if len(parts) != len(header): return ""
+
+ last = dict(zip(header, parts))
+ # Time delta
+ last_ts = int(last["unix_s"])
+ now_ts = int(time.time())
+ diff_min = (now_ts - last_ts) // 60
+
+ return f"Current Glucose: {last['sgv']} mg/dL ({last.get('direction', 'Unknown')}), {diff_min} mins ago."
+ except Exception as e:
+ return ""
+
+ def _read_all_rows(self, client_id: str) -> List[Dict[str, Any]]:
+ csv_path = os.path.join("data", client_id, "cgm.csv")
+ if not os.path.exists(csv_path):
+ return []
+
+ try:
+ with open(csv_path, "r") as f:
+ return list(csv.DictReader(f))
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to read CGM rows: {e}")
+ return []
+
+
+ def analyze_daily_trends(self, client_id: str, days=14) -> List[str]:
+ """Analyze last N days for hourly patterns"""
+ # Load data (should optimize to not load all)
+ csv_path = os.path.join("data", client_id, "cgm.csv")
+ if not os.path.exists(csv_path): return []
+
+ try:
+ with open(csv_path, "r") as f:
+ reader = csv.DictReader(f)
+ rows = list(reader)
+
+ if not rows: return []
+
+ # Filter last N days
+ cutoff_ts = int(time.time()) - (days * 86400)
+ recent_rows = [r for r in rows if int(r["unix_s"]) >= cutoff_ts]
+
+ if not recent_rows: return []
+
+ # Bin by hour
+ hourly_sum = {h: [] for h in range(24)}
+ for r in recent_rows:
+ h = int(r["hour"])
+ hourly_sum[h].append(int(r["sgv"]))
+
+ trends = []
+ # Find Highs (>180) Hotspots
+ high_hours = []
+ for h in range(24):
+ vals = hourly_sum[h]
+ if vals:
+ avg = sum(vals) / len(vals)
+ if avg > 160: # Threshold for "High Pattern"
+ high_hours.append(h)
+
+ if high_hours:
+ # Group consecutive
+ # Simplified representation
+ trends.append(f"Daily Pattern: Tendency to be high around {high_hours} hours.")
+
+ return trends
+ except Exception:
+ return []
+
+ def analyze_weekly_trends(self, client_id: str, weeks=4) -> List[str]:
+ # Similar logic for weekday (0-6)
+ return []
+
+ def analyze_long_term_control(self, client_id: str, days: int = 14) -> List[str]:
+ rows = self._read_all_rows(client_id)
+ if not rows:
+ return []
+
+ cutoff_ts = int(time.time()) - days * 86400
+ recent = [
+ r for r in rows
+ if r.get("unix_s") and int(r["unix_s"]) >= cutoff_ts
+ ]
+
+ values = [float(r["sgv"]) for r in recent if r.get("sgv")]
+ if not values:
+ return []
+
+ total = len(values)
+ mean_glucose = sum(values) / total
+
+ tir = sum(70 <= v <= 180 for v in values) / total * 100
+ tar = sum(v > 180 for v in values) / total * 100
+ tbr = sum(v < 70 for v in values) / total * 100
+
+ gmi = 3.31 + 0.02392 * mean_glucose
+
+ return [
+ f"TIR {tir:.1f}%, TAR {tar:.1f}%, TBR {tbr:.1f}%",
+ f"Mean glucose {mean_glucose:.1f} mg/dL, GMI {gmi:.2f}%"
+ ]
+
+ def get_context_summary(self, client_id: str) -> str:
+ """Full context block for LLM"""
+ status = self.get_realtime_status(client_id)
+ if not status: return ""
+
+ daily = self.analyze_daily_trends(client_id)
+ daily_str = " ".join(daily)
+
+ long_term = self.analyze_long_term_control(client_id)
+ daily_str += " " + " ".join(long_term)
+
+ return f"[CGM Data]\n{status}\n{daily_str}"
+
+
+
+async def cgm_background_task():
+ """Periodic update task"""
+ logger.bind(tag=TAG).info("CGM Scraper task started.")
+ manager = CGMManager()
+
+ while True:
+ try:
+ # Iterate active clients (directories in data/)
+ data_dir = "data"
+ if os.path.exists(data_dir):
+ for client_id in os.listdir(data_dir):
+ if os.path.isdir(os.path.join(data_dir, client_id)):
+ # Check if config has cgm
+ if manager._get_client_config(client_id):
+ manager.fetch_and_update(client_id)
+
+ # Wait 15 minutes
+ await asyncio.sleep(900)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Task error: {e}")
+ await asyncio.sleep(60)
diff --git a/main/xiaozhi-server/core/utils/current_time.py b/main/xiaozhi-server/core/utils/current_time.py
index 714dd50fd..f47ba597e 100644
--- a/main/xiaozhi-server/core/utils/current_time.py
+++ b/main/xiaozhi-server/core/utils/current_time.py
@@ -1,64 +1,55 @@
"""
-时间工具模块
-提供统一的时间获取功能
+Time Utility Module
+Provides unified time retrieval functionality
"""
import cnlunar
from datetime import datetime
-WEEKDAY_MAP = {
- "Monday": "星期一",
- "Tuesday": "星期二",
- "Wednesday": "星期三",
- "Thursday": "星期四",
- "Friday": "星期五",
- "Saturday": "星期六",
- "Sunday": "星期日",
-}
def get_current_time() -> str:
"""
- 获取当前时间字符串 (格式: HH:MM)
+ Get current time string (format: HH:MM)
"""
return datetime.now().strftime("%H:%M")
def get_current_date() -> str:
"""
- 获取今天日期字符串 (格式: YYYY-MM-DD)
+ Get today's date string (format: YYYY-MM-DD)
"""
return datetime.now().strftime("%Y-%m-%d")
def get_current_weekday() -> str:
"""
- 获取今天星期几
+ Get today's weekday
"""
now = datetime.now()
- return WEEKDAY_MAP[now.strftime("%A")]
+ return now.strftime("%A")
def get_current_lunar_date() -> str:
"""
- 获取农历日期字符串
+ Get lunar date string
"""
try:
now = datetime.now()
today_lunar = cnlunar.Lunar(now, godType="8char")
- return "%s年%s%s" % (
+ return "%s Year %s%s" % (
today_lunar.lunarYearCn,
today_lunar.lunarMonthCn[:-1],
today_lunar.lunarDayCn,
)
except Exception:
- return "农历获取失败"
+ return "Failed to get lunar date"
def get_current_time_info() -> tuple:
"""
- 获取当前时间信息
- 返回: (当前时间字符串, 今天日期, 今天星期, 农历日期)
+ Get current time information
+ Returns: (current time string, today date, today weekday, lunar date)
"""
current_time = get_current_time()
today_date = get_current_date()
diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py
index f135d930b..bdc53f7b1 100644
--- a/main/xiaozhi-server/core/utils/dialogue.py
+++ b/main/xiaozhi-server/core/utils/dialogue.py
@@ -23,7 +23,7 @@ class Message:
class Dialogue:
def __init__(self):
self.dialogue: List[Message] = []
- # 获取当前时间
+ # Get current time
self.current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def put(self, message: Message):
@@ -46,39 +46,45 @@ class Dialogue:
dialogue.append({"role": m.role, "content": m.content})
def get_llm_dialogue(self) -> List[Dict[str, str]]:
- # 直接调用get_llm_dialogue_with_memory,传入None作为memory_str
- # 这样确保说话人功能在所有调用路径下都生效
+ # Directly call get_llm_dialogue_with_memory, passing None as memory_str
+ # This ensures speaker function works in all call paths
return self.get_llm_dialogue_with_memory(None, None)
def update_system_message(self, new_content: str):
- """更新或添加系统消息"""
- # 查找第一个系统消息
- system_msg = next((msg for msg in self.dialogue if msg.role == "system"), None)
- if system_msg:
- system_msg.content = new_content
+ """Update or add system message (ensure only one exists)"""
+ # Find all system messages
+ system_indices = [i for i, msg in enumerate(self.dialogue) if msg.role == "system"]
+
+ if system_indices:
+ # Update the first one
+ self.dialogue[system_indices[0]].content = new_content
+ # Remove any others (duplicate cleanup)
+ for i in reversed(system_indices[1:]):
+ self.dialogue.pop(i)
else:
- self.put(Message(role="system", content=new_content))
+ # Insert at the beginning
+ self.dialogue.insert(0, Message(role="system", content=new_content))
def get_llm_dialogue_with_memory(
self, memory_str: str = None, voiceprint_config: dict = None
) -> List[Dict[str, str]]:
- # 构建对话
+ # Build dialogue
dialogue = []
- # 添加系统提示和记忆
+ # Add system prompt and memory
system_message = next(
(msg for msg in self.dialogue if msg.role == "system"), None
)
if system_message:
- # 基础系统提示
+ # Basic system prompt
enhanced_system_prompt = system_message.content
- # 替换时间占位符
+ # Replace time placeholder
enhanced_system_prompt = enhanced_system_prompt.replace(
"{{current_time}}", datetime.now().strftime("%H:%M")
)
- # 添加说话人个性化描述
+ # Add speaker personalized description
try:
speakers = voiceprint_config.get("speakers", [])
if speakers:
@@ -88,7 +94,7 @@ class Dialogue:
parts = speaker_str.split(",", 2)
if len(parts) >= 2:
name = parts[1].strip()
- # 如果描述为空,则为""
+ # If description is empty, set to ""
description = (
parts[2].strip() if len(parts) >= 3 else ""
)
@@ -97,22 +103,44 @@ class Dialogue:
pass
enhanced_system_prompt += "\n\n"
except:
- # 配置读取失败时忽略错误,不影响其他功能
+ # Ignore error if config read fails, does not affect other functions
pass
- # 使用正则表达式匹配 标签,不管中间有什么内容
+ # Use regex to match tag, regardless of content
if memory_str is not None:
- enhanced_system_prompt = re.sub(
- r".*? ",
- f"\n{memory_str}\n ",
- enhanced_system_prompt,
- flags=re.DOTALL,
- )
+ if "" in enhanced_system_prompt:
+ enhanced_system_prompt = re.sub(
+ r".*? ",
+ f"\n{memory_str}\n ",
+ enhanced_system_prompt,
+ flags=re.DOTALL,
+ )
+ else:
+ enhanced_system_prompt += f"\n\n\n{memory_str}\n "
+
+ # FINAL SANITY CHECK: Ensure we don't have nested identity if it somehow happened
+ if enhanced_system_prompt.count("") > 1:
+ # If nested, try to extract the innermost content or at least flatten
+ # This is a fallback defensive measure
+ inner_match = re.search(r"(?:(?!).)*? ", enhanced_system_prompt, re.DOTALL)
+ if inner_match:
+ # Keep the whole thing but maybe this is where we should be careful.
+ # For now, let's just log it if we were in a logging context.
+ pass
+
dialogue.append({"role": "system", "content": enhanced_system_prompt})
- # 添加用户和助手的对话
- for m in self.dialogue:
- if m.role != "system": # 跳过原始的系统消息
- self.getMessages(m, dialogue)
+ # Add user and assistant dialogue
+ # Limit to the last N turns to avoid context overflow and reduce latency
+ MAX_HISTORY = 20
+
+ # Filter out system messages first (we already added the system prompt above)
+ conversation_history = [m for m in self.dialogue if m.role != "system"]
+
+ # Take the last MAX_HISTORY messages
+ recent_history = conversation_history[-MAX_HISTORY:] if len(conversation_history) > MAX_HISTORY else conversation_history
+
+ for m in recent_history:
+ self.getMessages(m, dialogue)
return dialogue
diff --git a/main/xiaozhi-server/core/utils/exit_handler.py b/main/xiaozhi-server/core/utils/exit_handler.py
new file mode 100644
index 000000000..42077a0f0
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/exit_handler.py
@@ -0,0 +1,127 @@
+"""
+Centralized exit/goodbye detection and handling.
+
+Consolidates exit command matching and graceful shutdown logic
+that was previously duplicated across connection.py and intentHandler.py.
+
+Pre-caches TTS audio for exit replies so goodbye messages play instantly
+without waiting for TTS generation.
+"""
+import uuid
+import random
+import threading
+from core.providers.tts.dto.dto import ContentType, TTSMessageDTO, SentenceType
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+# Module-level cache: maps goodbye text -> list of opus packets
+_exit_audio_cache = {}
+_cache_lock = threading.Lock()
+_cache_initialized = False
+
+
+def is_exit_command(text: str, exit_commands: list) -> bool:
+ """
+ Check if text matches any configured exit command.
+
+ Args:
+ text: User input text (will be stripped of punctuation and lowercased)
+ exit_commands: List of exit command strings from config
+
+ Returns:
+ True if text matches an exit command
+ """
+ if not exit_commands or not text:
+ return False
+ clean = text.strip(" .,!?").lower()
+ return clean in exit_commands
+
+
+def pre_cache_exit_audio(tts_provider, exit_replies: list):
+ """
+ Pre-generate TTS audio for all exit replies in a background thread.
+ Call once after TTS provider is ready (e.g., after open_audio_channels).
+
+ Args:
+ tts_provider: The TTS provider instance (has to_tts method)
+ exit_replies: List of goodbye phrases to pre-generate
+ """
+ global _cache_initialized
+ if _cache_initialized or not exit_replies:
+ return
+
+ def _generate():
+ global _cache_initialized
+ for reply in exit_replies:
+ try:
+ result = tts_provider.to_tts(reply)
+ if result is not None:
+ # to_tts returns either a file path or a list of opus packets
+ if isinstance(result, list):
+ with _cache_lock:
+ _exit_audio_cache[reply] = result
+ else:
+ # It's a file path — convert to opus packets
+ from core.utils.util import audio_to_data
+ import asyncio
+ loop = asyncio.new_event_loop()
+ try:
+ packets = loop.run_until_complete(audio_to_data(result))
+ with _cache_lock:
+ _exit_audio_cache[reply] = packets
+ finally:
+ loop.close()
+ logger.bind(tag=TAG).debug(f"Pre-cached exit audio: '{reply}'")
+ else:
+ logger.bind(tag=TAG).warning(f"Failed to pre-cache exit audio: '{reply}'")
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"Error pre-caching exit audio for '{reply}': {e}")
+ _cache_initialized = True
+ logger.bind(tag=TAG).info(f"Exit audio cache ready: {len(_exit_audio_cache)}/{len(exit_replies)} phrases cached")
+
+ thread = threading.Thread(target=_generate, daemon=True)
+ thread.start()
+
+
+def handle_exit(conn, exit_replies: list = None):
+ """
+ Initiate a graceful exit with a random goodbye message.
+
+ If pre-cached audio is available, bypasses TTS generation entirely by
+ putting opus packets directly into the audio queue (~instant playback).
+ Otherwise falls back to the TTS text queue.
+
+ Args:
+ conn: ConnectionHandler instance
+ exit_replies: List of goodbye phrases. If None, reads from conn.config.
+ """
+ if exit_replies is None:
+ exit_replies = getattr(conn, "config", {}).get("exit_replies", [])
+
+ goodbye_text = random.choice(exit_replies) if exit_replies else "Goodbye!"
+
+ conn.close_after_chat = True
+ conn.sentence_id = str(uuid.uuid4().hex)
+
+ # Try to use pre-cached audio (bypasses TTS generation entirely)
+ with _cache_lock:
+ cached_audio = _exit_audio_cache.get(goodbye_text)
+
+ if cached_audio:
+ # Put audio directly into the audio queue — skips TTS generation
+ conn.tts.tts_audio_first_sentence = True
+ conn.tts.tts_audio_queue.put((SentenceType.LAST, cached_audio, goodbye_text))
+ logger.bind(tag=TAG).info(f"Exit initiated (cached): '{goodbye_text}'")
+ else:
+ # Fall back to normal TTS text queue
+ conn.tts.tts_text_queue.put(
+ TTSMessageDTO(
+ sentence_id=conn.sentence_id,
+ sentence_type=SentenceType.LAST,
+ content_type=ContentType.TEXT,
+ content_detail=goodbye_text,
+ )
+ )
+ logger.bind(tag=TAG).info(f"Exit initiated (TTS): '{goodbye_text}'")
diff --git a/main/xiaozhi-server/core/utils/gc_manager.py b/main/xiaozhi-server/core/utils/gc_manager.py
index e3b958fe4..382f2dd85 100644
--- a/main/xiaozhi-server/core/utils/gc_manager.py
+++ b/main/xiaozhi-server/core/utils/gc_manager.py
@@ -1,6 +1,6 @@
"""
-全局GC管理模块
-定期执行垃圾回收,避免频繁触发GC导致的GIL锁问题
+Global GC Management Module
+Periodically execute garbage collection to avoid GIL lock issues caused by frequent GC triggering
"""
import gc
@@ -13,14 +13,14 @@ logger = setup_logging()
class GlobalGCManager:
- """全局垃圾回收管理器"""
+ """Global Garbage Collection Manager"""
def __init__(self, interval_seconds=300):
"""
- 初始化GC管理器
+ Initialize GC Manager
Args:
- interval_seconds: GC执行间隔(秒),默认300秒(5分钟)
+ interval_seconds: GC execution interval (seconds), default 300 seconds (5 minutes)
"""
self.interval_seconds = interval_seconds
self._task = None
@@ -28,21 +28,21 @@ class GlobalGCManager:
self._lock = threading.Lock()
async def start(self):
- """启动定时GC任务"""
+ """Start scheduled GC task"""
if self._task is not None:
- logger.bind(tag=TAG).warning("GC管理器已经在运行")
+ logger.bind(tag=TAG).warning("GC manager is already running")
return
- logger.bind(tag=TAG).info(f"启动全局GC管理器,间隔{self.interval_seconds}秒")
+ logger.bind(tag=TAG).info(f"Starting global GC manager, interval {self.interval_seconds} seconds")
self._stop_event.clear()
self._task = asyncio.create_task(self._gc_loop())
async def stop(self):
- """停止定时GC任务"""
+ """Stop scheduled GC task"""
if self._task is None:
return
- logger.bind(tag=TAG).info("停止全局GC管理器")
+ logger.bind(tag=TAG).info("Stopping global GC manager")
self._stop_event.set()
if self._task and not self._task.done():
@@ -55,35 +55,35 @@ class GlobalGCManager:
self._task = None
async def _gc_loop(self):
- """GC循环任务"""
+ """GC Loop Task"""
try:
while not self._stop_event.is_set():
- # 等待指定间隔
+ # Wait for specified interval
try:
await asyncio.wait_for(
self._stop_event.wait(), timeout=self.interval_seconds
)
- # 如果stop_event被设置,退出循环
+ # If stop_event is set, exit loop
break
except asyncio.TimeoutError:
- # 超时表示到了执行GC的时间
+ # Timeout means it's time to execute GC
pass
- # 执行GC
+ # Execute GC
await self._run_gc()
except asyncio.CancelledError:
- logger.bind(tag=TAG).info("GC循环任务被取消")
+ logger.bind(tag=TAG).info("GC loop task cancelled")
raise
except Exception as e:
- logger.bind(tag=TAG).error(f"GC循环任务异常: {e}")
+ logger.bind(tag=TAG).error(f"GC loop task exception: {e}")
finally:
- logger.bind(tag=TAG).info("GC循环任务已退出")
+ logger.bind(tag=TAG).info("GC loop task exited")
async def _run_gc(self):
- """执行垃圾回收"""
+ """Execute garbage collection"""
try:
- # 在线程池中执行GC,避免阻塞事件循环
+ # Execute GC in thread pool to avoid blocking event loop
loop = asyncio.get_running_loop()
def do_gc():
@@ -95,26 +95,26 @@ class GlobalGCManager:
before, collected, after = await loop.run_in_executor(None, do_gc)
logger.bind(tag=TAG).debug(
- f"全局GC执行完成 - 回收对象: {collected}, "
- f"对象数量: {before} -> {after}"
+ f"Global GC completed - Collected: {collected}, "
+ f"Objects: {before} -> {after}"
)
except Exception as e:
- logger.bind(tag=TAG).error(f"执行GC时出错: {e}")
+ logger.bind(tag=TAG).error(f"Error executing GC: {e}")
-# 全局单例
+# Global Singleton
_gc_manager_instance = None
def get_gc_manager(interval_seconds=300):
"""
- 获取全局GC管理器实例(单例模式)
+ Get global GC manager instance (Singleton pattern)
Args:
- interval_seconds: GC执行间隔(秒),默认300秒(5分钟)
+ interval_seconds: GC execution interval (seconds), default 300 seconds (5 minutes)
Returns:
- GlobalGCManager实例
+ GlobalGCManager instance
"""
global _gc_manager_instance
if _gc_manager_instance is None:
diff --git a/main/xiaozhi-server/core/utils/history_rag.py b/main/xiaozhi-server/core/utils/history_rag.py
new file mode 100644
index 000000000..311d303a7
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/history_rag.py
@@ -0,0 +1,174 @@
+import os
+import json
+import re
+from typing import List, Dict, Optional
+from config.logger import setup_logging
+
+TAG = "history_rag"
+logger = setup_logging()
+
+class HistoryRAG:
+ _instance = None
+ _cache = {} # {client_id: {"mtime": float, "chunks": List[Dict]}}
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = super(HistoryRAG, cls).__new__(cls)
+ cls._instance.stopwords = {
+ "the", "a", "an", "and", "or", "but", "is", "are", "was", "were",
+ "in", "on", "at", "to", "for", "with", "by", "about", "of", "it",
+ "this", "that", "i", "you", "he", "she", "they", "we", "what",
+ "when", "where", "who", "why", "how",
+ "me", "my", "myself", "mine", "your", "yours", "yourself",
+ "him", "his", "her", "hers", "its", "our", "ours", "their", "theirs",
+ "do", "does", "did", "can", "could", "will", "would", "should",
+ "have", "has", "had", "be", "been", "being",
+ "s", "re", "m", "ll", "ve", "d", "t"
+ }
+ return cls._instance
+
+ def _load_history(self, client_id: str):
+ """Load and chunk memory.json for a specific client if changed"""
+ memory_path = os.path.join("data", client_id, "memory.json")
+ if not os.path.exists(memory_path):
+ return []
+
+ mtime = os.path.getmtime(memory_path)
+
+ # Check cache
+ if client_id in self._cache:
+ cache_entry = self._cache[client_id]
+ if mtime <= cache_entry["mtime"]:
+ return cache_entry["chunks"]
+
+ try:
+ with open(memory_path, "r", encoding="utf-8") as f:
+ history_data = json.load(f)
+
+ if not isinstance(history_data, list):
+ return []
+
+ chunks = []
+
+ for session in history_data:
+ session_timestamp = session.get("timestamp", "")
+ messages = session.get("messages", [])
+
+ # Pair up User and Assistant messages roughly
+ # Or just treat each relevant message as a chunk
+ # For context, it's nice to have the response.
+
+ for i, msg in enumerate(messages):
+ role = msg.get("role")
+ content = msg.get("content")
+
+ if role == "system" or not content:
+ continue
+
+ # Clean content
+ # 1. Remove News Context if present
+ if "\n\n\n---\nRELEVANT NEWS CONTEXT:" in content:
+ content = content.split("\n\n\n---\nRELEVANT NEWS CONTEXT:")[0]
+
+ # 2. Remove History RAG Context if present
+ content = re.sub(r'.*? ', '', content, flags=re.DOTALL)
+
+ # 3. Parse JSON if it looks like JSON (User messages are often JSON)
+ if content.strip().startswith("{") and "\"content\":" in content:
+ try:
+ data = json.loads(content)
+ if "content" in data:
+ content = data["content"]
+ except:
+ pass
+
+ if not content.strip():
+ continue
+
+ # Precompute keywords
+ keywords = self._tokenize(content)
+ if not keywords:
+ continue
+
+ chunks.append({
+ "session_date": session_timestamp[:10] if session_timestamp else "Unknown Date",
+ "role": role,
+ "content": content,
+ "keywords": keywords,
+ "full_text": f"[{session_timestamp[:16]}] {role}: {content}"
+ })
+
+ # Update cache
+ self._cache[client_id] = {
+ "mtime": mtime,
+ "chunks": chunks
+ }
+ logger.bind(tag=TAG).debug(f"Loaded {len(chunks)} history items for {client_id}")
+ return chunks
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to load history for {client_id}: {e}")
+ return []
+
+ def _tokenize(self, text: str) -> set:
+ """Simple tokenizer: lower, remove punct, remove stopwords"""
+ # Remove JSON artifacts if any (sometimes content is a JSON string)
+ # But usually it's cleaned text.
+
+ # Handle JSON content strings like '{"content": "..."}'
+ if text.strip().startswith("{") and "content" in text:
+ try:
+ data = json.loads(text)
+ if "content" in data:
+ text = data["content"]
+ except:
+ pass
+
+ text = re.sub(r'[^\w\s]', ' ', text.lower())
+ tokens = set(text.split())
+ return tokens - self.stopwords
+
+ def search(self, query: str, client_id: str, top_k: int = 3) -> str:
+ """Search history for relevant context"""
+ if not client_id:
+ return ""
+
+ chunks = self._load_history(client_id)
+ if not chunks:
+ return ""
+
+ query_tokens = self._tokenize(query)
+ if not query_tokens:
+ return ""
+
+ # For history, even 1 keyword overlap can be significant (e.g. "chickens")
+ # provided it's not a stopword.
+ threshold = 1
+
+ scored_chunks = []
+ for chunk in chunks:
+ overlap = len(query_tokens.intersection(chunk["keywords"]))
+ if overlap >= threshold:
+ scored_chunks.append((overlap, chunk))
+
+ # Sort by score desc, then by date (implicitly via list order? No, list is historical order)
+ # We want most relevant first. If tie, maybe most recent?
+ # Let's sort by score (desc), then index (desc) to prefer recent.
+ # But 'chunk' doesn't have index explicitly, but they are appended in order.
+ # So stable sort by score will keep order. But we want Recent history if scores are equal.
+ # So let's reverse chunks list before processing?
+ # Actually, let's just sort by score.
+
+ scored_chunks.sort(key=lambda x: x[0], reverse=True)
+
+ # Take top K
+ results = []
+ for score, chunk in scored_chunks[:top_k]:
+ results.append(chunk["full_text"])
+
+ if results:
+ return "\n\n\n" + "\n".join(results) + "\n \n"
+
+ return ""
+
+history_rag = HistoryRAG()
diff --git a/main/xiaozhi-server/core/utils/intent.py b/main/xiaozhi-server/core/utils/intent.py
index 747ecf38a..3e6a6fdf4 100644
--- a/main/xiaozhi-server/core/utils/intent.py
+++ b/main/xiaozhi-server/core/utils/intent.py
@@ -7,11 +7,11 @@ logger = setup_logging()
def create_instance(class_name, *args, **kwargs):
- # 创建intent实例
+ # Create intent instance
if os.path.exists(os.path.join('core', 'providers', 'intent', class_name, f'{class_name}.py')):
lib_name = f'core.providers.intent.{class_name}.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].IntentProvider(*args, **kwargs)
- raise ValueError(f"不支持的intent类型: {class_name},请检查该配置的type是否设置正确")
\ No newline at end of file
+ raise ValueError(f"Unsupported intent type: {class_name}, please check if the type in config is set correctly")
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/utils/llm.py b/main/xiaozhi-server/core/utils/llm.py
index 4c6ae27bf..b82da3c11 100644
--- a/main/xiaozhi-server/core/utils/llm.py
+++ b/main/xiaozhi-server/core/utils/llm.py
@@ -1,7 +1,7 @@
import os
import sys
-# 添加项目根目录到Python路径
+# Add project root directory to Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
sys.path.insert(0, project_root)
@@ -13,11 +13,11 @@ logger = setup_logging()
def create_instance(class_name, *args, **kwargs):
- # 创建LLM实例
+ # Create LLM instance
if os.path.exists(os.path.join('core', 'providers', 'llm', class_name, f'{class_name}.py')):
lib_name = f'core.providers.llm.{class_name}.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].LLMProvider(*args, **kwargs)
- raise ValueError(f"不支持的LLM类型: {class_name},请检查该配置的type是否设置正确")
+ raise ValueError(f"Unsupported LLM type: {class_name}, please check if the type in config is set correctly")
diff --git a/main/xiaozhi-server/core/utils/memory.py b/main/xiaozhi-server/core/utils/memory.py
index ff43b220c..8ee0192bf 100644
--- a/main/xiaozhi-server/core/utils/memory.py
+++ b/main/xiaozhi-server/core/utils/memory.py
@@ -15,4 +15,4 @@ def create_instance(class_name, *args, **kwargs):
sys.modules[lib_name] = importlib.import_module(f"{lib_name}")
return sys.modules[lib_name].MemoryProvider(*args, **kwargs)
- raise ValueError(f"不支持的记忆服务类型: {class_name}")
+ raise ValueError(f"Unsupported memory service type: {class_name}")
diff --git a/main/xiaozhi-server/core/utils/modules_initialize.py b/main/xiaozhi-server/core/utils/modules_initialize.py
index afe041098..58e91f1ca 100644
--- a/main/xiaozhi-server/core/utils/modules_initialize.py
+++ b/main/xiaozhi-server/core/utils/modules_initialize.py
@@ -5,7 +5,6 @@ from core.utils import tts, llm, intent, memory, vad, asr
TAG = __name__
logger = setup_logging()
-
def initialize_modules(
logger,
config: Dict[str, Any],
@@ -17,37 +16,22 @@ def initialize_modules(
init_intent=False,
) -> Dict[str, Any]:
"""
- 初始化所有模块组件
-
- Args:
- config: 配置字典
-
- Returns:
- Dict[str, Any]: 包含所有初始化后的模块的字典
+ Initialize all module components.
"""
modules = {}
- # 初始化TTS模块
if init_tts:
select_tts_module = config["selected_module"]["TTS"]
modules["tts"] = initialize_tts(config)
- logger.bind(tag=TAG).info(f"初始化组件: tts成功 {select_tts_module}")
+ logger.bind(tag=TAG).info(f"Component initialized: TTS success {select_tts_module}")
- # 初始化LLM模块
if init_llm:
select_llm_module = config["selected_module"]["LLM"]
- llm_type = (
- select_llm_module
- if "type" not in config["LLM"][select_llm_module]
- else config["LLM"][select_llm_module]["type"]
- )
- modules["llm"] = llm.create_instance(
- llm_type,
- config["LLM"][select_llm_module],
- )
- logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}")
+ llm_type = select_llm_module if "type" not in config["LLM"][select_llm_module] else config["LLM"][select_llm_module]["type"]
+ modules["llm"] = llm.create_instance(llm_type, config["LLM"][select_llm_module])
+ logger.bind(tag=TAG).info(f"Component initialized: LLM success {select_llm_module}")
- # 初始化Intent模块
+ # FIX: Lowercase 'intent' to match your config.yaml
if init_intent:
select_intent_module = config["selected_module"]["Intent"]
intent_type = (
@@ -55,97 +39,83 @@ def initialize_modules(
if "type" not in config["Intent"][select_intent_module]
else config["Intent"][select_intent_module]["type"]
)
- modules["intent"] = intent.create_instance(
+ modules["Intent"] = intent.create_instance(
intent_type,
config["Intent"][select_intent_module],
)
- logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}")
+ logger.bind(tag=TAG).info(f"Component initialized: Intent success {select_intent_module}")
- # 初始化Memory模块
if init_memory:
select_memory_module = config["selected_module"]["Memory"]
- memory_type = (
- select_memory_module
- if "type" not in config["Memory"][select_memory_module]
- else config["Memory"][select_memory_module]["type"]
- )
- modules["memory"] = memory.create_instance(
- memory_type,
- config["Memory"][select_memory_module],
- config.get("summaryMemory", None),
- )
- logger.bind(tag=TAG).info(f"初始化组件: memory成功 {select_memory_module}")
+ memory_type = select_memory_module if "type" not in config["Memory"][select_memory_module] else config["Memory"][select_memory_module]["type"]
+ modules["memory"] = memory.create_instance(memory_type, config["Memory"][select_memory_module], config.get("summaryMemory", None))
+ logger.bind(tag=TAG).info(f"Component initialized: Memory success {select_memory_module}")
- # 初始化VAD模块
if init_vad:
select_vad_module = config["selected_module"]["VAD"]
- vad_type = (
- select_vad_module
- if "type" not in config["VAD"][select_vad_module]
- else config["VAD"][select_vad_module]["type"]
- )
- modules["vad"] = vad.create_instance(
- vad_type,
- config["VAD"][select_vad_module],
- )
- logger.bind(tag=TAG).info(f"初始化组件: vad成功 {select_vad_module}")
+ vad_type = select_vad_module if "type" not in config["VAD"][select_vad_module] else config["VAD"][select_vad_module]["type"]
+ modules["vad"] = vad.create_instance(vad_type, config["VAD"][select_vad_module])
+ logger.bind(tag=TAG).info(f"Component initialized: VAD success {select_vad_module}")
- # 初始化ASR模块
if init_asr:
- select_asr_module = config["selected_module"]["ASR"]
modules["asr"] = initialize_asr(config)
- logger.bind(tag=TAG).info(f"初始化组件: asr成功 {select_asr_module}")
+
return modules
+# Global cache for ASR and TTS instances
+ASR_INSTANCES = {}
+TTS_INSTANCES = {}
-def initialize_tts(config):
+def initialize_tts(config, use_cache=True):
select_tts_module = config["selected_module"]["TTS"]
- tts_type = (
- select_tts_module
- if "type" not in config["TTS"][select_tts_module]
- else config["TTS"][select_tts_module]["type"]
- )
- new_tts = tts.create_instance(
- tts_type,
- config["TTS"][select_tts_module],
- str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
- )
+
+ # Check cache first (only if requested)
+ if use_cache and select_tts_module in TTS_INSTANCES:
+ logger.bind(tag=TAG).debug(f"Using cached TTS instance: {select_tts_module}")
+ return TTS_INSTANCES[select_tts_module]
+
+ tts_type = select_tts_module if "type" not in config["TTS"][select_tts_module] else config["TTS"][select_tts_module]["type"]
+ new_tts = tts.create_instance(tts_type, config["TTS"][select_tts_module], str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"))
+
+ # Cache the new instance (only if not a private override)
+ if use_cache:
+ TTS_INSTANCES[select_tts_module] = new_tts
+ logger.bind(tag=TAG).info(f"Component initialized and cached: TTS success {select_tts_module}")
+ else:
+ logger.bind(tag=TAG).info(f"Private Component initialized (not cached): TTS success {select_tts_module}")
+
return new_tts
-
-def initialize_asr(config):
+def initialize_asr(config, use_cache=True):
select_asr_module = config["selected_module"]["ASR"]
- asr_type = (
- select_asr_module
- if "type" not in config["ASR"][select_asr_module]
- else config["ASR"][select_asr_module]["type"]
- )
- new_asr = asr.create_instance(
- asr_type,
- config["ASR"][select_asr_module],
- str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"),
- )
- logger.bind(tag=TAG).info("ASR模块初始化完成")
+
+ # Check cache first (only if requested)
+ if use_cache and select_asr_module in ASR_INSTANCES:
+ logger.bind(tag=TAG).debug(f"Using cached ASR instance: {select_asr_module}")
+ return ASR_INSTANCES[select_asr_module]
+
+ asr_type = select_asr_module if "type" not in config["ASR"][select_asr_module] else config["ASR"][select_asr_module]["type"]
+ new_asr = asr.create_instance(asr_type, config["ASR"][select_asr_module], str(config.get("delete_audio", True)).lower() in ("true", "1", "yes"))
+
+ # Cache the new instance (only if not a private override)
+ if use_cache:
+ ASR_INSTANCES[select_asr_module] = new_asr
+ logger.bind(tag=TAG).info(f"Component initialized and cached: ASR success {select_asr_module}")
+ else:
+ logger.bind(tag=TAG).info(f"Private Component initialized (not cached): ASR success {select_asr_module}")
+
return new_asr
-
def initialize_voiceprint(asr_instance, config):
- """初始化声纹识别功能"""
+ """Initialize voiceprint identification"""
voiceprint_config = config.get("voiceprint")
- if not voiceprint_config:
- return False
-
- # 应用配置
- if not voiceprint_config.get("url") or not voiceprint_config.get("speakers"):
- logger.bind(tag=TAG).warning("声纹识别配置不完整")
+ if not voiceprint_config or not voiceprint_config.get("url") or not voiceprint_config.get("speakers"):
return False
-
try:
asr_instance.init_voiceprint(voiceprint_config)
- logger.bind(tag=TAG).info("ASR模块声纹识别功能已动态启用")
- logger.bind(tag=TAG).info(f"配置说话人数量: {len(voiceprint_config['speakers'])}")
+ logger.bind(tag=TAG).info("Voiceprint recognition enabled")
return True
except Exception as e:
- logger.bind(tag=TAG).error(f"动态初始化声纹识别功能失败: {str(e)}")
+ logger.bind(tag=TAG).error(f"Voiceprint initialization failed: {str(e)}")
return False
diff --git a/main/xiaozhi-server/core/utils/news_rag.py b/main/xiaozhi-server/core/utils/news_rag.py
new file mode 100644
index 000000000..8f8e7f4d6
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/news_rag.py
@@ -0,0 +1,171 @@
+import os
+import re
+import json
+import time
+from typing import List, Dict, Optional
+from config.logger import setup_logging
+
+TAG = "news_rag"
+logger = setup_logging()
+
+class NewsRAG:
+ _instance = None
+ _articles_cache = None # ID -> ArticleObj
+ _topic_index = None # Topic -> [ID list]
+ _last_load_time = 0
+ _stopwords = None
+
+ def __new__(cls):
+ if cls._instance is None:
+ cls._instance = super(NewsRAG, cls).__new__(cls)
+ cls._instance._stopwords = {
+ "the", "a", "an", "and", "or", "but", "is", "are", "was", "were",
+ "in", "on", "at", "to", "for", "with", "by", "about", "of", "it",
+ "this", "that", "i", "you", "he", "she", "they", "we", "what",
+ "when", "where", "who", "why", "how",
+ "me", "my", "myself", "mine", "your", "yours", "yourself",
+ "him", "his", "her", "hers", "its", "our", "ours", "their", "theirs",
+ "do", "does", "did", "can", "could", "will", "would", "should",
+ "have", "has", "had", "be", "been", "being",
+ "s", "re", "m", "ll", "ve", "d", "t",
+ "name", "tell", "say", "ask", "know", "think", "give",
+ "hello", "hi", "hey", "goodbye", "bye", "good", "morning", "afternoon", "evening", "night"
+ }
+ return cls._instance
+
+ def _load_news(self):
+ """Load and index news.json if changed"""
+ news_path = os.path.join("data", "news.json")
+ if not os.path.exists(news_path):
+ return {}, {}
+
+ mtime = os.path.getmtime(news_path)
+ if self._articles_cache is not None and mtime <= self._last_load_time:
+ return self._articles_cache, self._topic_index
+
+ try:
+ with open(news_path, "r", encoding="utf-8") as f:
+ data = json.load(f)
+
+ # Schema:
+ # "articles": {"1001": {...}},
+ # "topic_index": {"Trump": [1001]}
+
+ articles = data.get("articles", {})
+ topic_index = data.get("topic_index", {})
+
+ # Precompute keywords for each article to speed up search
+ for aid, art in articles.items():
+ if "keywords" not in art:
+ text_content = f"{art.get('title', '')}\n{art.get('content', '')}"
+ art["keywords"] = self._tokenize(text_content)
+
+ self._articles_cache = articles
+ self._topic_index = topic_index
+ self._last_load_time = mtime
+
+ logger.bind(tag=TAG).info(f"Loaded {len(articles)} articles and {len(topic_index)} topics")
+ return articles, topic_index
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to load news for RAG: {e}")
+ return {}, {}
+
+ def _tokenize(self, text: str) -> set:
+ """Simple tokenizer"""
+ text = re.sub(r'[^\w\s]', ' ', text.lower())
+ tokens = set(text.split())
+ return tokens - self._stopwords
+
+ def search(self, query: str, top_k: int = 5) -> str:
+ """
+ Search news.
+ 1. Identify relevant articles by keyword match.
+ 2. Identify the dominant topics from those articles.
+ 3. Retrieve full timeline for those topics (evolution).
+ """
+ articles, topic_index = self._load_news()
+ if not articles:
+ return ""
+
+ query_tokens = self._tokenize(query)
+ if not query_tokens:
+ return ""
+
+ explicit_triggers = {"news", "headline", "headlines", "happening", "current", "events"}
+ is_explicit_news_query = len(query_tokens.intersection(explicit_triggers)) > 0
+
+ # Dynamic threshold: if query keywords are few, require fewer matches
+ # e.g. "Tell me about state" -> "state" (1 token) -> match 1
+ # "State Department" -> "state", "department" (2 tokens) -> match 2
+ # But maybe safer to cap at 2.
+ if is_explicit_news_query:
+ threshold = 1
+ else:
+ threshold = min(2, len(query_tokens))
+
+ # 1. Score articles to find best matches
+ scored_articles = []
+ for aid, art in articles.items():
+ # art["keywords"] precomputed in _load_news
+ overlap = len(query_tokens.intersection(art.get("keywords", set())))
+ if overlap >= threshold:
+ scored_articles.append((overlap, art))
+
+ scored_articles.sort(key=lambda x: x[0], reverse=True)
+
+ # If no specific matches, handle generic "news" query
+ if not scored_articles:
+ if "news" in query_tokens:
+ # Return latest 3 articles (sorted by ID decending)
+ # Assuming larger ID = newer
+ sorted_ids = sorted([int(k) for k in articles.keys()], reverse=True)[:3]
+ latest_arts = [articles[str(i)] for i in sorted_ids if str(i) in articles]
+
+ if latest_arts:
+ out = "\n\n---\nLATEST NEWS HEADLINES:\n"
+ for art in latest_arts:
+ ts = time.strftime('%Y-%m-%d', time.localtime(art.get('timestamp', time.time())))
+ out += f"Title: {art.get('title')}\nDate: {ts}\nSummary: {art.get('content')}\n\n"
+ out += "---\n"
+ return out
+ return ""
+
+ # 2. Identify Dominant Topic
+ # We take the BEST matching article, and look at its topics.
+ best_match_art = scored_articles[0][1]
+ best_topics = best_match_art.get("topics", [])
+
+ if not best_topics:
+ # Fallback: just return the single article
+ return f"\n\n---\nRELEVANT NEWS:\nTitle: {best_match_art.get('title')}\nSummary: {best_match_art.get('content')}\n---\n"
+
+ # Pick the first topic as primary (or valid approach: merge all articles from all its topics?)
+ # Let's pick the first one for now as "Primary Topic"
+ target_topic = best_topics[0]
+
+ # 3. Retrieve Timeline
+ if target_topic in topic_index:
+ art_ids = topic_index[target_topic]
+ # Convert to ints for sorting
+ art_ids_int = [int(i) for i in art_ids]
+ art_ids_int.sort() # Oldest to Newest
+
+ # Limit to context window (e.g., last 3 articles)
+ relevant_ids = art_ids_int[-3:]
+
+ timeline_arts = []
+ for i in relevant_ids:
+ if str(i) in articles:
+ timeline_arts.append(articles[str(i)])
+
+ out = f"\n\n---\nNEWS TIMELINE (Topic: {target_topic}):\n"
+ for art in timeline_arts:
+ ts = time.strftime('%Y-%m-%d', time.localtime(art.get('timestamp', time.time())))
+ out += f"\n[{ts}] {art.get('title')}\n{art.get('content')}\n"
+ out += "\n---\n"
+ return out
+
+ return ""
+
+news_rag = NewsRAG()
diff --git a/main/xiaozhi-server/core/utils/npr_scraper.py b/main/xiaozhi-server/core/utils/npr_scraper.py
new file mode 100644
index 000000000..902e178b8
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/npr_scraper.py
@@ -0,0 +1,289 @@
+import os
+import time
+import json
+import asyncio
+import requests
+import logging
+import re
+from bs4 import BeautifulSoup
+from config.settings import load_config
+from config.logger import setup_logging
+from core.utils import llm
+
+TAG = "npr_scraper"
+logger = setup_logging()
+
+NEWS_JSON_PATH = os.path.join("data", "news.json")
+MAX_ARTICLES = 100
+
+def generate_summary_and_topics(llm_instance, text, title):
+ """Summarize text and extract multiple topics using the provided LLM instance."""
+ try:
+ # Simple heuristic to skip very short articles
+ if len(text) < 300:
+ return text, ["General"]
+
+ system_prompt = (
+ "You are a news editor. Read the article and provide:\n"
+ "1. A concise summary (80-100 words).\n"
+ "2. A list of 1-3 relevant topic tags (e.g., 'Politics', 'Trump', 'Economy', 'World').\n"
+ "Format your response exactly as:\n"
+ "Topics: [Topic1], [Topic2]\n"
+ "Summary: [Summary Content]"
+ )
+ user_prompt = f"Title: {title}\n\nContent:\n{text[:3000]}" # Truncate to avoid context limits
+
+ response = llm_instance.response_no_stream(system_prompt=system_prompt, user_prompt=user_prompt)
+
+ # Parse response
+ topics = ["General"]
+ summary = response
+
+ if "Topics:" in response and "Summary:" in response:
+ try:
+ parts = response.split("Summary:")
+ topic_part = parts[0].replace("Topics:", "").strip()
+ summary_part = parts[1].strip()
+
+ # Parse comma-separated topics
+ parsed_topics = [t.strip() for t in topic_part.split(",") if t.strip()]
+ if parsed_topics:
+ topics = parsed_topics
+
+ if summary_part:
+ summary = summary_part
+ except:
+ pass
+
+ return summary, topics
+ except Exception as e:
+ logger.bind(tag=TAG).warning(f"Summarization/Topic extraction failed for '{title}': {e}")
+ words = text.split()
+ return (" ".join(words[:150]) + "..." if len(words) > 150 else text), ["General"]
+
+def _load_news_json():
+ """Load existing news using new schema."""
+ if not os.path.exists(NEWS_JSON_PATH):
+ return {
+ "next_sequence_id": 1000,
+ "articles": {}, # ID -> ArticleObj
+ "topic_index": {} # TopicName -> [ID, ID...]
+ }
+
+ try:
+ with open(NEWS_JSON_PATH, "r", encoding="utf-8") as f:
+ data = json.load(f)
+ # Ensure schema integrity if upgrading from old format
+ if "articles" not in data:
+ return {
+ "next_sequence_id": 1000,
+ "articles": {},
+ "topic_index": {}
+ }
+ return data
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to load news.json: {e}")
+ return {
+ "next_sequence_id": 1000,
+ "articles": {},
+ "topic_index": {}
+ }
+
+def _save_news_json(data):
+ """Save news data to news.json."""
+ try:
+ with open(NEWS_JSON_PATH, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to save news.json: {e}")
+
+def _prune_articles(data):
+ """
+ Enforce MAX_ARTICLES limit using FIFO on Sequence ID.
+ If len(articles) > MAX_ARTICLES:
+ 1. Identify oldest articles by ID.
+ 2. Remove from 'articles'.
+ 3. Remove ID from all 'topic_index' lists.
+ 4. Remove empty topics.
+ """
+ articles = data.get("articles", {})
+ topic_index = data.get("topic_index", {})
+
+ current_count = len(articles)
+ if current_count <= MAX_ARTICLES:
+ return
+
+ logger.bind(tag=TAG).info(f"Pruning articles... Current: {current_count}, Max: {MAX_ARTICLES}")
+
+ # Sort IDs (keys are strings in JSON, need int conversion for reliable sorting)
+ # But wait, next_sequence_id is int. Keys in json dump are strings.
+ # So we sort by int(id)
+ sorted_ids = sorted([int(k) for k in articles.keys()])
+
+ # Calculate how many to remove
+ to_remove_count = current_count - MAX_ARTICLES
+ ids_to_remove = sorted_ids[:to_remove_count]
+
+ for aid_int in ids_to_remove:
+ aid_str = str(aid_int)
+
+ # 1. Remove from articles
+ if aid_str in articles:
+ # title = articles[aid_str].get("title", "Unknown")
+ del articles[aid_str]
+
+ # 2. Remove from topic_index
+ topics_to_delete = []
+ for topic, id_list in topic_index.items():
+ # Filter out this ID
+ # Use int comparison just in case list has ints or strings
+ if aid_int in id_list:
+ id_list.remove(aid_int)
+ elif aid_str in id_list:
+ id_list.remove(aid_str)
+
+ if not id_list:
+ topics_to_delete.append(topic)
+
+ # 3. Cleanup empty topics
+ for t in topics_to_delete:
+ del topic_index[t]
+
+ _save_news_json(data)
+
+def fetch_npr_news():
+ """
+ Fetches headlines, summarizes, categorizes, and updates news.json.
+ """
+ logger.bind(tag=TAG).info("Starting NPR news scrape (Relational JSON mode)...")
+
+ # Initialize LLM
+ try:
+ config = load_config()
+ select_llm_module = config["selected_module"]["LLM"]
+ llm_config = config["LLM"][select_llm_module]
+ llm_type = select_llm_module if "type" not in llm_config else llm_config["type"]
+ llm_instance = llm.create_instance(llm_type, llm_config)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to initialize LLM: {e}")
+ return
+
+ # Load data
+ news_data = _load_news_json()
+ articles_map = news_data["articles"]
+ topic_index = news_data["topic_index"]
+ next_seq_id = news_data.get("next_sequence_id", 1000)
+
+ # Quick lookup for existing titles
+ existing_titles = {art.get("title") for art in articles_map.values()}
+
+ base_url = "https://text.npr.org"
+
+ try:
+ response = requests.get(base_url, timeout=10)
+ response.raise_for_status()
+ soup = BeautifulSoup(response.text, 'html.parser')
+ topic_container = soup.find("div", class_="topic-container")
+
+ if not topic_container:
+ return
+
+ links = topic_container.find_all("a", class_="topic-title")
+ logger.bind(tag=TAG).info(f"Found {len(links)} articles.")
+
+ new_article_count = 0
+ current_time = time.time()
+
+ for i, link in enumerate(links):
+ title = link.get_text().strip()
+ if title in existing_titles:
+ continue
+
+ href = link.get('href')
+ article_url = base_url + href if not href.startswith("http") else href
+
+ logger.bind(tag=TAG).info(f"Processing [{i+1}/{len(links)}]: {title}")
+
+ try:
+ art_resp = requests.get(article_url, timeout=10)
+ art_resp.raise_for_status()
+ art_soup = BeautifulSoup(art_resp.text, 'html.parser')
+
+ # Extract text
+ search_root = art_soup.find("div", class_="paragraphs-container") or art_soup.find("main") or art_soup
+ elements = search_root.find_all(["p", "h2", "h3"])
+
+ article_text = ""
+ for el in elements:
+ txt = el.get_text().strip()
+ if not txt or txt.lower() == "text-only version": continue
+ if txt.strip().upper().startswith("TRANSCRIPT"): break
+ article_text += txt + "\n\n"
+
+ # LLM Process
+ summary, topics_list = generate_summary_and_topics(llm_instance, article_text, title)
+
+ # Assign ID
+ seq_id = next_seq_id
+ next_seq_id += 1
+
+ # Create Article Object
+ article_obj = {
+ "id": seq_id,
+ "title": title,
+ "url": article_url,
+ "content": summary,
+ "timestamp": current_time,
+ "topics": topics_list
+ }
+
+ # Update Storage
+ articles_map[str(seq_id)] = article_obj
+
+ # Update Index
+ for topic in topics_list:
+ if topic not in topic_index:
+ topic_index[topic] = []
+ topic_index[topic].append(seq_id)
+
+ news_data["next_sequence_id"] = next_seq_id
+ new_article_count += 1
+
+ time.sleep(0.5)
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Failed to process '{title}': {e}")
+ continue
+
+ total_articles = len(news_data.get("articles", {}))
+ total_topics = len(news_data.get("topic_index", {}))
+
+ if new_article_count > 0:
+ _prune_articles(news_data) # This saves internally IF pruning happens
+ # Force save if pruning didn't happen (or just save again to be safe)
+ _save_news_json(news_data)
+ logger.bind(tag=TAG).info(f"Added {new_article_count} new articles. Total: {total_articles}, Topics: {total_topics}")
+ else:
+ logger.bind(tag=TAG).info(f"No changes. No new articles found. Total: {total_articles}, Topics: {total_topics}")
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Scraper error: {e}")
+
+async def news_scraper_task():
+ """Background task to run the scraper every hour."""
+ logger.bind(tag=TAG).info("NPR Scraper task initialized.")
+ loop = asyncio.get_running_loop()
+
+ # Run immediately
+ await loop.run_in_executor(None, fetch_npr_news)
+
+ while True:
+ try:
+ await asyncio.sleep(3600)
+ logger.bind(tag=TAG).info("Running scheduled NPR scrape...")
+ await loop.run_in_executor(None, fetch_npr_news)
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"Error in scraper loop: {e}")
+ await asyncio.sleep(60)
diff --git a/main/xiaozhi-server/core/utils/opus_encoder_utils.py b/main/xiaozhi-server/core/utils/opus_encoder_utils.py
index 8d603e226..8bd35b961 100644
--- a/main/xiaozhi-server/core/utils/opus_encoder_utils.py
+++ b/main/xiaozhi-server/core/utils/opus_encoder_utils.py
@@ -1,6 +1,6 @@
"""
-Opus编码工具类
-将PCM音频数据编码为Opus格式
+Opus Encoder Utility
+Encode PCM audio data to Opus format
"""
import logging
@@ -11,73 +11,73 @@ from opuslib_next import constants
from typing import Optional, Callable, Any
class OpusEncoderUtils:
- """PCM到Opus的编码器"""
+ """PCM to Opus encoder"""
def __init__(self, sample_rate: int, channels: int, frame_size_ms: int):
"""
- 初始化Opus编码器
+ Initialize Opus encoder
Args:
- sample_rate: 采样率 (Hz)
- channels: 通道数 (1=单声道, 2=立体声)
- frame_size_ms: 帧大小 (毫秒)
+ sample_rate: Sampling rate (Hz)
+ channels: Number of channels (1=Mono, 2=Stereo)
+ frame_size_ms: Frame size (ms)
"""
self.sample_rate = sample_rate
self.channels = channels
self.frame_size_ms = frame_size_ms
- # 计算每帧样本数 = 采样率 * 帧大小(毫秒) / 1000
+ # Calc samples per frame = sample_rate * frame_size_ms / 1000
self.frame_size = (sample_rate * frame_size_ms) // 1000
- # 总帧大小 = 每帧样本数 * 通道数
+ # Total frame size = samples per frame * channels
self.total_frame_size = self.frame_size * channels
- # 比特率和复杂度设置
+ # Bitrate and complexity settings
self.bitrate = 24000 # bps
- self.complexity = 10 # 最高质量
+ self.complexity = 10 # Highest quality
- # 缓冲区初始化为空
+ # Buffer initialized to empty
self.buffer = np.array([], dtype=np.int16)
try:
- # 创建Opus编码器
+ # Create Opus encoder
self.encoder = Encoder(
- sample_rate, channels, constants.APPLICATION_AUDIO # 音频优化模式
+ sample_rate, channels, constants.APPLICATION_AUDIO # Audio optimization mode
)
self.encoder.bitrate = self.bitrate
self.encoder.complexity = self.complexity
- self.encoder.signal = constants.SIGNAL_VOICE # 语音信号优化
+ self.encoder.signal = constants.SIGNAL_VOICE # Voice signal optimization
except Exception as e:
- logging.error(f"初始化Opus编码器失败: {e}")
- raise RuntimeError("初始化失败") from e
+ logging.error(f"Failed to initialize Opus encoder: {e}")
+ raise RuntimeError("Initialization failed") from e
def reset_state(self):
- """重置编码器状态"""
+ """Reset encoder state"""
self.encoder.reset_state()
self.buffer = np.array([], dtype=np.int16)
def encode_pcm_to_opus_stream(self, pcm_data: bytes, end_of_stream: bool, callback: Callable[[Any], Any]):
"""
- 将PCM数据编码为Opus格式,以流式方式进行处理
+ Encode PCM data to Opus format, processing in stream mode
Args:
- pcm_data: PCM字节数据
- end_of_stream: 是否为流的结束,
- callback: opus处理方法
+ pcm_data: PCM byte data
+ end_of_stream: Whether it is end of stream,
+ callback: Opus processing method
Returns:
- Opus数据包列表
+ Opus data packet list
"""
- # 将字节数据转换为short数组
+ # Convert byte data to short array
new_samples = self._convert_bytes_to_shorts(pcm_data)
- # 校验PCM数据
+ # Validate PCM data
self._validate_pcm_data(new_samples)
- # 将新数据追加到缓冲区
+ # Append new data to buffer
self.buffer = np.append(self.buffer, new_samples)
offset = 0
- # 处理所有完整帧
+ # Process all complete frames
while offset <= len(self.buffer) - self.total_frame_size:
frame = self.buffer[offset : offset + self.total_frame_size]
output = self._encode(frame)
@@ -85,12 +85,12 @@ class OpusEncoderUtils:
callback(output)
offset += self.total_frame_size
- # 保留未处理的样本
+ # Keep unprocessed samples
self.buffer = self.buffer[offset:]
- # 流结束时处理剩余数据
+ # Process remaining data at end of stream
if end_of_stream and len(self.buffer) > 0:
- # 创建最后一帧并用0填充
+ # Create last frame and pad with 0s
last_frame = np.zeros(self.total_frame_size, dtype=np.int16)
last_frame[: len(self.buffer)] = self.buffer
@@ -100,37 +100,37 @@ class OpusEncoderUtils:
self.buffer = np.array([], dtype=np.int16)
def _encode(self, frame: np.ndarray) -> Optional[bytes]:
- """编码一帧音频数据"""
+ """Encode one frame of audio data"""
try:
- # 编码器已释放,跳过编码
+ # Encoder released, skip encoding
if not hasattr(self, 'encoder') or self.encoder is None:
return None
- # 将numpy数组转换为bytes
+ # Convert numpy array to bytes
frame_bytes = frame.tobytes()
- # opuslib要求输入字节数必须是channels*2的倍数
+ # opuslib requires input bytes to be multiple of channels*2
encoded = self.encoder.encode(frame_bytes, self.frame_size)
return encoded
except Exception as e:
- logging.error(f"Opus编码失败: {e}")
+ logging.error(f"Opus encoding failed: {e}")
traceback.print_exc()
return None
def _convert_bytes_to_shorts(self, bytes_data: bytes) -> np.ndarray:
- """将字节数组转换为short数组 (16位PCM)"""
- # 假设输入是小端字节序的16位PCM
+ """Convert byte array to short array (16-bit PCM)"""
+ # Assume input is little-endian 16-bit PCM
return np.frombuffer(bytes_data, dtype=np.int16)
def _validate_pcm_data(self, pcm_shorts: np.ndarray) -> None:
- """验证PCM数据是否有效"""
- # 16位PCM数据范围是 -32768 到 32767
+ """Verify successful PCM data"""
+ # 16-bit PCM data range is -32768 to 32767
if np.any((pcm_shorts < -32768) | (pcm_shorts > 32767)):
invalid_samples = pcm_shorts[(pcm_shorts < -32768) | (pcm_shorts > 32767)]
- logging.warning(f"发现无效PCM样本: {invalid_samples[:5]}...")
- # 在实际应用中可以选择裁剪而不是抛出异常
+ logging.warning(f"Invalid PCM samples found: {invalid_samples[:5]}...")
+ # In practice, can clip instead of raising exception
# np.clip(pcm_shorts, -32768, 32767, out=pcm_shorts)
def close(self):
- """关闭编码器并释放资源"""
+ """Close encoder and release resources"""
if hasattr(self, 'encoder') and self.encoder:
try:
del self.encoder
diff --git a/main/xiaozhi-server/core/utils/output_counter.py b/main/xiaozhi-server/core/utils/output_counter.py
index 1e7ae8df6..e76965078 100644
--- a/main/xiaozhi-server/core/utils/output_counter.py
+++ b/main/xiaozhi-server/core/utils/output_counter.py
@@ -1,23 +1,23 @@
import datetime
from typing import Dict, Tuple
-# 全局字典,用于存储每个设备的每日输出字数
+# Global dictionary to store daily output character count for each device
_device_daily_output: Dict[Tuple[str, datetime.date], int] = {}
-# 记录最后一次检查的日期
+# Record the date of the last check
_last_check_date: datetime.date = None
def reset_device_output():
"""
- 重置所有设备的每日输出字数
- 每天0点调用此函数
+ Reset daily output character count for all devices
+ Called at 00:00 every day
"""
_device_daily_output.clear()
def get_device_output(device_id: str) -> int:
"""
- 获取设备当日的输出字数
+ Get the output character count for the device today
"""
current_date = datetime.datetime.now().date()
return _device_daily_output.get((device_id, current_date), 0)
@@ -25,12 +25,12 @@ def get_device_output(device_id: str) -> int:
def add_device_output(device_id: str, char_count: int):
"""
- 增加设备的输出字数
+ Increase the output character count for the device
"""
current_date = datetime.datetime.now().date()
global _last_check_date
- # 如果是第一次调用或者日期发生变化,清空计数器
+ # Clear counter if it's the first call or the date has changed
if _last_check_date is None or _last_check_date != current_date:
_device_daily_output.clear()
_last_check_date = current_date
@@ -41,8 +41,8 @@ def add_device_output(device_id: str, char_count: int):
def check_device_output_limit(device_id: str, max_output_size: int) -> bool:
"""
- 检查设备是否超过输出限制
- :return: True 如果超过限制,False 如果未超过
+ Check if the device has exceeded the output limit
+ :return: True if exceeded, False otherwise
"""
if not device_id:
return False
diff --git a/main/xiaozhi-server/core/utils/p3.py b/main/xiaozhi-server/core/utils/p3.py
index c75b968e0..111aec31e 100644
--- a/main/xiaozhi-server/core/utils/p3.py
+++ b/main/xiaozhi-server/core/utils/p3.py
@@ -2,25 +2,25 @@ import struct
def decode_opus_from_file(input_file):
"""
- 从p3文件中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。
+ Decode Opus data from a p3 file and return a list of Opus data packets and the total duration.
"""
opus_datas = []
total_frames = 0
- sample_rate = 16000 # 文件采样率
- frame_duration_ms = 60 # 帧时长
+ sample_rate = 16000 # File sample rate
+ frame_duration_ms = 60 # Frame duration
frame_size = int(sample_rate * frame_duration_ms / 1000)
with open(input_file, 'rb') as f:
while True:
- # 读取头部(4字节):[1字节类型,1字节保留,2字节长度]
+ # Read header(4 bytes): [1 byte type, 1 byte reserved, 2 bytes length]
header = f.read(4)
if not header:
break
- # 解包头部信息
+ # Unpack header info
_, _, data_len = struct.unpack('>BBH', header)
- # 根据头部指定的长度读取 Opus 数据
+ # Read Opus data based on the length specified in the header
opus_data = f.read(data_len)
if len(opus_data) != data_len:
raise ValueError(f"Data length({len(opus_data)}) mismatch({data_len}) in the file.")
@@ -28,19 +28,19 @@ def decode_opus_from_file(input_file):
opus_datas.append(opus_data)
total_frames += 1
- # 计算总时长
+ # Calculate total duration
total_duration = (total_frames * frame_duration_ms) / 1000.0
return opus_datas, total_duration
def decode_opus_from_bytes(input_bytes):
"""
- 从p3二进制数据中解码 Opus 数据,并返回一个 Opus 数据包的列表以及总时长。
+ Decode Opus data from p3 binary data and return a list of Opus data packets and the total duration.
"""
import io
opus_datas = []
total_frames = 0
- sample_rate = 16000 # 文件采样率
- frame_duration_ms = 60 # 帧时长
+ sample_rate = 16000 # File sample rate
+ frame_duration_ms = 60 # Frame duration
frame_size = int(sample_rate * frame_duration_ms / 1000)
f = io.BytesIO(input_bytes)
diff --git a/main/xiaozhi-server/core/utils/prompt_manager.py b/main/xiaozhi-server/core/utils/prompt_manager.py
index 70f14d929..968ac2596 100644
--- a/main/xiaozhi-server/core/utils/prompt_manager.py
+++ b/main/xiaozhi-server/core/utils/prompt_manager.py
@@ -1,25 +1,16 @@
"""
-系统提示词管理器模块
-负责管理和更新系统提示词,包括快速初始化和异步增强功能
+System prompt manager module
+Responsible for managing and updating system prompts, including quick initialization and async enhancement functions
"""
import os
from typing import Dict, Any
from config.logger import setup_logging
+from config.config_loader import get_project_dir
from jinja2 import Template
TAG = __name__
-WEEKDAY_MAP = {
- "Monday": "星期一",
- "Tuesday": "星期二",
- "Wednesday": "星期三",
- "Thursday": "星期四",
- "Friday": "星期五",
- "Saturday": "星期六",
- "Sunday": "星期日",
-}
-
EMOJI_List = [
"😶",
"🙂",
@@ -46,7 +37,7 @@ EMOJI_List = [
class PromptManager:
- """系统提示词管理器,负责管理和更新系统提示词"""
+ """System prompt manager, responsible for managing and updating system prompts"""
def __init__(self, config: Dict[str, Any], logger=None):
self.config = config
@@ -54,13 +45,13 @@ class PromptManager:
self.base_prompt_template = None
self.last_update_time = 0
- # 导入全局缓存管理器
+ # Import global cache manager
from core.utils.cache.manager import cache_manager, CacheType
self.cache_manager = cache_manager
self.CacheType = CacheType
- # 初始化上下文源
+ # Initialize context source
from core.utils.context_provider import ContextDataProvider
self.context_provider = ContextDataProvider(config, self.logger)
self.context_data = {}
@@ -68,61 +59,99 @@ class PromptManager:
self._load_base_template()
def _load_base_template(self):
- """加载基础提示词模板"""
+ """Load base prompt template"""
try:
- template_path = self.config.get("prompt_template", None)
- if not template_path:
- template_path = "agent-base-prompt.txt"
+ template_path = self.config.get("prompt_template", "data/agent-base-prompt.txt")
+ if not os.path.isabs(template_path):
+ template_path = os.path.join(get_project_dir(), template_path)
cache_key = f"prompt_template:{template_path}"
- # 先从缓存获取
+ # Try cache first
cached_template = self.cache_manager.get(self.CacheType.CONFIG, cache_key)
if cached_template is not None:
self.base_prompt_template = cached_template
- self.logger.bind(tag=TAG).debug("从缓存加载基础提示词模板")
+ self.logger.bind(tag=TAG).debug("Load base prompt template from cache")
return
- # 缓存未命中,从文件读取
+ # Cache miss, read from file
if os.path.exists(template_path):
with open(template_path, "r", encoding="utf-8") as f:
template_content = f.read()
- # 存入缓存(CONFIG类型默认不自动过期,需要手动失效)
+ # Save to cache (CONFIG type does not expire automatically, needs manual invalidation)
self.cache_manager.set(
self.CacheType.CONFIG, cache_key, template_content
)
self.base_prompt_template = template_content
- self.logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存")
+ self.logger.bind(tag=TAG).debug("Successfully loaded base prompt template and cached")
else:
- self.logger.bind(tag=TAG).warning(f"未找到{template_path}文件")
+ self.logger.bind(tag=TAG).warning(f"File {template_path} not found")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to load prompt template: {e}")
- def get_quick_prompt(self, user_prompt: str, device_id: str = None) -> str:
- """快速获取系统提示词(使用用户配置)"""
- device_cache_key = f"device_prompt:{device_id}"
- cached_device_prompt = self.cache_manager.get(
- self.CacheType.DEVICE_PROMPT, device_cache_key
- )
- if cached_device_prompt is not None:
- self.logger.bind(tag=TAG).debug(f"使用设备 {device_id} 的缓存提示词")
- return cached_device_prompt
- else:
- self.logger.bind(tag=TAG).debug(
- f"设备 {device_id} 无缓存提示词,使用传入的提示词"
+ def get_quick_prompt(self, user_prompt: str, device_id: str = None, client_id: str = None) -> str:
+ """Quickly get system prompt (use user config or device-specific override)"""
+
+ # 1. Check for file-based override: data/{client_id}/prompt.txt
+ # Check client_id first (more specific session), then device_id (hardware)
+ target_ids = []
+ if client_id: target_ids.append(client_id)
+ if device_id: target_ids.append(device_id)
+
+ for tid in target_ids:
+ # Modified Logic: data/{client_id}/prompt.txt
+ prompt_file = os.path.join("data", tid, "prompt.txt")
+ if os.path.exists(prompt_file):
+ try:
+ with open(prompt_file, "r", encoding="utf-8") as f:
+ file_prompt = f.read().strip()
+ if file_prompt:
+ self.logger.bind(tag=TAG).info(f"Loaded device-specific prompt from {prompt_file}")
+ return file_prompt
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to load prompt file {prompt_file}: {e}")
+
+ # Legacy Fallback: check data/prompts/{tid}.txt
+ legacy_file = os.path.join("data", "prompts", f"{tid}.txt")
+ if os.path.exists(legacy_file):
+ try:
+ with open(legacy_file, "r", encoding="utf-8") as f:
+ file_prompt = f.read().strip()
+ if file_prompt:
+ self.logger.bind(tag=TAG).info(f"Loaded legacy device-specific prompt from {legacy_file}")
+ return file_prompt
+ except Exception as e:
+ self.logger.bind(tag=TAG).error(f"Failed to load legacy prompt file {legacy_file}: {e}")
+
+ # 2. Check Device Cache (using device_id as primary key)
+ # Note: if client_id is provided but not device_id, we might want to cache by client_id too,
+ # but existing logic uses device_id extensively.
+ cache_key_id = device_id or client_id
+ device_cache_key = f"device_prompt:{cache_key_id}" if cache_key_id else None
+
+ if device_cache_key:
+ cached_device_prompt = self.cache_manager.get(
+ self.CacheType.DEVICE_PROMPT, device_cache_key
)
+ if cached_device_prompt is not None:
+ self.logger.bind(tag=TAG).debug(f"Using cached prompt for {cache_key_id}")
+ return cached_device_prompt
- # 使用传入的提示词并缓存(如果有设备ID)
+ # 3. Fallback to default user_prompt
+ self.logger.bind(tag=TAG).debug(
+ f"No specific prompt for {cache_key_id}, using provided default"
+ )
+
+ # Cache provided prompt if device ID exists
if device_id:
device_cache_key = f"device_prompt:{device_id}"
self.cache_manager.set(self.CacheType.CONFIG, device_cache_key, user_prompt)
- self.logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存")
- self.logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...")
+ self.logger.bind(tag=TAG).info(f"Using default prompt: {user_prompt[:50]}...")
return user_prompt
def _get_current_time_info(self) -> tuple:
- """获取当前时间信息"""
+ """Get current time info"""
from .current_time import (
get_current_date,
get_current_weekday,
@@ -135,117 +164,149 @@ class PromptManager:
return today_date, today_weekday, lunar_date
- def _get_location_info(self, client_ip: str) -> str:
- """获取位置信息"""
+ def _get_location_info(self, client_ip: str, client_id: str = None) -> str:
+ """Get location info (prefer IP, fallback to client config)"""
try:
- # 先从缓存获取
+ # 1. Try cache for IP-based location
cached_location = self.cache_manager.get(self.CacheType.LOCATION, client_ip)
if cached_location is not None:
return cached_location
- # 缓存未命中,调用API获取
+ # 2. Try IP Geolocation
from core.utils.util import get_ip_info
ip_info = get_ip_info(client_ip, self.logger)
- city = ip_info.get("city", "未知位置")
- location = f"{city}"
+ city = ip_info.get("city")
+
+ if city and city != "Unknown location":
+ location = f"{city}"
+ # Save to cache
+ self.cache_manager.set(self.CacheType.LOCATION, client_ip, location)
+ return location
- # 存入缓存
- self.cache_manager.set(self.CacheType.LOCATION, client_ip, location)
- return location
+ # 3. Fallback to Client Configuration if IP geo fails or is uncertain
+ if client_id:
+ client_config_path = os.path.join("data", client_id, "config.json")
+ if os.path.exists(client_config_path):
+ try:
+ import json
+ with open(client_config_path, "r", encoding="utf-8") as f:
+ c = json.load(f)
+ client_location = c.get("default_location") or c.get("location")
+ if client_location:
+ self.logger.bind(tag=TAG).info(f"IP geo failed/Unknown, using client-specific fallback location: {client_location}")
+ return client_location
+ except Exception as e:
+ self.logger.bind(tag=TAG).warning(f"Failed to read client config for location: {e}")
+
+ return "Unknown location"
except Exception as e:
- self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
- return "未知位置"
+ self.logger.bind(tag=TAG).error(f"Failed to get location info: {e}")
+ return "Unknown location"
def _get_weather_info(self, conn, location: str) -> str:
- """获取天气信息"""
+ """Get weather info"""
try:
- # 先从缓存获取
+ # Try cache first
cached_weather = self.cache_manager.get(self.CacheType.WEATHER, location)
if cached_weather is not None:
return cached_weather
- # 缓存未命中,调用get_weather函数获取
+ # Cache miss, call get_weather function to get
from plugins_func.functions.get_weather import get_weather
from plugins_func.register import ActionResponse
- # 调用get_weather函数
- result = get_weather(conn, location=location, lang="zh_CN")
+ # Call get_weather function
+ result = get_weather(conn, location=location, lang="en_US")
if isinstance(result, ActionResponse):
weather_report = result.result
self.cache_manager.set(self.CacheType.WEATHER, location, weather_report)
return weather_report
- return "天气信息获取失败"
+ return "Failed to get weather info"
except Exception as e:
- self.logger.bind(tag=TAG).error(f"获取天气信息失败: {e}")
- return "天气信息获取失败"
+ self.logger.bind(tag=TAG).error(f"Failed to get weather info: {e}")
+ return "Failed to get weather info"
def update_context_info(self, conn, client_ip: str):
- """同步更新上下文信息"""
+ """Sync update context info"""
try:
local_address = ""
+ client_id = getattr(conn, "client_id", None)
+ if not client_id and hasattr(conn, "headers") and conn.headers:
+ client_id = conn.headers.get("client-id")
+
if (
- client_ip
+ (client_ip or client_id)
and self.base_prompt_template
and (
"local_address" in self.base_prompt_template
or "weather_info" in self.base_prompt_template
)
):
- # 获取位置信息(使用全局缓存)
- local_address = self._get_location_info(client_ip)
+ # Get location info (prefer client config)
+ local_address = self._get_location_info(client_ip, client_id)
if (
self.base_prompt_template
and "weather_info" in self.base_prompt_template
and local_address
):
- # 获取天气信息(使用全局缓存)
+ # Get weather info (use global cache)
self._get_weather_info(conn, local_address)
- # 获取配置的上下文数据
+ # Get configured context data
if hasattr(conn, "device_id") and conn.device_id:
if self.base_prompt_template and "dynamic_context" in self.base_prompt_template:
self.context_data = self.context_provider.fetch_all(conn.device_id)
else:
self.context_data = ""
- self.logger.bind(tag=TAG).debug(f"上下文信息更新完成")
+ self.logger.bind(tag=TAG).debug(f"Context info update completed")
except Exception as e:
- self.logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to update context info: {e}")
def build_enhanced_prompt(
self, user_prompt: str, device_id: str, client_ip: str = None, *args, **kwargs
) -> str:
- """构建增强的系统提示词"""
+ """Build enhanced system prompt"""
if not self.base_prompt_template:
return user_prompt
+ # PREVENT NESTED IDENTITY TAGS
+ # If user_prompt (from prompt.txt) already has , strip external template's tags
+ template_str = self.base_prompt_template
+ if "" in user_prompt:
+ # Simple heuristic: if user_prompt has its own identity,
+ # we should not wrap it again in the template.
+ # We strip the tags from the template for this render.
+ template_str = template_str.replace("", "").replace(" ", "")
+
try:
- # 获取最新的时间信息(不缓存)
+ # Get latest time info (no cache)
today_date, today_weekday, lunar_date = self._get_current_time_info()
- # 获取缓存的上下文信息
+ # Get cached context info
local_address = ""
weather_info = ""
- if client_ip:
- # 获取位置信息(从全局缓存)
- local_address = (
- self.cache_manager.get(self.CacheType.LOCATION, client_ip) or ""
- )
+ # Try to get client_id from kwargs (passed from Connection)
+ client_id = kwargs.get("client_id")
- # 获取天气信息(从全局缓存)
+ if client_ip or client_id:
+ # Get location info (resolves client config internally)
+ local_address = self._get_location_info(client_ip, client_id)
+
+ # Get weather info (from global cache)
if local_address:
weather_info = (
self.cache_manager.get(self.CacheType.WEATHER, local_address)
or ""
)
- # 替换模板变量
- template = Template(self.base_prompt_template)
+ # Replace template variables
+ template = Template(template_str)
enhanced_prompt = template.render(
base_prompt=user_prompt,
current_time="{{current_time}}",
@@ -266,10 +327,10 @@ class PromptManager:
self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt
)
self.logger.bind(tag=TAG).info(
- f"构建增强提示词成功,长度: {len(enhanced_prompt)}"
+ f"Enhanced prompt built successfully, length: {len(enhanced_prompt)}"
)
return enhanced_prompt
except Exception as e:
- self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}")
+ self.logger.bind(tag=TAG).error(f"Failed to build enhanced prompt: {e}")
return user_prompt
diff --git a/main/xiaozhi-server/core/utils/pump_manager.py b/main/xiaozhi-server/core/utils/pump_manager.py
new file mode 100644
index 000000000..f7335c114
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/pump_manager.py
@@ -0,0 +1,889 @@
+"""Pump data manager for Nightscout treatment/profile sync.
+
+This module is designed to be imported by the main server and run as a background
+async task, similar to a CGM manager. It can:
+1. load per-client pump config from `data//config.json`
+2. fetch new Nightscout treatments and profile data
+3. normalize and persist pump events to CSV/JSON
+4. generate short text summaries for downstream prompt/context assembly
+"""
+from __future__ import annotations
+
+import os
+import csv
+import json
+import time
+import asyncio
+from datetime import datetime, timezone, timedelta
+from typing import Any, Dict, List, Union, Optional
+from collections import Counter
+
+import requests
+import pytz
+
+TAG = "pump_manager"
+EASTERN_TZ = pytz.timezone("US/Eastern")
+
+
+class SimpleLogger:
+ def info(self, msg: str) -> None:
+ print(f"[INFO] {msg}")
+
+ def warning(self, msg: str) -> None:
+ print(f"[WARNING] {msg}")
+
+ def error(self, msg: str) -> None:
+ print(f"[ERROR] {msg}")
+
+
+logger = SimpleLogger()
+
+
+def create_pump_background_task(data_root: str = "data"):
+ """Return the coroutine for the server to schedule.
+
+ Example integration in an async server startup:
+ asyncio.create_task(create_pump_background_task("data"))
+ """
+ return pump_background_task(data_root=data_root)
+
+
+def to_utc_ms(value: Union[str, datetime]) -> int:
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
+ return int(dt.astimezone(timezone.utc).timestamp() * 1000)
+
+ if isinstance(value, str):
+ s = value.strip()
+ if s.endswith("Z"):
+ s = s[:-1] + "+00:00"
+ dt = datetime.fromisoformat(s)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return int(dt.astimezone(timezone.utc).timestamp() * 1000)
+
+ raise TypeError("value must be str or datetime")
+
+
+def parse_iso_to_dt(value: str) -> datetime:
+ s = value.strip()
+ if s.endswith("Z"):
+ s = s[:-1] + "+00:00"
+ dt = datetime.fromisoformat(s)
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=timezone.utc)
+ return dt
+
+
+class PumpManager:
+ def __init__(self, data_root: str = "data"):
+ self.data_root = data_root
+
+ def _get_client_config(self, client_id: str) -> Optional[Dict[str, Any]]:
+ config_path = os.path.join(self.data_root, client_id, "config.json")
+ if not os.path.exists(config_path):
+ return None
+ try:
+ with open(config_path, "r") as f:
+ payload = json.load(f)
+ return payload.get("pump")
+ except Exception as e:
+ logger.error(f"Failed to load pump config for {client_id}: {e}")
+ return None
+
+ def _client_dir(self, client_id: str) -> str:
+ return os.path.join(self.data_root, client_id)
+
+ def _events_csv_path(self, client_id: str) -> str:
+ return os.path.join(self._client_dir(client_id), "pump_events.csv")
+
+ def _profile_json_path(self, client_id: str) -> str:
+ return os.path.join(self._client_dir(client_id), "pump_profile.json")
+
+ def _is_pump_treatment(self, row: Dict[str, Any]) -> bool:
+ entered_by = str(row.get("enteredBy") or "").strip().lower()
+ event_type = str(row.get("eventType") or "").strip().lower()
+ pump_event_id = row.get("pump_event_id")
+
+ if "tconnectsync" in entered_by:
+ return True
+ if entered_by.startswith("pump"):
+ return True
+ if pump_event_id not in (None, "", 0):
+ return True
+ if "bolus" in event_type or event_type == "temp basal":
+ return True
+ return False
+
+ def _get_last_event_time_ms(self, client_id: str) -> int:
+ csv_path = self._events_csv_path(client_id)
+ if not os.path.exists(csv_path):
+ return 0
+
+ try:
+ with open(csv_path, "r", newline="") as f:
+ rows = list(csv.DictReader(f))
+ if not rows:
+ return 0
+
+ for row in reversed(rows):
+ unix_s = row.get("unix_s")
+ if unix_s in (None, ""):
+ continue
+ try:
+ return int(unix_s) * 1000
+ except (TypeError, ValueError):
+ continue
+ return 0
+ except Exception as e:
+ logger.warning(f"Failed to read last pump event time for {client_id}: {e}")
+ return 0
+
+ def _get_existing_event_keys(self, client_id: str) -> set:
+ rows = self._read_all_events(client_id)
+ keys = set()
+ for row in rows:
+ pump_event_id = str(row.get("pump_event_id") or "").strip()
+ raw_id = ""
+ try:
+ raw_json = row.get("raw_json")
+ if raw_json:
+ raw_payload = json.loads(raw_json)
+ raw_id = str(raw_payload.get("_id") or "").strip()
+ except Exception:
+ raw_id = ""
+
+ if pump_event_id:
+ keys.add(("pump_event_id", pump_event_id))
+ elif raw_id:
+ keys.add(("_id", raw_id))
+ else:
+ keys.add((
+ "fallback",
+ str(row.get("time") or ""),
+ str(row.get("event_type") or ""),
+ str(row.get("insulin_units") or ""),
+ str(row.get("rate_u_per_hr") or ""),
+ ))
+ return keys
+
+ def _event_key_from_normalized(self, row: Dict[str, Any]) -> tuple:
+ pump_event_id = str(row.get("pump_event_id") or "").strip()
+ raw_id = ""
+ try:
+ raw_json = row.get("raw_json")
+ if raw_json:
+ raw_payload = json.loads(raw_json)
+ raw_id = str(raw_payload.get("_id") or "").strip()
+ except Exception:
+ raw_id = ""
+
+ if pump_event_id:
+ return ("pump_event_id", pump_event_id)
+ if raw_id:
+ return ("_id", raw_id)
+ return (
+ "fallback",
+ str(row.get("time") or ""),
+ str(row.get("event_type") or ""),
+ str(row.get("insulin_units") or ""),
+ str(row.get("rate_u_per_hr") or ""),
+ )
+
+ def fetch_treatments(
+ self,
+ start: Union[str, datetime],
+ end: Union[str, datetime],
+ *,
+ base_url: str,
+ api_secret_sha1: str,
+ page_size: int = 500,
+ timeout: int = 20,
+ ) -> List[Dict[str, Any]]:
+ start_ms = to_utc_ms(start)
+ end_ms = to_utc_ms(end)
+
+ if end_ms < start_ms:
+ raise ValueError("end must be >= start")
+
+ headers = {"api-secret": api_secret_sha1}
+ url = f"{base_url.rstrip('/')}/api/v1/treatments.json"
+
+ all_rows: List[Dict[str, Any]] = []
+ last_ms = start_ms - 1
+
+ while True:
+ gt_time = datetime.fromtimestamp(last_ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
+ lte_time = datetime.fromtimestamp(end_ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
+ params = {
+ "count": page_size,
+ "find[created_at][$gt]": gt_time,
+ "find[created_at][$lte]": lte_time,
+ "sort$created_at": 1,
+ }
+
+ r = requests.get(url, params=params, headers=headers, timeout=timeout)
+ if not r.ok:
+ raise RuntimeError(f"Nightscout error {r.status_code}: {r.text[:300]}")
+
+ try:
+ batch = r.json()
+ except ValueError as e:
+ logger.error(
+ f"Nightscout returned non-JSON treatments response. "
+ f"url={r.url} status={r.status_code} content_type={r.headers.get('content-type')} "
+ f"body={r.text[:300]!r}"
+ )
+ raise RuntimeError(f"Nightscout returned non-JSON treatments response: {e}")
+ if not isinstance(batch, list):
+ raise RuntimeError(f"Unexpected response type: {type(batch)}")
+
+ if not batch:
+ break
+
+ batch.sort(key=lambda x: parse_iso_to_dt(x["created_at"]).timestamp() if "created_at" in x else 0)
+
+ for row in batch:
+ created_at = row.get("created_at")
+ if not isinstance(created_at, str):
+ continue
+ ms = int(parse_iso_to_dt(created_at).astimezone(timezone.utc).timestamp() * 1000)
+ if start_ms <= ms <= end_ms:
+ all_rows.append(row)
+
+ last_created_at = batch[-1].get("created_at")
+ if not isinstance(last_created_at, str):
+ break
+
+ new_last_ms = int(parse_iso_to_dt(last_created_at).astimezone(timezone.utc).timestamp() * 1000)
+
+ if new_last_ms <= last_ms:
+ break
+
+ last_ms = new_last_ms
+
+ if last_ms >= end_ms:
+ break
+
+ seen = set()
+ deduped: List[Dict[str, Any]] = []
+ for row in sorted(all_rows, key=lambda x: x.get("created_at", "")):
+ key = row.get("_id") or (
+ row.get("created_at"),
+ row.get("eventType"),
+ row.get("pump_event_id"),
+ )
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(row)
+
+ return deduped
+
+ def fetch_profile(self, *, base_url: str, api_secret_sha1: str, timeout: int = 20) -> Any:
+ headers = {"api-secret": api_secret_sha1}
+ url = f"{base_url.rstrip('/')}/api/v1/profile.json"
+
+ r = requests.get(url, headers=headers, timeout=timeout)
+ if not r.ok:
+ raise RuntimeError(f"Nightscout profile error {r.status_code}: {r.text[:300]}")
+ try:
+ return r.json()
+ except ValueError as e:
+ logger.error(
+ f"Nightscout returned non-JSON profile response. "
+ f"url={r.url} status={r.status_code} content_type={r.headers.get('content-type')} "
+ f"body={r.text[:300]!r}"
+ )
+ raise RuntimeError(f"Nightscout returned non-JSON profile response: {e}")
+
+ def extract_active_profile(self, profile_payload: Any) -> Dict[str, Any]:
+ if not isinstance(profile_payload, list) or not profile_payload:
+ return {}
+
+ first = profile_payload[0]
+ if not isinstance(first, dict):
+ return {}
+
+ default_profile_name = first.get("defaultProfile")
+ store = first.get("store", {})
+
+ if not isinstance(store, dict):
+ return {}
+
+ if isinstance(default_profile_name, str) and default_profile_name in store:
+ active_name = default_profile_name
+ else:
+ active_name = next(iter(store.keys()), None)
+
+ if active_name is None:
+ return {}
+
+ profile = store.get(active_name, {})
+ if not isinstance(profile, dict):
+ return {}
+
+ return {
+ "active_profile_name": active_name,
+ "timezone": profile.get("timezone"),
+ "units": profile.get("units"),
+ "dia_hours": profile.get("dia"),
+ "basal_schedule": profile.get("basal", []),
+ "carbratio_schedule": profile.get("carbratio", []),
+ "sensitivity_schedule": profile.get("sens", []),
+ "target_low_schedule": profile.get("target_low", []),
+ "target_high_schedule": profile.get("target_high", []),
+ "raw_profile": profile,
+ }
+
+ def _normalize_event(self, row: Dict[str, Any], tz=pytz.timezone("US/Eastern")) -> Optional[Dict[str, Any]]:
+ created_at = row.get("created_at")
+ if not isinstance(created_at, str):
+ return None
+
+ dt_utc = parse_iso_to_dt(created_at).astimezone(timezone.utc)
+ dt_local = dt_utc.astimezone(tz)
+ event_type = row.get("eventType", "UNKNOWN")
+
+ if event_type == "Temp Basal":
+ category = "temp_basal"
+ elif "Bolus" in str(event_type):
+ category = "bolus"
+ else:
+ category = "other"
+
+ return {
+ "time": created_at,
+ "time_et": dt_local.isoformat(),
+ "unix_s": int(dt_utc.timestamp()),
+ "hour": dt_local.hour,
+ "weekday": dt_local.weekday(),
+ "event_type": event_type,
+ "category": category,
+ "entered_by": row.get("enteredBy"),
+ "pump_event_id": row.get("pump_event_id"),
+ "insulin_units": row.get("insulin"),
+ "carbs_g": row.get("carbs"),
+ "glucose_mgdl": row.get("glucose"),
+ "rate_u_per_hr": row.get("absolute") if row.get("absolute") is not None else row.get("rate"),
+ "duration_min": row.get("duration"),
+ "reason": row.get("reason"),
+ "notes": row.get("notes"),
+ "raw_json": json.dumps(row, ensure_ascii=False),
+ }
+
+ def _append_to_csv(self, rows: List[Dict[str, Any]], filename: str) -> None:
+ if not rows:
+ return
+
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
+ file_exists = os.path.isfile(filename)
+
+ with open(filename, "a", newline="") as f:
+ writer = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
+ if not file_exists:
+ writer.writeheader()
+ writer.writerows(rows)
+
+ def _write_profile_json(self, client_id: str, payload: Dict[str, Any]) -> None:
+ path = self._profile_json_path(client_id)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ with open(path, "w") as f:
+ json.dump(payload, f, indent=2)
+
+ def _read_all_events(self, client_id: str) -> List[Dict[str, Any]]:
+ csv_path = self._events_csv_path(client_id)
+ if not os.path.exists(csv_path):
+ return []
+
+ try:
+ with open(csv_path, "r", newline="") as f:
+ return list(csv.DictReader(f))
+ except Exception as e:
+ logger.error(f"Failed to read pump events for {client_id}: {e}")
+ return []
+
+ def _safe_float(self, value: Any) -> Optional[float]:
+ if value in (None, ""):
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return None
+
+ def _fmt_number(self, value: Any, decimals: int = 2) -> str:
+ number = self._safe_float(value)
+ if number is None:
+ return "unknown"
+ return f"{number:.{decimals}f}"
+
+ def _fmt_int_like(self, value: Any) -> str:
+ number = self._safe_float(value)
+ if number is None:
+ return "unknown"
+ if float(number).is_integer():
+ return str(int(number))
+ return f"{number:.1f}"
+
+
+ def get_latest_bolus_event(self, client_id: str) -> Optional[Dict[str, Any]]:
+ rows = self._read_all_events(client_id)
+ if not rows:
+ return None
+
+ for row in reversed(rows):
+ category = str(row.get("category") or "").strip().lower()
+ event_type = str(row.get("event_type") or "").strip().lower()
+ insulin = self._safe_float(row.get("insulin_units"))
+
+ if category == "bolus":
+ return row
+ if "bolus" in event_type:
+ return row
+ if insulin is not None and insulin > 0:
+ return row
+
+ return None
+
+ def format_latest_bolus_summary(self, client_id: str) -> str:
+ bolus = self.get_latest_bolus_event(client_id)
+ if not bolus:
+ return ""
+
+ try:
+ now_ts = int(time.time())
+ event_ts = int(float(bolus.get("unix_s", 0)))
+ diff_min = max(0, (now_ts - event_ts) // 60)
+ except Exception:
+ diff_min = None
+
+ event_type = bolus.get("event_type") or "Bolus"
+ time_et = bolus.get("time_et") or bolus.get("time") or "unknown time"
+ insulin = self._fmt_number(bolus.get("insulin_units"))
+ carbs = self._fmt_int_like(bolus.get("carbs_g"))
+ glucose = self._fmt_int_like(bolus.get("glucose_mgdl"))
+ notes = str(bolus.get("notes") or "").strip()
+
+ parts = [
+ f"Last Bolus: {event_type} at {time_et}",
+ f"insulin {insulin} U",
+ ]
+
+ if carbs != "unknown":
+ parts.append(f"carbs {carbs} g")
+ if glucose != "unknown":
+ parts.append(f"glucose {glucose} mg/dL")
+ if diff_min is not None:
+ parts.append(f"{diff_min} mins ago")
+ if notes:
+ parts.append(f"notes: {notes}")
+
+ return ", ".join(parts) + "."
+
+ def fetch_and_update(self, client_id: str) -> None:
+ pump_config = self._get_client_config(client_id)
+ if not pump_config:
+ return
+
+ base_url = pump_config.get("base_url")
+ api_secret = pump_config.get("api_secret")
+ user_tz_str = pump_config.get("user_tz", "US/Eastern")
+
+ if not base_url or not api_secret:
+ return
+
+ try:
+ tz = pytz.timezone(user_tz_str)
+ except Exception:
+ tz = EASTERN_TZ
+
+ last_ms = self._get_last_event_time_ms(client_id)
+ end = datetime.now(timezone.utc)
+ # Always look back to avoid missing delayed/out-of-order Nightscout uploads.
+ # Existing rows are de-duplicated by pump_event_id, then Nightscout _id, then a fallback key.
+ start = end - timedelta(hours=6)
+
+ logger.info(
+ f"Pump fetch window for {client_id}: start={start.isoformat()} end={end.isoformat()} last_ms={last_ms}"
+ )
+
+ try:
+ treatments = self.fetch_treatments(
+ start,
+ end,
+ base_url=base_url,
+ api_secret_sha1=api_secret,
+ )
+ profile_payload = self.fetch_profile(
+ base_url=base_url,
+ api_secret_sha1=api_secret,
+ )
+ except Exception as e:
+ logger.error(f"Pump fetch failed for {client_id}: {e}")
+ return
+
+ logger.info(f"Raw treatments fetched for {client_id}: {len(treatments)}")
+ if treatments:
+ sample_entered_by = [str(x.get("enteredBy")) for x in treatments[:10]]
+ sample_event_types = [str(x.get("eventType")) for x in treatments[:10]]
+ logger.info(f"Sample enteredBy values for {client_id}: {sample_entered_by}")
+ logger.info(f"Sample eventType values for {client_id}: {sample_event_types}")
+
+ pump_rows = [x for x in treatments if self._is_pump_treatment(x)]
+ logger.info(f"Pump-like treatments after filter for {client_id}: {len(pump_rows)}")
+
+ normalized_rows = []
+ for row in pump_rows:
+ normalized = self._normalize_event(row, tz=tz)
+ if normalized is not None:
+ normalized_rows.append(normalized)
+
+ existing_keys = self._get_existing_event_keys(client_id)
+ deduped_rows = []
+ for normalized in normalized_rows:
+ key = self._event_key_from_normalized(normalized)
+ if key in existing_keys:
+ continue
+ existing_keys.add(key)
+ deduped_rows.append(normalized)
+
+ deduped_rows.sort(key=lambda x: int(float(x.get("unix_s", 0))))
+ self._append_to_csv(deduped_rows, self._events_csv_path(client_id))
+
+ active_profile = self.extract_active_profile(profile_payload)
+ profile_output = {
+ "updated_at": datetime.now(timezone.utc).isoformat(),
+ "active_profile": active_profile,
+ "raw_profile_payload": profile_payload,
+ }
+ self._write_profile_json(client_id, profile_output)
+
+ logger.info(
+ f"Fetched {len(deduped_rows)} new pump events for {client_id} "
+ f"after de-dup from {len(normalized_rows)} pump-like rows; "
+ f"profile saved to {self._profile_json_path(client_id)}"
+ )
+
+ def get_latest_event(self, client_id: str) -> Optional[Dict[str, Any]]:
+ rows = self._read_all_events(client_id)
+ if not rows:
+ return None
+ return rows[-1]
+
+ def _format_rate_clean(self, value: Any) -> str:
+ number = self._safe_float(value)
+ if number is None:
+ return "unknown"
+ return f"{number:.2f}".rstrip("0").rstrip(".")
+
+ def _load_active_profile(self, client_id: str) -> Dict[str, Any]:
+ profile_path = self._profile_json_path(client_id)
+ if not os.path.exists(profile_path):
+ return {}
+ try:
+ with open(profile_path, "r", encoding="utf-8") as f:
+ payload = json.load(f)
+ active_profile = payload.get("active_profile", {})
+ return active_profile if isinstance(active_profile, dict) else {}
+ except Exception as e:
+ logger.warning(f"Failed to load active pump profile for {client_id}: {e}")
+ return {}
+
+ def _get_scheduled_basal_rate_at_event(self, client_id: str, event_row: Dict[str, Any]) -> Optional[float]:
+ active_profile = self._load_active_profile(client_id)
+ basal_schedule = active_profile.get("basal_schedule", [])
+ if not isinstance(basal_schedule, list) or not basal_schedule:
+ return None
+
+ event_time = event_row.get("time_et") or event_row.get("time")
+ if not event_time:
+ return None
+
+ try:
+ event_dt = parse_iso_to_dt(str(event_time))
+ seconds_since_midnight = event_dt.hour * 3600 + event_dt.minute * 60 + event_dt.second
+ except Exception:
+ return None
+
+ selected_rate = None
+ selected_start = -1
+ for segment in basal_schedule:
+ try:
+ start_seconds = int(float(segment.get("timeAsSeconds", 0)))
+ value = float(segment.get("value"))
+ except Exception:
+ continue
+
+ if start_seconds <= seconds_since_midnight and start_seconds >= selected_start:
+ selected_start = start_seconds
+ selected_rate = value
+
+ if selected_rate is None:
+ for segment in reversed(basal_schedule):
+ try:
+ return float(segment.get("value"))
+ except Exception:
+ continue
+
+ return selected_rate
+
+ def get_realtime_status(self, client_id: str) -> str:
+ latest = self.get_latest_event(client_id)
+ if not latest:
+ return ""
+
+ try:
+ now_ts = int(time.time())
+ event_ts = int(float(latest.get("unix_s", 0)))
+ diff_min = max(0, (now_ts - event_ts) // 60)
+ event_type = latest.get("event_type", "UNKNOWN")
+ category = latest.get("category", "other")
+
+ if category == "temp_basal":
+ raw_rate = latest.get("rate_u_per_hr")
+ raw_duration = latest.get("duration_min")
+ rate = self._format_rate_clean(raw_rate)
+ duration = self._fmt_int_like(raw_duration)
+ reason = str(latest.get("reason") or "").strip()
+
+ scheduled_rate = self._get_scheduled_basal_rate_at_event(client_id, latest)
+ event_rate = self._safe_float(raw_rate)
+
+ if scheduled_rate is not None and event_rate is not None:
+ scheduled_text = self._format_rate_clean(scheduled_rate)
+ if abs(event_rate - scheduled_rate) < 0.01:
+ summary = (
+ f"Latest Pump Event: basal delivery matched scheduled profile rate "
+ f"({rate} U/hr), {diff_min} mins ago"
+ )
+ else:
+ summary = (
+ f"Latest Pump Event: Temp Basal {rate} U/hr for {duration} min, "
+ f"{diff_min} mins ago; scheduled profile basal was {scheduled_text} U/hr"
+ )
+ else:
+ summary = f"Latest Pump Event: Temp Basal {rate} U/hr for {duration} min, {diff_min} mins ago"
+
+ if reason:
+ summary += f" ({reason})"
+ return summary + "."
+
+ if category == "bolus":
+ insulin = self._fmt_number(latest.get("insulin_units"))
+ carbs = self._fmt_int_like(latest.get("carbs_g"))
+ glucose = self._fmt_int_like(latest.get("glucose_mgdl"))
+ parts = [
+ f"Latest Pump Event: {event_type}",
+ f"{insulin} U",
+ ]
+ if carbs != "unknown":
+ parts.append(f"{carbs} g carbs")
+ if glucose != "unknown":
+ parts.append(f"glucose {glucose} mg/dL")
+ parts.append(f"{diff_min} mins ago")
+ return ", ".join(parts) + "."
+
+ reason = str(latest.get("reason") or latest.get("notes") or "").strip()
+ summary = f"Latest Pump Event: {event_type}, {diff_min} mins ago"
+ if reason:
+ summary += f" ({reason})"
+ return summary + "."
+ except Exception:
+ return ""
+
+
+ def get_authoritative_summary(self, client_id: str) -> str:
+ """Force a fresh read and return an authoritative summary."""
+ # fetch_and_update should be called by the caller before this if needed
+ rows = self._read_all_events(client_id)
+ if not rows:
+ return "[No Pump Data Available]"
+
+ # Sort by unix_s to ensure absolute latest
+ try:
+ rows.sort(key=lambda x: int(float(x.get("unix_s", 0))))
+ except Exception:
+ pass
+
+ latest = rows[-1]
+
+ # Build authoritative status
+ status_text = self.get_realtime_status(client_id)
+ bolus_summary = self.format_latest_bolus_summary(client_id)
+
+ return (
+ f"--- FRESH PUMP STATUS (AUTHORITATIVE) ---\n"
+ f"{status_text}\n"
+ f"{bolus_summary}\n"
+ f"Interpretation rule: For Temp Basal events, compare event rate with scheduled pump profile basal rate. If they match or nearly match, do not describe it as a separate temp basal intervention; describe it as basal delivery matching the scheduled profile.\n"
+ f"--- END FRESH DATA ---"
+ )
+
+ def analyze_recent_patterns(self, client_id: str, days: int = 3) -> List[str]:
+ rows = self._read_all_events(client_id)
+ if not rows:
+ return []
+
+ try:
+ cutoff_ts = int(time.time()) - days * 86400
+ recent_rows = [
+ r for r in rows
+ if int(float(r.get("unix_s", 0))) >= cutoff_ts
+ ]
+ if not recent_rows:
+ return []
+
+ counts = Counter(r.get("event_type", "UNKNOWN") for r in recent_rows)
+ trends: List[str] = []
+
+ if counts:
+ top_name, top_count = counts.most_common(1)[0]
+ trends.append(
+ f"Pump Pattern: Most frequent recent event is {top_name} ({top_count} times in last {days} days)."
+ )
+
+ bolus_rows = [
+ r for r in recent_rows
+ if str(r.get("category") or "").strip().lower() == "bolus"
+ or "bolus" in str(r.get("event_type") or "").strip().lower()
+ ]
+
+ hourly_bolus = Counter(int(float(r.get("hour", 0))) for r in bolus_rows)
+ if hourly_bolus:
+ top_hour, top_hour_count = hourly_bolus.most_common(1)[0]
+ trends.append(
+ f"Pump Pattern: Bolus events most often happen around hour {top_hour:02d}:00 ({top_hour_count} times)."
+ )
+
+ bolus_with_amount = [
+ self._safe_float(r.get("insulin_units"))
+ for r in bolus_rows
+ if self._safe_float(r.get("insulin_units")) is not None
+ ]
+ if bolus_with_amount:
+ avg_bolus = sum(bolus_with_amount) / len(bolus_with_amount)
+ trends.append(
+ f"Pump Pattern: Average recent bolus size is {avg_bolus:.2f} U across {len(bolus_with_amount)} bolus events."
+ )
+
+ return trends
+ except Exception as e:
+ logger.warning(f"Failed to analyze recent pump patterns for {client_id}: {e}")
+ return []
+
+ def get_context_summary(self, client_id: str) -> str:
+ status = self.get_realtime_status(client_id)
+ latest_bolus = self.format_latest_bolus_summary(client_id)
+ patterns = self.analyze_recent_patterns(client_id)
+
+ sections = ["[Pump Data]"]
+ if status:
+ sections.append(status)
+ if latest_bolus:
+ sections.append(latest_bolus)
+ if patterns:
+ sections.extend(patterns)
+
+ if len(sections) == 1:
+ return ""
+ return "\n".join(sections)
+
+ def has_pump_config(self, client_id: str) -> bool:
+ pump_config = self._get_client_config(client_id)
+ return bool(pump_config and pump_config.get("base_url") and pump_config.get("api_secret"))
+
+ def analyze_insulin_effectiveness(self, client_id: str) -> List[str]:
+ pump_rows = self._read_all_events(client_id)
+ cgm_path = os.path.join(self._client_dir(client_id), "cgm.csv")
+
+ if not os.path.exists(cgm_path):
+ return []
+
+ with open(cgm_path, "r") as f:
+ cgm_rows = list(csv.DictReader(f))
+
+ if not pump_rows or not cgm_rows:
+ return []
+
+ results = []
+
+ for row in pump_rows[-10:]: # 看最近10次
+ if row.get("category") != "bolus":
+ continue
+
+ ts = int(float(row["unix_s"]))
+
+ before = [
+ float(r["sgv"])
+ for r in cgm_rows
+ if ts - 1800 <= int(r["unix_s"]) <= ts
+ ]
+
+ after = [
+ float(r["sgv"])
+ for r in cgm_rows
+ if ts + 3600 <= int(r["unix_s"]) <= ts + 4*3600
+ ]
+
+ if not before or not after:
+ continue
+
+ delta = sum(after)/len(after) - sum(before)/len(before)
+ results.append(delta)
+
+ if not results:
+ return []
+
+ avg_delta = sum(results)/len(results)
+
+ direction = "decreased" if avg_delta < 0 else "increased"
+
+ return [
+ f"After recent boluses, glucose {direction} by {abs(avg_delta):.1f} mg/dL on average"
+ ]
+
+ def detect_pump_anomalies(self, client_id: str) -> List[str]:
+ rows = self._read_all_events(client_id)
+ if not rows:
+ return []
+
+ recent = rows[-100:]
+ bolus_count = sum(1 for r in recent if r.get("category") == "bolus")
+
+ insights = []
+
+ if bolus_count > 20:
+ insights.append("High frequency of bolus events detected recently")
+
+ overnight_temp = [
+ r for r in recent
+ if r.get("category") == "temp_basal" and int(r.get("hour", 0)) < 6
+ ]
+
+ if len(overnight_temp) > 5:
+ insights.append("Frequent overnight temp basal usage")
+
+ return insights
+
+async def pump_background_task(data_root: str = "data") -> None:
+ logger.info("Pump scraper task started.")
+ manager = PumpManager(data_root=data_root)
+
+ while True:
+ try:
+ if os.path.exists(data_root):
+ for client_id in os.listdir(data_root):
+ client_path = os.path.join(data_root, client_id)
+ if os.path.isdir(client_path) and manager.has_pump_config(client_id):
+ manager.fetch_and_update(client_id)
+ await asyncio.sleep(900)
+ except Exception as e:
+ logger.error(f"Pump background task error: {e}")
+ await asyncio.sleep(60)
+
+
+if __name__ == "__main__":
+ manager = PumpManager(data_root="data")
+ demo_client = "demo_client"
+ print("Pump manager module loaded.")
+ print(manager.get_context_summary(demo_client))
diff --git a/main/xiaozhi-server/core/utils/textUtils.py b/main/xiaozhi-server/core/utils/textUtils.py
index 2f6afa8c9..05a9872a2 100644
--- a/main/xiaozhi-server/core/utils/textUtils.py
+++ b/main/xiaozhi-server/core/utils/textUtils.py
@@ -36,13 +36,13 @@ EMOJI_RANGES = [
def get_string_no_punctuation_or_emoji(s):
- """去除字符串首尾的空格、标点符号和表情符号"""
+ """Remove spaces, punctuation and emoji from start/end of string"""
chars = list(s)
- # 处理开头的字符
+ # Process starting characters
start = 0
while start < len(chars) and is_punctuation_or_emoji(chars[start]):
start += 1
- # 处理结尾的字符
+ # Process ending characters
end = len(chars) - 1
while end >= start and is_punctuation_or_emoji(chars[end]):
end -= 1
@@ -50,27 +50,32 @@ def get_string_no_punctuation_or_emoji(s):
def is_punctuation_or_emoji(char):
- """检查字符是否为空格、指定标点或表情符号"""
- # 定义需要去除的中英文标点(包括全角/半角)
+ """Check if char is space, specified punctuation or emoji"""
+ # Define Chinese/English punctuation to remove (including full/half width)
punctuation_set = {
",",
- ",", # 中文逗号 + 英文逗号
+ ",", # Chinese comma + English comma
"。",
- ".", # 中文句号 + 英文句号
+ ".", # Chinese period + English period
"!",
- "!", # 中文感叹号 + 英文感叹号
+ "!", # Chinese exclamation mark + English exclamation mark
"“",
"”",
- '"', # 中文双引号 + 英文引号
+ '"', # Chinese double quotes + English quotes
":",
- ":", # 中文冒号 + 英文冒号
+ ":", # Chinese colon + English colon
"-",
- "-", # 英文连字符 + 中文全角横线
- "、", # 中文顿号
+ "-", # English hyphen + Chinese full-width dash
+ "、", # Chinese uneven mark
"[",
- "]", # 方括号
+ "]", # Brackets
"【",
- "】", # 中文方括号
+ "】", # Chinese brackets
+ "(", ")", # English Parentheses
+ "(", ")", # Chinese Parentheses
+ ";", ";", # Semicolons
+ "?", "?", # Question marks
+ "~", "~", # Tildes
}
if char.isspace() or char in punctuation_set:
return True
@@ -78,7 +83,7 @@ def is_punctuation_or_emoji(char):
async def get_emotion(conn, text):
- """获取文本内的情绪消息"""
+ """Get emotion message/emoji within text"""
emoji = "🙂"
emotion = "happy"
for char in text:
@@ -98,16 +103,16 @@ async def get_emotion(conn, text):
)
)
except Exception as e:
- conn.logger.bind(tag=TAG).warning(f"发送情绪表情失败,错误:{e}")
+ conn.logger.bind(tag=TAG).warning(f"Failed to send emotion emoji, error: {e}")
return
def is_emoji(char):
- """检查字符是否为emoji表情"""
+ """Check if char is an emoji"""
code_point = ord(char)
return any(start <= code_point <= end for start, end in EMOJI_RANGES)
def check_emoji(text):
- """去除文本中的所有emoji表情"""
+ """Remove all emojis from text"""
return ''.join(char for char in text if not is_emoji(char) and char != "\n")
diff --git a/main/xiaozhi-server/core/utils/tts.py b/main/xiaozhi-server/core/utils/tts.py
index 6727f6de6..43cb4955c 100644
--- a/main/xiaozhi-server/core/utils/tts.py
+++ b/main/xiaozhi-server/core/utils/tts.py
@@ -10,50 +10,50 @@ logger = setup_logging()
punctuation_set = {
",",
- ",", # 中文逗号 + 英文逗号
+ ",", # Chinese comma + English comma
"。",
- ".", # 中文句号 + 英文句号
+ ".", # Chinese period + English period
"!",
- "!", # 中文感叹号 + 英文感叹号
+ "!", # Chinese exclamation mark + English exclamation mark
"“",
"”",
- '"', # 中文双引号 + 英文引号
+ '"', # Chinese double quotes + English quotes
":",
- ":", # 中文冒号 + 英文冒号
+ ":", # Chinese colon + English colon
"-",
- "-", # 英文连字符 + 中文全角横线
- "、", # 中文顿号
+ "-", # English hyphen + Chinese full-width dash
+ "、", # Chinese uneven mark
"[",
- "]", # 方括号
+ "]", # Brackets
"【",
- "】", # 中文方括号
- "~", # 波浪号
+ "】", # Chinese brackets
+ "~", # Tilde
}
def create_instance(class_name, *args, **kwargs):
- # 创建TTS实例
+ # Create TTS instance
if os.path.exists(os.path.join('core', 'providers', 'tts', f'{class_name}.py')):
lib_name = f'core.providers.tts.{class_name}'
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f'{lib_name}')
return sys.modules[lib_name].TTSProvider(*args, **kwargs)
- raise ValueError(f"不支持的TTS类型: {class_name},请检查该配置的type是否设置正确")
+ raise ValueError(f"Unsupported TTS type: {class_name}, please check if the type in config is set correctly")
class MarkdownCleaner:
"""
- 封装 Markdown 清理逻辑:直接用 MarkdownCleaner.clean_markdown(text) 即可
+ Encapsulate Markdown cleanup logic: simply use MarkdownCleaner.clean_markdown(text)
"""
- # 公式字符
+ # Formula characters
NORMAL_FORMULA_CHARS = re.compile(r'[a-zA-Z\\^_{}\+\-\(\)\[\]=]')
@staticmethod
def _replace_inline_dollar(m: re.Match) -> str:
"""
- 只要捕获到完整的 "$...$":
- - 如果内部有典型公式字符 => 去掉两侧 $
- - 否则 (纯数字/货币等) => 保留 "$...$"
+ As long as a complete "$...$" is captured:
+ - If internal contains typical formula characters => remove both sides $
+ - Otherwise (pure numbers/currency etc.) => keep "$...$"
"""
content = m.group(1)
if MarkdownCleaner.NORMAL_FORMULA_CHARS.search(content):
@@ -64,7 +64,7 @@ class MarkdownCleaner:
@staticmethod
def _replace_table_block(match: re.Match) -> str:
"""
- 当匹配到一个整段表格块时,回调该函数。
+ Callback when matching a whole table block.
"""
block_text = match.group('table_block')
lines = block_text.strip('\n').split('\n')
@@ -86,11 +86,11 @@ class MarkdownCleaner:
lines_for_tts = []
if len(parsed_table) == 1:
- # 只有一行
+ # Only one line
only_line_str = ", ".join(parsed_table[0])
- lines_for_tts.append(f"单行表格:{only_line_str}")
+ lines_for_tts.append(f"Single line table: {only_line_str}")
else:
- lines_for_tts.append(f"表头是:{', '.join(headers)}")
+ lines_for_tts.append(f"Headers are: {', '.join(headers)}")
for i, row in enumerate(data_rows, start=1):
row_str_list = []
for col_index, cell_val in enumerate(row):
@@ -98,47 +98,47 @@ class MarkdownCleaner:
row_str_list.append(f"{headers[col_index]} = {cell_val}")
else:
row_str_list.append(cell_val)
- lines_for_tts.append(f"第 {i} 行:{', '.join(row_str_list)}")
+ lines_for_tts.append(f"Row {i}: {', '.join(row_str_list)}")
return "\n".join(lines_for_tts) + "\n"
- # 预编译所有正则表达式(按执行频率排序)
- # 这里要把 replace_xxx 的静态方法放在最前定义,以便在列表里能正确引用它们。
+ # Pre-compile all regexes (sorted by execution frequency)
+ # Must define static methods replace_xxx first to reference them correctly in the list.
REGEXES = [
- (re.compile(r'```.*?```', re.DOTALL), ''), # 代码块
- (re.compile(r'^#+\s*', re.MULTILINE), ''), # 标题
- (re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # 粗体
- (re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\1'), r'\2'), # 斜体
- (re.compile(r'!\[.*?\]\(.*?\)'), ''), # 图片
- (re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # 链接
- (re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # 引用
+ (re.compile(r'```.*?```', re.DOTALL), ''), # Code block
+ (re.compile(r'^#+\s*', re.MULTILINE), ''), # Header
+ (re.compile(r'(\*\*|__)(.*?)\1'), r'\2'), # Bold
+ (re.compile(r'(\*|_)(?=\S)(.*?)(?<=\S)\1'), r'\2'), # Italic
+ (re.compile(r'!\[.*?\]\(.*?\)'), ''), # Image
+ (re.compile(r'\[(.*?)\]\(.*?\)'), r'\1'), # Link
+ (re.compile(r'^\s*>+\s*', re.MULTILINE), ''), # Quote
(
re.compile(r'(?P(?:^[^\n]*\|[^\n]*\n)+)', re.MULTILINE),
_replace_table_block
),
- (re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # 列表
- (re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # 块级公式
+ (re.compile(r'^\s*[*+-]\s*', re.MULTILINE), '- '), # List
+ (re.compile(r'\$\$.*?\$\$', re.DOTALL), ''), # Block level formula
(
re.compile(r'(? str:
"""
- 主入口方法:依序执行所有正则,移除或替换 Markdown 元素
+ Main entry method: execute all regexes in order to remove or replace Markdown elements
"""
- # 检查文本是否全为英文和基本标点符号
+ # Check if text is all English and basic punctuation
if text and all((c.isascii() or c.isspace() or c in punctuation_set) for c in text):
- # 保留原始空格,直接返回
+ # Keep original spaces, return directly
return text
for regex, replacement in MarkdownCleaner.REGEXES:
text = regex.sub(replacement, text)
- # 去除emoji表情
+ # Remove emoji expressions
text = check_emoji(text)
return text.strip()
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py
index 9339da7ec..14cf37192 100644
--- a/main/xiaozhi-server/core/utils/util.py
+++ b/main/xiaozhi-server/core/utils/util.py
@@ -72,78 +72,109 @@ def is_private_ip(ip_addr):
except (ValueError, IndexError):
return False # IP address format error or insufficient segments
-
-def get_ip_info(ip_addr, logger):
+def get_ip_info(client_ip=None, logger=None):
+ """
+ Resolves location based on public IP.
+ If client_ip is local, it fetches the server's public IP.
+ """
+ import requests
+
+ # Check if IP is private/local
+ is_local = not client_ip or is_private_ip(client_ip)
+
try:
- # 导入全局缓存管理器
- from core.utils.cache.manager import cache_manager, CacheType
-
- # 先从缓存获取
- cached_ip_info = cache_manager.get(CacheType.IP_INFO, ip_addr)
- if cached_ip_info is not None:
- return cached_ip_info
-
- # 缓存未命中,调用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")}
-
- # 存入缓存
- cache_manager.set(CacheType.IP_INFO, ip_addr, ip_info)
- return ip_info
+ # Use ip-api.com (reliable and returns JSON)
+ # If local, calling without an IP returns the public IP of your Durham gateway
+ url = "http://ip-api.com/json/" if is_local else f"http://ip-api.com/json/{client_ip}"
+ response = requests.get(url, timeout=5).json()
+
+ if response.get("status") == "success":
+ return {
+ "city": response.get("city"),
+ "lat": response.get("lat"),
+ "lon": response.get("lon"),
+ "region": response.get("regionName")
+ }
except Exception as e:
- logger.bind(tag=TAG).error(f"Error getting client ip info: {e}")
- return {}
-
+ if logger: logger.error(f"GeoIP Lookup failed: {e}")
+ return None
def write_json_file(file_path, data):
- """将数据写入 JSON 文件"""
+ """Write data to JSON file"""
with open(file_path, "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=4)
def remove_punctuation_and_length(text):
- # 全角符号和半角符号的Unicode范围
+ # Unicode range for full-width and half-width punctuation
full_width_punctuations = (
"!"#$%&'()*+,-。/:;<=>?@[\]^_`{|}~"
)
half_width_punctuations = r'!"#$%&\'()*+,-./:;<=>?@[\]^_`{|}~'
- space = " " # 半角空格
- full_width_space = " " # 全角空格
+ space = " " # Half-width space
+ full_width_space = " " # Full-width space
- # 去除全角和半角符号以及空格
+ # Remove full-width and half-width punctuation and spaces
result = "".join(
[
char
for char in text
if char not in full_width_punctuations
and char not in half_width_punctuations
- and char not in space
- and char not in full_width_space
]
)
- if result == "Yeah":
+ # Aggressive filtering for "Yeah", "I", "I." and variants
+ cleaned = result.strip().lower()
+ if cleaned in ["yeah", "yeah.", "i", "i."]:
return 0, ""
+
return len(result), result
+def check_for_noise(pcm_data: bytes) -> bool:
+ """
+ Check if audio data is likely noise/silence based on energy.
+ Criteria:
+ 1. Total Energy ave(sum of squares) < 600
+ 2. Max value < 1000
+ """
+ if not pcm_data:
+ return True
+
+ ms_threshold = 600.0
+ # Convert to 16-bit integers
+ samples = np.frombuffer(pcm_data, dtype=np.int16)
+
+ # Energy = mean(sample^2)
+ # Using astype(np.float64) to ensure precision and avoid overflow
+ energy = np.mean(samples.astype(np.float64) ** 2)
+ if energy < ms_threshold:
+ return True
+
+ max_threshold = 1000
+ # Check absolute max value (amplitude)
+ maxvalue = np.max(np.abs(samples))
+ if maxvalue < max_threshold:
+ return True
+
+ return False
+
+
def check_model_key(modelType, modelKey):
if "你" in modelKey:
- return f"配置错误: {modelType} 的 API key 未设置,当前值为: {modelKey}"
+ return f"Config error: API key for {modelType} not set, current value: {modelKey}"
return None
def parse_string_to_list(value, separator=";"):
"""
- 将输入值转换为列表
+ Convert input value to list
Args:
- value: 输入值,可以是 None、字符串或列表
- separator: 分隔符,默认为分号
+ value: Input value, can be None, string or list
+ separator: Separator, default is semicolon
Returns:
- list: 处理后的列表
+ list: Processed list
"""
if value is None or value == "":
return []
@@ -156,92 +187,94 @@ def parse_string_to_list(value, separator=";"):
def check_ffmpeg_installed() -> bool:
"""
- 检查当前环境中是否已正确安装并可执行 ffmpeg。
+ Check if ffmpeg is correctly installed and executable in the current environment.
Returns:
- bool: 如果 ffmpeg 正常可用,返回 True;否则抛出 ValueError 异常。
+ bool: Returns True if ffmpeg is available; otherwise raises ValueError.
Raises:
- ValueError: 当检测到 ffmpeg 未安装或依赖缺失时,抛出详细的提示信息。
+ ValueError: Raises detailed error message when ffmpeg is not installed or dependencies are missing.
"""
try:
- # 尝试执行 ffmpeg 命令
+ # Try to execute ffmpeg command
result = subprocess.run(
["ffmpeg", "-version"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
- check=True, # 非零退出码会触发 CalledProcessError
+ check=True, # Non-zero exit code triggers CalledProcessError
)
output = (result.stdout + result.stderr).lower()
if "ffmpeg version" in output:
return True
- # 如果未检测到版本信息,也视为异常情况
- raise ValueError("未检测到有效的 ffmpeg 版本输出。")
+ # If version info not detected, consider as exception
+ raise ValueError("No valid ffmpeg version output detected.")
except (subprocess.CalledProcessError, FileNotFoundError) as e:
- # 提取错误输出
+ # Extract error output
stderr_output = ""
if isinstance(e, subprocess.CalledProcessError):
stderr_output = (e.stderr or "").strip()
else:
stderr_output = str(e).strip()
- # 构建基础错误提示
+ # Build basic error message
error_msg = [
- "❌ 检测到 ffmpeg 无法正常运行。\n",
- "建议您:",
- "1. 确认已正确激活 conda 环境;",
- "2. 查阅项目安装文档,了解如何在 conda 环境中安装 ffmpeg。\n",
+ "❌ FFmpeg cannot run normally.\n",
+ "Suggestion:",
+ "1. Ensure conda environment is activated correctly;",
+ "2. Refer to project installation docs to install ffmpeg in conda environment.\n",
]
- # 🎯 针对具体错误信息提供额外提示
+ # 🎯 Provide extra tips for specific error messages
if "libiconv.so.2" in stderr_output:
- error_msg.append("⚠️ 发现缺少依赖库:libiconv.so.2")
- error_msg.append("解决方法:在当前 conda 环境中执行:")
+ error_msg.append("⚠️ Missing dependency: libiconv.so.2")
+ error_msg.append("Solution: Run in current conda environment:")
error_msg.append(" conda install -c conda-forge libiconv\n")
elif (
"no such file or directory" in stderr_output
and "ffmpeg" in stderr_output.lower()
):
- error_msg.append("⚠️ 系统未找到 ffmpeg 可执行文件。")
- error_msg.append("解决方法:在当前 conda 环境中执行:")
+ error_msg.append("⚠️ FFmpeg executable not found.")
+ error_msg.append("Solution: Run in current conda environment:")
error_msg.append(" conda install -c conda-forge ffmpeg\n")
else:
- error_msg.append("错误详情:")
- error_msg.append(stderr_output or "未知错误。")
+ error_msg.append("Error details:")
+ error_msg.append(stderr_output or "Unknown error.")
- # 抛出详细异常信息
+ # Raise detailed exception info
raise ValueError("\n".join(error_msg)) from e
def extract_json_from_string(input_string):
- """提取字符串中的 JSON 部分"""
+ """Extract JSON part from string"""
pattern = r"(\{.*\})"
- match = re.search(pattern, input_string, re.DOTALL) # 添加 re.DOTALL
+ match = re.search(pattern, input_string, re.DOTALL) # Add re.DOTALL
if match:
- return match.group(1) # 返回提取的 JSON 字符串
+ return match.group(1) # Return extracted JSON string
return None
def audio_to_data_stream(
audio_file_path, is_opus=True, callback: Callable[[Any], Any] = None
) -> None:
- # 获取文件后缀名
+ # Get file extension
file_type = os.path.splitext(audio_file_path)[1]
if file_type:
file_type = file_type.lstrip(".")
- # 读取音频文件,-nostdin 参数:不要从标准输入读取数据,否则FFmpeg会阻塞
+ # Read audio file, -nostdin parameter: do not read data from stdin, otherwise FFmpeg will block
audio = AudioSegment.from_file(
audio_file_path, format=file_type, parameters=["-nostdin"]
)
- # 转换为单声道/16kHz采样率/16位小端编码(确保与编码器匹配)
+ # Convert to mono/16kHz sample rate/16-bit little endian (ensure match with encoder)
audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
+ # Append 200ms silence to prevent voxing
+ audio += AudioSegment.silent(duration=200)
- # 获取原始PCM数据(16位小端)
+ # Get raw PCM data (16-bit little endian)
raw_data = audio.raw_data
pcm_to_data_stream(raw_data, is_opus, callback)
@@ -250,61 +283,63 @@ async def audio_to_data(
audio_file_path: str, is_opus: bool = True, use_cache: bool = True
) -> list[bytes]:
"""
- 将音频文件转换为Opus/PCM编码的帧列表
+ Convert audio file to Opus/PCM encoded frame list
Args:
- audio_file_path: 音频文件路径
- is_opus: 是否进行Opus编码
- use_cache: 是否使用缓存
+ audio_file_path: Audio file path
+ is_opus: Whether to perform Opus encoding
+ use_cache: Whether to use cache
"""
from core.utils.cache.manager import cache_manager
from core.utils.cache.config import CacheType
- # 生成缓存键,包含文件路径和编码类型
+ # Generate cache key, including file path and encoding type
cache_key = f"{audio_file_path}:{is_opus}"
- # 尝试从缓存获取结果
+ # Try to get result from cache
if use_cache:
cached_result = cache_manager.get(CacheType.AUDIO_DATA, cache_key)
if cached_result is not None:
return cached_result
def _sync_audio_to_data():
- # 获取文件后缀名
+ # Get file extension
file_type = os.path.splitext(audio_file_path)[1]
if file_type:
file_type = file_type.lstrip(".")
- # 读取音频文件,-nostdin 参数:不要从标准输入读取数据,否则FFmpeg会阻塞
+ # Read audio file, -nostdin parameter: do not read data from stdin, otherwise FFmpeg will block
audio = AudioSegment.from_file(
audio_file_path, format=file_type, parameters=["-nostdin"]
)
- # 转换为单声道/16kHz采样率/16位小端编码(确保与编码器匹配)
+ # Convert to mono/16kHz sample rate/16-bit little endian (ensure match with encoder)
audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
+ # Append 200ms silence to prevent voxing
+ audio += AudioSegment.silent(duration=200)
- # 获取原始PCM数据(16位小端)
+ # Get raw PCM data (16-bit little endian)
raw_data = audio.raw_data
- # 初始化Opus编码器
+ # Initialize Opus encoder
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
- # 编码参数
+ # Encoding parameters
frame_duration = 60 # 60ms per frame
frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame
datas = []
- # 按帧处理所有音频数据(包括最后一帧可能补零)
+ # Process all audio data frame by frame (including padding zero for last frame)
for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample
- # 获取当前帧的二进制数据
+ # Get binary data of current frame
chunk = raw_data[i : i + frame_size * 2]
- # 如果最后一帧不足,补零
+ # If last frame is insufficient, pad with zeros
if len(chunk) < frame_size * 2:
chunk += b"\x00" * (frame_size * 2 - len(chunk))
if is_opus:
- # 转换为numpy数组处理
+ # Convert to numpy array for processing
np_frame = np.frombuffer(chunk, dtype=np.int16)
- # 编码Opus数据
+ # Encode Opus data
frame_data = encoder.encode(np_frame.tobytes(), frame_size)
else:
frame_data = chunk if isinstance(chunk, bytes) else bytes(chunk)
@@ -314,10 +349,10 @@ async def audio_to_data(
return datas
loop = asyncio.get_running_loop()
- # 在单独的线程中执行同步的音频处理操作
+ # Execute synchronous audio processing operations in a separate thread
result = await loop.run_in_executor(None, _sync_audio_to_data)
- # 将结果存入缓存,使用配置中定义的TTL(10分钟)
+ # Save result to cache using TTL defined in config (10 minutes)
if use_cache:
cache_manager.set(CacheType.AUDIO_DATA, cache_key, result)
@@ -328,42 +363,44 @@ def audio_bytes_to_data_stream(
audio_bytes, file_type, is_opus, callback: Callable[[Any], Any]
) -> None:
"""
- 直接用音频二进制数据转为opus/pcm数据,支持wav、mp3、p3
+ Directly convert audio binary data to opus/pcm data, supports wav, mp3, p3
"""
if file_type == "p3":
- # 直接用p3解码
+ # Decode using p3 directly
return p3.decode_opus_from_bytes_stream(audio_bytes, callback)
else:
- # 其他格式用pydub
+ # Use pydub for other formats
audio = AudioSegment.from_file(
BytesIO(audio_bytes), format=file_type, parameters=["-nostdin"]
)
audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
+ # Append 200ms silence to prevent voxing
+ audio += AudioSegment.silent(duration=200)
raw_data = audio.raw_data
pcm_to_data_stream(raw_data, is_opus, callback)
def pcm_to_data_stream(raw_data, is_opus=True, callback: Callable[[Any], Any] = None):
- # 初始化Opus编码器
+ # Initialize Opus encoder
encoder = opuslib_next.Encoder(16000, 1, opuslib_next.APPLICATION_AUDIO)
- # 编码参数
+ # Encoding parameters
frame_duration = 60 # 60ms per frame
frame_size = int(16000 * frame_duration / 1000) # 960 samples/frame
- # 按帧处理所有音频数据(包括最后一帧可能补零)
+ # Process all audio data frame by frame (including padding zero for last frame)
for i in range(0, len(raw_data), frame_size * 2): # 16bit=2bytes/sample
- # 获取当前帧的二进制数据
+ # Get binary data of current frame
chunk = raw_data[i : i + frame_size * 2]
- # 如果最后一帧不足,补零
+ # If last frame is insufficient, pad with zeros
if len(chunk) < frame_size * 2:
chunk += b"\x00" * (frame_size * 2 - len(chunk))
if is_opus:
- # 转换为numpy数组处理
+ # Convert to numpy array for processing
np_frame = np.frombuffer(chunk, dtype=np.int16)
- # 编码Opus数据
+ # Encode Opus data
frame_data = encoder.encode(np_frame.tobytes(), frame_size)
callback(frame_data)
else:
@@ -373,7 +410,7 @@ def pcm_to_data_stream(raw_data, is_opus=True, callback: Callable[[Any], Any] =
def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1):
"""
- 将opus帧列表解码为wav字节流
+ Decode opus frame list to wav byte stream
"""
decoder = opuslib_next.Decoder(sample_rate, channels)
try:
@@ -383,13 +420,13 @@ def opus_datas_to_wav_bytes(opus_datas, sample_rate=16000, channels=1):
frame_size = int(sample_rate * frame_duration / 1000) # 960
for opus_frame in opus_datas:
- # 解码为PCM(返回bytes,2字节/采样点)
+ # Decode to PCM (return bytes, 2 bytes/sample)
pcm = decoder.decode(opus_frame, frame_size)
pcm_datas.append(pcm)
pcm_bytes = b"".join(pcm_datas)
- # 写入wav字节流
+ # Write wav byte stream
wav_buffer = BytesIO()
with wave.open(wav_buffer, "wb") as wf:
wf.setnchannels(channels)
@@ -453,11 +490,11 @@ def check_asr_update(before_config, new_config):
def filter_sensitive_info(config: dict) -> dict:
"""
- 过滤配置中的敏感信息
+ Filter sensitive info in config
Args:
- config: 原始配置字典
+ config: Original config dict
Returns:
- 过滤后的配置字典
+ Filtered config dict
"""
sensitive_keys = [
"api_key",
@@ -497,10 +534,10 @@ def filter_sensitive_info(config: dict) -> dict:
def get_vision_url(config: dict) -> str:
- """获取 vision URL
+ """Get vision URL
Args:
- config: 配置字典
+ config: Config dict
Returns:
str: vision URL
@@ -516,15 +553,15 @@ def get_vision_url(config: dict) -> str:
def is_valid_image_file(file_data: bytes) -> bool:
"""
- 检查文件数据是否为有效的图片格式
+ Check if file data is valid image format
Args:
- file_data: 文件的二进制数据
+ file_data: Binary data of file
Returns:
- bool: 如果是有效的图片格式返回True,否则返回False
+ bool: Return True if valid image format, else False
"""
- # 常见图片格式的魔数(文件头)
+ # Magic numbers for common image formats (file headers)
image_signatures = {
b"\xff\xd8\xff": "JPEG",
b"\x89PNG\r\n\x1a\n": "PNG",
@@ -536,7 +573,7 @@ def is_valid_image_file(file_data: bytes) -> bool:
b"RIFF": "WEBP",
}
- # 检查文件头是否匹配任何已知的图片格式
+ # Check if file header matches any known image formats
for signature in image_signatures:
if file_data.startswith(signature):
return True
@@ -546,30 +583,58 @@ def is_valid_image_file(file_data: bytes) -> bool:
def sanitize_tool_name(name: str) -> str:
"""Sanitize tool names for OpenAI compatibility."""
- # 支持中文、英文字母、数字、下划线和连字符
+ # Supports Chinese, English letters, numbers, underscores and hyphens
return re.sub(r"[^a-zA-Z0-9_\-\u4e00-\u9fff]", "_", name)
def validate_mcp_endpoint(mcp_endpoint: str) -> bool:
"""
- 校验MCP接入点格式
+ Validate MCP endpoint format
Args:
- mcp_endpoint: MCP接入点字符串
+ mcp_endpoint: MCP endpoint string
Returns:
- bool: 是否有效
+ bool: Whether valid
"""
- # 1. 检查是否以ws开头
+ # 1. Check if starts with ws
if not mcp_endpoint.startswith("ws"):
return False
- # 2. 检查是否包含key、call字样
+ # 2. Check if contains key, call words
if "key" in mcp_endpoint.lower() or "call" in mcp_endpoint.lower():
return False
- # 3. 检查是否包含/mcp/字样
+ # 3. Check if contains /mcp/ string
if "/mcp/" not in mcp_endpoint:
return False
return True
+
+def fetch_lat_lon(location):
+ """
+ Resolve city name to Lat/Lon using Open-Meteo Geocoding API (Free).
+ """
+ import requests
+ url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1&language=en&format=json"
+
+ try:
+ # We don't have access to logger here easily without circular import if we init it,
+ # so we'll just print or use logging.getLogger if needed, or rely on caller to log failure if returns None.
+ # But actually we can import setup_logging inside function or at top if not circular.
+ # core/utils/util.py doesn't seem to import config.logger at top (wait, it does line 17? No.)
+ # Let's check imports. line 496 `from config.logger import setup_logging`? No.
+ # We will skip logging inside this util function for simplicity or use print/standard logging if critical.
+ # Actually simplest is just to request content.
+
+ response = requests.get(url, timeout=5)
+
+ if response.status_code == 200:
+ data = response.json()
+ if "results" in data and len(data["results"]) > 0:
+ result = data["results"][0]
+ return result["latitude"], result["longitude"], f"{result['name']}, {result.get('admin1', '')}"
+
+ return None, None, None
+ except Exception:
+ return None, None, None
diff --git a/main/xiaozhi-server/core/utils/vad.py b/main/xiaozhi-server/core/utils/vad.py
index b1dd1faf8..c6d9103b1 100644
--- a/main/xiaozhi-server/core/utils/vad.py
+++ b/main/xiaozhi-server/core/utils/vad.py
@@ -9,11 +9,11 @@ logger = setup_logging()
def create_instance(class_name: str, *args, **kwargs) -> VADProviderBase:
- """工厂方法创建VAD实例"""
+ """Factory method for creating VAD instance"""
if os.path.exists(os.path.join("core", "providers", "vad", f"{class_name}.py")):
lib_name = f"core.providers.vad.{class_name}"
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f"{lib_name}")
return sys.modules[lib_name].VADProvider(*args, **kwargs)
- raise ValueError(f"不支持的VAD类型: {class_name},请检查该配置的type是否设置正确")
+ raise ValueError(f"Unsupported VAD type: {class_name}, please check if the type in config is set correctly")
diff --git a/main/xiaozhi-server/core/utils/vllm.py b/main/xiaozhi-server/core/utils/vllm.py
index 465580f76..d08efece7 100644
--- a/main/xiaozhi-server/core/utils/vllm.py
+++ b/main/xiaozhi-server/core/utils/vllm.py
@@ -1,7 +1,7 @@
import os
import sys
-# 添加项目根目录到Python路径
+# Add project root to Python path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
sys.path.insert(0, project_root)
@@ -13,11 +13,11 @@ logger = setup_logging()
def create_instance(class_name, *args, **kwargs):
- # 创建LLM实例
+ # Create LLM instance
if os.path.exists(os.path.join("core", "providers", "vllm", f"{class_name}.py")):
lib_name = f"core.providers.vllm.{class_name}"
if lib_name not in sys.modules:
sys.modules[lib_name] = importlib.import_module(f"{lib_name}")
return sys.modules[lib_name].VLLMProvider(*args, **kwargs)
- raise ValueError(f"不支持的VLLM类型: {class_name},请检查该配置的type是否设置正确")
+ raise ValueError(f"Unsupported VLLM type: {class_name}, please check if the type is set correctly")
diff --git a/main/xiaozhi-server/core/utils/voiceprint_provider.py b/main/xiaozhi-server/core/utils/voiceprint_provider.py
index ee4f06ca8..7ae4bc364 100644
--- a/main/xiaozhi-server/core/utils/voiceprint_provider.py
+++ b/main/xiaozhi-server/core/utils/voiceprint_provider.py
@@ -13,40 +13,40 @@ logger = setup_logging()
class VoiceprintProvider:
- """声纹识别服务提供者"""
+ """Voiceprint Recognition Service Provider"""
def __init__(self, config: dict):
self.original_url = config.get("url", "")
self.speakers = config.get("speakers", [])
self.speaker_map = self._parse_speakers()
- # 声纹识别相似度阈值,默认0.4
+ # Voiceprint similarity threshold, default 0.4
self.similarity_threshold = float(config.get("similarity_threshold", 0.4))
- # 解析API地址和密钥
+ # Parse API address and key
self.api_url = None
self.api_key = None
self.speaker_ids = []
if not self.original_url:
- logger.bind(tag=TAG).warning("声纹识别URL未配置,声纹识别将被禁用")
+ logger.bind(tag=TAG).warning("Voiceprint recognition URL not configured, voiceprint recognition will be disabled")
self.enabled = False
else:
- # 解析URL和key
+ # Parse URL and key
parsed_url = urlparse(self.original_url)
base_url = f"{parsed_url.scheme}://{parsed_url.netloc}"
- # 从查询参数中提取key
+ # Extract key from query parameters
query_params = parse_qs(parsed_url.query)
self.api_key = query_params.get('key', [''])[0]
if not self.api_key:
- logger.bind(tag=TAG).error("URL中未找到key参数,声纹识别将被禁用")
+ logger.bind(tag=TAG).error("Key parameter not found in URL, voiceprint recognition will be disabled")
self.enabled = False
else:
- # 构造identify接口地址
+ # Construct identify interface address
self.api_url = f"{base_url}/voiceprint/identify"
- # 提取speaker_ids
+ # Extract speaker_ids
for speaker_str in self.speakers:
try:
parts = speaker_str.split(",", 2)
@@ -56,21 +56,21 @@ class VoiceprintProvider:
except Exception:
continue
- # 检查是否有有效的说话人配置
+ # Check if there is valid speaker configuration
if not self.speaker_ids:
- logger.bind(tag=TAG).warning("未配置有效的说话人,声纹识别将被禁用")
+ logger.bind(tag=TAG).warning("No valid speakers configured, voiceprint recognition will be disabled")
self.enabled = False
else:
- # 进行健康检查,验证服务器是否可用
+ # Perform health check, verify if server is available
if self._check_server_health():
self.enabled = True
- logger.bind(tag=TAG).info(f"声纹识别已启用: API={self.api_url}, 说话人={len(self.speaker_ids)}个, 相似度阈值={self.similarity_threshold}")
+ logger.bind(tag=TAG).info(f"Voiceprint recognition enabled: API={self.api_url}, Speakers={len(self.speaker_ids)}, Threshold={self.similarity_threshold}")
else:
self.enabled = False
- logger.bind(tag=TAG).warning(f"声纹识别服务器不可用,声纹识别已禁用: {self.api_url}")
+ logger.bind(tag=TAG).warning(f"Voiceprint recognition server unavailable, disabled: {self.api_url}")
def _parse_speakers(self) -> Dict[str, Dict[str, str]]:
- """解析说话人配置"""
+ """Parse speaker configuration"""
speaker_map = {}
for speaker_str in self.speakers:
try:
@@ -82,84 +82,84 @@ class VoiceprintProvider:
"description": description
}
except Exception as e:
- logger.bind(tag=TAG).warning(f"解析说话人配置失败: {speaker_str}, 错误: {e}")
+ logger.bind(tag=TAG).warning(f"Failed to parse speaker config: {speaker_str}, Error: {e}")
return speaker_map
def _check_server_health(self) -> bool:
- """检查声纹识别服务器健康状态"""
+ """Check voiceprint recognition server health status"""
if not self.api_url or not self.api_key:
return False
cache_key = f"{self.api_url}:{self.api_key}"
- # 检查缓存
+ # Check cache
cached_result = cache_manager.get(CacheType.VOICEPRINT_HEALTH, cache_key)
if cached_result is not None:
- logger.bind(tag=TAG).debug(f"使用缓存的健康状态: {cached_result}")
+ logger.bind(tag=TAG).debug(f"Using cached health status: {cached_result}")
return cached_result
- # 缓存过期或不存在
- logger.bind(tag=TAG).info("执行声纹服务器健康检查")
+ # Cache expired or not exists
+ logger.bind(tag=TAG).info("Executing voiceprint server health check")
try:
- # 健康检查URL
+ # Health check URL
parsed_url = urlparse(self.api_url)
health_url = f"{parsed_url.scheme}://{parsed_url.netloc}/voiceprint/health?key={self.api_key}"
- # 发送健康检查请求
+ # Send health check request
response = requests.get(health_url, timeout=3)
if response.status_code == 200:
result = response.json()
if result.get("status") == "healthy":
- logger.bind(tag=TAG).info("声纹识别服务器健康检查通过")
+ logger.bind(tag=TAG).info("Voiceprint recognition server health check passed")
is_healthy = True
else:
- logger.bind(tag=TAG).warning(f"声纹识别服务器状态异常: {result}")
+ logger.bind(tag=TAG).warning(f"Voiceprint recognition server status abnormal: {result}")
is_healthy = False
else:
- logger.bind(tag=TAG).warning(f"声纹识别服务器健康检查失败: HTTP {response.status_code}")
+ logger.bind(tag=TAG).warning(f"Voiceprint recognition server health check failed: HTTP {response.status_code}")
is_healthy = False
except requests.exceptions.ConnectTimeout:
- logger.bind(tag=TAG).warning("声纹识别服务器连接超时")
+ logger.bind(tag=TAG).warning("Voiceprint recognition server connection timeout")
is_healthy = False
except requests.exceptions.ConnectionError:
- logger.bind(tag=TAG).warning("声纹识别服务器连接被拒绝")
+ logger.bind(tag=TAG).warning("Voiceprint recognition server connection refused")
is_healthy = False
except Exception as e:
- logger.bind(tag=TAG).warning(f"声纹识别服务器健康检查异常: {e}")
+ logger.bind(tag=TAG).warning(f"Voiceprint recognition server health check exception: {e}")
is_healthy = False
- # 使用全局缓存管理器缓存结果
+ # Cache result using global cache manager
cache_manager.set(CacheType.VOICEPRINT_HEALTH, cache_key, is_healthy)
- logger.bind(tag=TAG).info(f"健康检查结果已缓存: {is_healthy}")
+ logger.bind(tag=TAG).info(f"Health check result cached: {is_healthy}")
return is_healthy
async def identify_speaker(self, audio_data: bytes, session_id: str) -> Optional[str]:
- """识别说话人"""
+ """Identify speaker"""
if not self.enabled or not self.api_url or not self.api_key:
- logger.bind(tag=TAG).debug("声纹识别功能已禁用或未配置,跳过识别")
+ logger.bind(tag=TAG).debug("Voiceprint recognition disabled or not configured, skipping identification")
return None
try:
api_start_time = time.monotonic()
- # 准备请求头
+ # Prepare request headers
headers = {
'Authorization': f'Bearer {self.api_key}',
'Accept': 'application/json'
}
- # 准备multipart/form-data数据
+ # Prepare multipart/form-data
data = aiohttp.FormData()
data.add_field('speaker_ids', ','.join(self.speaker_ids))
data.add_field('file', audio_data, filename='audio.wav', content_type='audio/wav')
timeout = aiohttp.ClientTimeout(total=10)
- # 网络请求
+ # Network request
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(self.api_url, headers=headers, data=data) as response:
@@ -169,30 +169,30 @@ class VoiceprintProvider:
score = result.get("score", 0)
total_elapsed_time = time.monotonic() - api_start_time
- logger.bind(tag=TAG).info(f"声纹识别耗时: {total_elapsed_time:.3f}s")
+ logger.bind(tag=TAG).info(f"Voiceprint recognition duration: {total_elapsed_time:.3f}s")
- # 相似度阈值检查
+ # Similarity threshold check
if score < self.similarity_threshold:
- logger.bind(tag=TAG).warning(f"声纹识别相似度{score:.3f}低于阈值{self.similarity_threshold}")
- return "未知说话人"
+ logger.bind(tag=TAG).warning(f"Voiceprint similarity {score:.3f} below threshold {self.similarity_threshold}")
+ return "Unknown Speaker"
if speaker_id and speaker_id in self.speaker_map:
result_name = self.speaker_map[speaker_id]["name"]
- logger.bind(tag=TAG).info(f"声纹识别成功: {result_name} (相似度: {score:.3f})")
+ logger.bind(tag=TAG).info(f"Voiceprint recognition success: {result_name} (Similarity: {score:.3f})")
return result_name
else:
- logger.bind(tag=TAG).warning(f"未识别的说话人ID: {speaker_id}")
- return "未知说话人"
+ logger.bind(tag=TAG).warning(f"Unrecognized speaker ID: {speaker_id}")
+ return "Unknown Speaker"
else:
- logger.bind(tag=TAG).error(f"声纹识别API错误: HTTP {response.status}")
+ logger.bind(tag=TAG).error(f"Voiceprint recognition API error: HTTP {response.status}")
return None
except asyncio.TimeoutError:
elapsed = time.monotonic() - api_start_time
- logger.bind(tag=TAG).error(f"声纹识别超时: {elapsed:.3f}s")
+ logger.bind(tag=TAG).error(f"Voiceprint recognition timeout: {elapsed:.3f}s")
return None
except Exception as e:
elapsed = time.monotonic() - api_start_time
- logger.bind(tag=TAG).error(f"声纹识别失败: {e}")
+ logger.bind(tag=TAG).error(f"Voiceprint recognition failed: {e}")
return None
diff --git a/main/xiaozhi-server/core/utils/wakeup_word.py b/main/xiaozhi-server/core/utils/wakeup_word.py
index 93d4e6b84..776ad07a9 100644
--- a/main/xiaozhi-server/core/utils/wakeup_word.py
+++ b/main/xiaozhi-server/core/utils/wakeup_word.py
@@ -21,7 +21,7 @@ class FileLock:
return self.file
except portalocker.LockException:
if time.time() - self.start_time > self.timeout:
- raise TimeoutError("获取文件锁超时")
+ raise TimeoutError("Acquiring file lock timeout")
time.sleep(0.1)
def __exit__(self, exc_type, exc_val, exc_tb):
@@ -35,19 +35,19 @@ class WakeupWordsConfig:
self._ensure_directories()
self._config_cache = None
self._last_load_time = 0
- self._cache_ttl = 1 # 缓存有效期(秒)
- self._lock_timeout = 5 # 文件锁超时时间(秒)
+ self._cache_ttl = 1 # Cache time to live (seconds)
+ self._lock_timeout = 5 # File lock timeout (seconds)
def _ensure_directories(self):
- """确保必要的目录存在"""
+ """Ensure necessary directories exist"""
os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
os.makedirs(self.assets_dir, exist_ok=True)
def _load_config(self) -> Dict:
- """加载配置文件,使用缓存机制"""
+ """Load configuration file, using cache mechanism"""
current_time = time.time()
- # 如果缓存有效,直接返回缓存
+ # If cache is valid, return cache directly
if (
self._config_cache is not None
and current_time - self._last_load_time < self._cache_ttl
@@ -64,14 +64,14 @@ class WakeupWordsConfig:
self._last_load_time = current_time
return config
except (TimeoutError, IOError) as e:
- print(f"加载配置文件失败: {e}")
+ print(f"Failed to load config file: {e}")
return {}
except Exception as e:
- print(f"加载配置文件时发生未知错误: {e}")
+ print(f"Unknown error occurred while loading config file: {e}")
return {}
def _save_config(self, config: Dict):
- """保存配置到文件,使用文件锁保护"""
+ """Save configuration to file, protected by file lock"""
try:
with open(self.config_file, "w", encoding="utf-8") as f:
with FileLock(f, timeout=self._lock_timeout):
@@ -79,21 +79,21 @@ class WakeupWordsConfig:
self._config_cache = config
self._last_load_time = time.time()
except (TimeoutError, IOError) as e:
- print(f"保存配置文件失败: {e}")
+ print(f"Failed to save config file: {e}")
raise
except Exception as e:
- print(f"保存配置文件时发生未知错误: {e}")
+ print(f"Unknown error occurred while saving config file: {e}")
raise
def get_wakeup_response(self, voice: str) -> Dict:
voice = hashlib.md5(voice.encode()).hexdigest()
- """获取唤醒词回复配置"""
+ """Get wakeup word response configuration"""
config = self._load_config()
if not config or voice not in config:
return None
- # 检查文件大小
+ # Check file size
file_path = config[voice]["file_path"]
if not os.path.exists(file_path) or os.stat(file_path).st_size < (15 * 1024):
return None
@@ -101,9 +101,9 @@ class WakeupWordsConfig:
return config[voice]
def update_wakeup_response(self, voice: str, file_path: str, text: str):
- """更新唤醒词回复配置"""
+ """Update wakeup word response configuration"""
try:
- # 过滤表情符号
+ # Filter emojis
filtered_text = re.sub(r'[\U0001F600-\U0001F64F\U0001F900-\U0001F9FF]', '', text)
config = self._load_config()
@@ -116,25 +116,25 @@ class WakeupWordsConfig:
}
self._save_config(config)
except Exception as e:
- print(f"更新唤醒词回复配置失败: {e}")
+ print(f"Failed to update wakeup word response config: {e}")
raise
def generate_file_path(self, voice: str) -> str:
- """生成音频文件路径,使用voice的哈希值作为文件名"""
+ """Generate audio file path, using hex digest of voice as filename"""
try:
- # 生成voice的哈希值
+ # Generate MD5 hash of voice
voice_hash = hashlib.md5(voice.encode()).hexdigest()
file_path = os.path.join(self.assets_dir, f"{voice_hash}.wav")
- # 如果文件已存在,先删除
+ # If file already exists, delete it first
if os.path.exists(file_path):
try:
os.remove(file_path)
except Exception as e:
- print(f"删除已存在的音频文件失败: {e}")
+ print(f"Failed to delete existing audio file: {e}")
raise
return file_path
except Exception as e:
- print(f"生成音频文件路径失败: {e}")
+ print(f"Failed to generate audio file path: {e}")
raise
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/utils/web_search.py b/main/xiaozhi-server/core/utils/web_search.py
new file mode 100644
index 000000000..b7bfc4e65
--- /dev/null
+++ b/main/xiaozhi-server/core/utils/web_search.py
@@ -0,0 +1,46 @@
+from ddgs import DDGS
+from config.logger import setup_logging
+
+TAG = "web_search"
+logger = setup_logging()
+
+class WebSearch:
+ def __init__(self, config: dict):
+ self.config = config
+ self.plugin_config = config.get("plugins", {}).get("web_search", {})
+ self.count = self.plugin_config.get("count", 5)
+
+ def search(self, query: str) -> str:
+ """Perform a web search using DuckDuckGo (via ddgs) and return a formatted string of results."""
+ logger.bind(tag=TAG).info(f"Searching DuckDuckGo for: {query}")
+ try:
+ results = []
+ with DDGS(timeout=10) as ddgs:
+ ddgs_gen = ddgs.text(query, max_results=self.count)
+ for r in ddgs_gen:
+ results.append(r)
+
+ logger.bind(tag=TAG).info(f"DuckDuckGo found {len(results)} results")
+
+ if not results:
+ logger.bind(tag=TAG).warning(f"No results found for query: {query}")
+ return "No search results found via DuckDuckGo."
+
+ formatted_results = []
+ for i, res in enumerate(results):
+ title = res.get("title", "No Title")
+ url = res.get("href", "No URL")
+ snippet = res.get("body", "No Snippet")
+ logger.bind(tag=TAG).debug(f"Result {i+1}: {title} ({url})")
+ formatted_results.append(f"Title: {title}\nURL: {url}\nSnippet: {snippet}")
+
+ return "\n\n\n" + "\n---\n".join(formatted_results) + "\n \n"
+
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"DuckDuckGo search failed for query '{query}': {e}")
+ return f"Search failed (DuckDuckGo): {str(e)}"
+
+def perform_web_search(query: str, config: dict) -> str:
+ """Helper function to perform web search."""
+ searcher = WebSearch(config)
+ return searcher.search(query)
diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py
index 168b436e0..72876f698 100644
--- a/main/xiaozhi-server/core/websocket_server.py
+++ b/main/xiaozhi-server/core/websocket_server.py
@@ -6,7 +6,7 @@ from config.logger import setup_logging
class SuppressInvalidHandshakeFilter(logging.Filter):
- """过滤掉无效握手错误日志(如HTTPS访问WS端口)"""
+ """Filter out invalid handshake error logs (e.g. HTTPS access to WS port)"""
def filter(self, record):
msg = record.getMessage()
@@ -20,7 +20,7 @@ class SuppressInvalidHandshakeFilter(logging.Filter):
def _setup_websockets_logger():
- """配置 websockets 相关的所有 logger,过滤无效握手错误"""
+ """Configure all websockets related loggers, filter invalid handshake errors"""
filter_instance = SuppressInvalidHandshakeFilter()
for logger_name in ["websockets", "websockets.server", "websockets.client"]:
logger = logging.getLogger(logger_name)
@@ -50,19 +50,20 @@ class WebSocketServer:
"VAD" in self.config["selected_module"],
"ASR" in self.config["selected_module"],
"LLM" in self.config["selected_module"],
- False,
+ "TTS" in self.config["selected_module"],
"Memory" in self.config["selected_module"],
"Intent" in self.config["selected_module"],
)
self._vad = modules["vad"] if "vad" in modules else None
self._asr = modules["asr"] if "asr" in modules else None
+ self._tts = modules["tts"] if "tts" in modules else None
self._llm = modules["llm"] if "llm" in modules else None
- self._intent = modules["intent"] if "intent" in modules else None
+ self._intent = modules["Intent"] if "Intent" in modules else None
self._memory = modules["memory"] if "memory" in modules else None
auth_config = self.config["server"].get("auth", {})
self.auth_enable = auth_config.get("enabled", False)
- # 设备白名单
+ # Device whitelist
self.allowed_devices = set(auth_config.get("allowed_devices", []))
secret_key = self.config["server"]["auth_key"]
expire_seconds = auth_config.get("expire_seconds", None)
@@ -73,27 +74,47 @@ class WebSocketServer:
host = server_config.get("ip", "0.0.0.0")
port = int(server_config.get("port", 8000))
+ import ssl
+ import os
+
+ ssl_context = None
+ ssl_cert = server_config.get("ssl_cert")
+ ssl_key = server_config.get("ssl_key")
+
+ if ssl_cert and ssl_key:
+ if os.path.exists(ssl_cert) and os.path.exists(ssl_key):
+ ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ ssl_context.load_cert_chain(certfile=ssl_cert, keyfile=ssl_key)
+ self.logger.bind(tag=TAG).info(f"WSS (SSL) enabled using {ssl_cert}")
+ else:
+ self.logger.bind(tag=TAG).error(f"SSL cert/key files not found: {ssl_cert}, {ssl_key}")
+
async with websockets.serve(
- self._handle_connection, host, port, process_request=self._http_response
+ self._handle_connection,
+ host,
+ port,
+ process_request=self._http_response,
+ ssl=ssl_context
):
await asyncio.Future()
async def _handle_connection(self, websocket):
headers = dict(websocket.request.headers)
if headers.get("device-id", None) is None:
- # 尝试从 URL 的查询参数中获取 device-id
+ # Try to get device-id from URL query parameters
from urllib.parse import parse_qs, urlparse
- # 从 WebSocket 请求中获取路径
+ # Get path from WebSocket request
request_path = websocket.request.path
if not request_path:
- self.logger.bind(tag=TAG).error("无法获取请求路径")
+ self.logger.bind(tag=TAG).error("Unable to get request path")
await websocket.close()
return
parsed_url = urlparse(request_path)
query_params = parse_qs(parsed_url.query)
if "device-id" not in query_params:
- await websocket.send("端口正常,如需测试连接,请使用test_page.html")
+# await websocket.send("Port is working normally. To test connection, please use test_page.html")
+ await websocket.send("The port is working. To test use... test_page.html")
await websocket.close()
return
else:
@@ -105,76 +126,77 @@ class WebSocketServer:
"authorization"
][0]
- """处理新连接,每次创建独立的ConnectionHandler"""
- # 先认证,后建立连接
+ """Handle new connection, create independent ConnectionHandler each time"""
+ # Authenticate first, then establish connection
try:
await self._handle_auth(websocket)
except AuthenticationError:
- await websocket.send("认证失败")
+ await websocket.send("Authentication failed")
await websocket.close()
return
- # 创建ConnectionHandler时传入当前server实例
+ # Pass current server instance when creating ConnectionHandler
handler = ConnectionHandler(
self.config,
self._vad,
self._asr,
+ self._tts,
self._llm,
self._memory,
self._intent,
- self, # 传入server实例
+ self, # Pass server instance
)
try:
await handler.handle_connection(websocket)
except Exception as e:
- self.logger.bind(tag=TAG).error(f"处理连接时出错: {e}")
+ self.logger.bind(tag=TAG).error(f"Error handling connection: {e}")
finally:
- # 强制关闭连接(如果还没有关闭的话)
+ # Force close connection (if not already closed)
try:
- # 安全地检查WebSocket状态并关闭
+ # Safely check WebSocket state and close
if hasattr(websocket, "closed") and not websocket.closed:
await websocket.close()
elif hasattr(websocket, "state") and websocket.state.name != "CLOSED":
await websocket.close()
else:
- # 如果没有closed属性,直接尝试关闭
+ # If no closed attribute, try to close directly
await websocket.close()
except Exception as close_error:
self.logger.bind(tag=TAG).error(
- f"服务器端强制关闭连接时出错: {close_error}"
+ f"Error during server forced connection close: {close_error}"
)
async def _http_response(self, websocket, request_headers):
- # 检查是否为 WebSocket 升级请求
+ # Check if it is a WebSocket upgrade request
if request_headers.headers.get("connection", "").lower() == "upgrade":
- # 如果是 WebSocket 请求,返回 None 允许握手继续
+ # If it is a WebSocket request, return None to allow handshake to continue
return None
else:
- # 如果是普通 HTTP 请求,返回 "server is running"
+ # If it is a normal HTTP request, return "server is running"
return websocket.respond(200, "Server is running\n")
async def update_config(self) -> bool:
- """更新服务器配置并重新初始化组件
+ """Update server configuration and re-initialize components
Returns:
- bool: 更新是否成功
+ bool: Whether update was successful
"""
try:
async with self.config_lock:
- # 重新获取配置(使用异步版本)
+ # Re-fetch auth (use async version)
new_config = await get_config_from_api_async(self.config)
if new_config is None:
- self.logger.bind(tag=TAG).error("获取新配置失败")
+ self.logger.bind(tag=TAG).error("Failed to fetch new config")
return False
- self.logger.bind(tag=TAG).info(f"获取新配置成功")
- # 检查 VAD 和 ASR 类型是否需要更新
+ self.logger.bind(tag=TAG).info(f"Fetch new config success")
+ # Check if VAD and ASR types need update
update_vad = check_vad_update(self.config, new_config)
update_asr = check_asr_update(self.config, new_config)
self.logger.bind(tag=TAG).info(
- f"检查VAD和ASR类型是否需要更新: {update_vad} {update_asr}"
+ f"Check if VAD and ASR types need update: {update_vad} {update_asr}"
)
- # 更新配置
+ # Update config
self.config = new_config
- # 重新初始化组件
+ # Re-initialize components
modules = initialize_modules(
self.logger,
new_config,
@@ -186,40 +208,40 @@ class WebSocketServer:
"Intent" in new_config["selected_module"],
)
- # 更新组件实例
+ # Update component instances
if "vad" in modules:
self._vad = modules["vad"]
if "asr" in modules:
self._asr = modules["asr"]
if "llm" in modules:
self._llm = modules["llm"]
- if "intent" in modules:
- self._intent = modules["intent"]
+ if "Intent" in modules:
+ self._intent = modules["Intent"]
if "memory" in modules:
self._memory = modules["memory"]
- self.logger.bind(tag=TAG).info(f"更新配置任务执行完毕")
+ self.logger.bind(tag=TAG).info(f"Config update task completed")
return True
except Exception as e:
- self.logger.bind(tag=TAG).error(f"更新服务器配置失败: {str(e)}")
+ self.logger.bind(tag=TAG).error(f"Failed to update server config: {str(e)}")
return False
async def _handle_auth(self, websocket):
- # 先认证,后建立连接
+ # Authenticate first, then establish connection
if self.auth_enable:
headers = dict(websocket.request.headers)
device_id = headers.get("device-id", None)
client_id = headers.get("client-id", None)
if self.allowed_devices and device_id in self.allowed_devices:
- # 如果属于白名单内的设备,不校验token,直接放行
+ # If in allowable devices list, skip token check
return
else:
- # 否则校验token
+ # Otherwise, check token
token = headers.get("authorization", "")
if token.startswith("Bearer "):
- token = token[7:] # 移除'Bearer '前缀
+ token = token[7:] # Remove 'Bearer ' prefix
else:
raise AuthenticationError("Missing or invalid Authorization header")
- # 进行认证
+ # Authenticate
auth_success = self.auth.verify_token(
token, client_id=client_id, username=device_id
)
diff --git a/main/xiaozhi-server/inspect_npr.py b/main/xiaozhi-server/inspect_npr.py
new file mode 100644
index 000000000..fe35bf2b6
--- /dev/null
+++ b/main/xiaozhi-server/inspect_npr.py
@@ -0,0 +1,49 @@
+import requests
+from bs4 import BeautifulSoup
+
+base_url = "https://text.npr.org"
+target_title = "In one south Minneapolis neighborhood, tragedy repeats but connection endures"
+
+try:
+ # 1. Fetch Home to find link
+ print(f"Fetching home: {base_url}")
+ resp = requests.get(base_url)
+ soup = BeautifulSoup(resp.text, 'html.parser')
+
+ links = soup.find_all("a", class_="topic-title")
+ target_url = None
+ for link in links:
+ if target_title.lower() in link.get_text().strip().lower():
+ href = link.get('href')
+ if not href.startswith("http"):
+ target_url = base_url + href
+ else:
+ target_url = href
+ print(f"Found URL: {target_url}")
+ break
+
+ if not target_url:
+ print("Could not find article on home page. Trying to fetch a known recent ID if possible, or just fail.")
+ # Fallback: User might have meant an article that was there.
+ # If I can't find it, I will inspect a general article with transcript.
+ # But let's assume it's there since the user just mentioned it.
+
+ if target_url:
+ # 2. Fetch Article
+ print(f"Fetching article: {target_url}")
+ art_resp = requests.get(target_url)
+ art_soup = BeautifulSoup(art_resp.text, 'html.parser')
+
+ # 3. Print structure around "Transcript"
+ # We look for any tag containing "Transcript"
+ print("\n--- Searching for 'Transcript' in tags ---")
+ for tag in art_soup.find_all(string=lambda t: "Transcript" in str(t)):
+ parent = tag.parent
+ print(f"Tag: {parent.name}, Text: '{parent.get_text()}'")
+ print(f"Parent Class: {parent.get('class')}")
+ # print surrounding HTML
+ print(f"HTML: {parent}")
+ print("-" * 20)
+
+except Exception as e:
+ print(e)
diff --git a/main/xiaozhi-server/list_voices.py b/main/xiaozhi-server/list_voices.py
new file mode 100644
index 000000000..ebbf70d28
--- /dev/null
+++ b/main/xiaozhi-server/list_voices.py
@@ -0,0 +1,11 @@
+import asyncio
+import edge_tts
+
+async def list_voices():
+ voices = await edge_tts.VoicesManager.create()
+ en_gb_voices = voices.find(Language="en", Locale="en-GB")
+ for v in en_gb_voices:
+ print(f"{v['ShortName']} ({v['Gender']})")
+
+if __name__ == "__main__":
+ asyncio.run(list_voices())
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/.msc b/main/xiaozhi-server/models/iic/SenseVoiceSmall/.msc
new file mode 100644
index 000000000..dac1a281b
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/.msc differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/.mv b/main/xiaozhi-server/models/iic/SenseVoiceSmall/.mv
new file mode 100644
index 000000000..81e82dda3
--- /dev/null
+++ b/main/xiaozhi-server/models/iic/SenseVoiceSmall/.mv
@@ -0,0 +1 @@
+Revision:master,CreatedAt:1727321787
\ No newline at end of file
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/README.md b/main/xiaozhi-server/models/iic/SenseVoiceSmall/README.md
new file mode 100644
index 000000000..04792495c
--- /dev/null
+++ b/main/xiaozhi-server/models/iic/SenseVoiceSmall/README.md
@@ -0,0 +1,219 @@
+---
+frameworks:
+- Pytorch
+license: Apache License 2.0
+tasks:
+- auto-speech-recognition
+
+#model-type:
+##如 gpt、phi、llama、chatglm、baichuan 等
+#- gpt
+
+#domain:
+##如 nlp、cv、audio、multi-modal
+#- nlp
+
+#language:
+##语言代码列表 https://help.aliyun.com/document_detail/215387.html?spm=a2c4g.11186623.0.0.9f8d7467kni6Aa
+#- cn
+
+#metrics:
+##如 CIDEr、Blue、ROUGE 等
+#- CIDEr
+
+#tags:
+##各种自定义,包括 pretrained、fine-tuned、instruction-tuned、RL-tuned 等训练方法和其他
+#- pretrained
+
+#tools:
+##如 vllm、fastchat、llamacpp、AdaSeq 等
+#- vllm
+---
+
+# Highlights
+**SenseVoice**专注于高精度多语言语音识别、情感辨识和音频事件检测
+- **多语言识别:** 采用超过40万小时数据训练,支持超过50种语言,识别效果上优于Whisper模型。
+- **富文本识别:**
+ - 具备优秀的情感识别,能够在测试数据上达到和超过目前最佳情感识别模型的效果。
+ - 支持声音事件检测能力,支持音乐、掌声、笑声、哭声、咳嗽、喷嚏等多种常见人机交互事件进行检测。
+- **高效推理:** SenseVoice-Small模型采用非自回归端到端框架,推理延迟极低,10s音频推理仅耗时70ms,15倍优于Whisper-Large。
+- **微调定制:** 具备便捷的微调脚本与策略,方便用户根据业务场景修复长尾样本问题。
+- **服务部署:** 具有完整的服务部署链路,支持多并发请求,支持客户端语言有,python、c++、html、java与c#等。
+
+
+## [SenseVoice开源项目介绍](https://github.com/FunAudioLLM/SenseVoice)
+[SenseVoice](https://github.com/FunAudioLLM/SenseVoice) 开源模型是多语言音频理解模型,具有包括语音识别、语种识别、语音情感识别,声学事件检测能力。
+
+[**github仓库**](https://github.com/FunAudioLLM/SenseVoice)
+| [**最新动态**](https://github.com/FunAudioLLM/SenseVoice/blob/main/README_zh.md#%E6%9C%80%E6%96%B0%E5%8A%A8%E6%80%81)
+| [**环境安装**](https://github.com/FunAudioLLM/SenseVoice/blob/main/README_zh.md#%E7%8E%AF%E5%A2%83%E5%AE%89%E8%A3%85)
+
+# 模型结构图
+SenseVoice多语言音频理解模型,支持语音识别、语种识别、语音情感识别、声学事件检测、逆文本正则化等能力,采用工业级数十万小时的标注音频进行模型训练,保证了模型的通用识别效果。模型可以被应用于中文、粤语、英语、日语、韩语音频识别,并输出带有情感和事件的富文本转写结果。
+
+
+
+
+
+SenseVoice-Small是基于非自回归端到端框架模型,为了指定任务,我们在语音特征前添加四个嵌入作为输入传递给编码器:
+- LID:用于预测音频语种标签。
+- SER:用于预测音频情感标签。
+- AED:用于预测音频包含的事件标签。
+- ITN:用于指定识别输出文本是否进行逆文本正则化。
+
+
+# 依赖环境
+
+推理之前,请务必更新funasr与modelscope版本
+
+```shell
+pip install -U funasr modelscope
+```
+
+# 用法
+
+
+## 推理
+
+### modelscope pipeline推理
+```python
+from modelscope.pipelines import pipeline
+from modelscope.utils.constant import Tasks
+
+inference_pipeline = pipeline(
+ task=Tasks.auto_speech_recognition,
+ model='iic/SenseVoiceSmall',
+ model_revision="master",
+ device="cuda:0",)
+
+rec_result = inference_pipeline('https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav')
+print(rec_result)
+```
+
+### 使用funasr推理
+
+支持任意格式音频输入,支持任意时长输入
+
+```python
+from funasr import AutoModel
+from funasr.utils.postprocess_utils import rich_transcription_postprocess
+
+model_dir = "iic/SenseVoiceSmall"
+
+
+model = AutoModel(
+ model=model_dir,
+ trust_remote_code=True,
+ remote_code="./model.py",
+ vad_model="fsmn-vad",
+ vad_kwargs={"max_single_segment_time": 30000},
+ device="cuda:0",
+)
+
+# en
+res = model.generate(
+ input=f"{model.model_path}/example/en.mp3",
+ cache={},
+ language="auto", # "zn", "en", "yue", "ja", "ko", "nospeech"
+ use_itn=True,
+ batch_size_s=60,
+ merge_vad=True, #
+ merge_length_s=15,
+)
+text = rich_transcription_postprocess(res[0]["text"])
+print(text)
+```
+参数说明:
+- `model_dir`:模型名称,或本地磁盘中的模型路径。
+- `trust_remote_code`:
+ - `True`表示model代码实现从`remote_code`处加载,`remote_code`指定`model`具体代码的位置(例如,当前目录下的`model.py`),支持绝对路径与相对路径,以及网络url。
+ - `False`表示,model代码实现为 [FunASR](https://github.com/modelscope/FunASR) 内部集成版本,此时修改当前目录下的`model.py`不会生效,因为加载的是funasr内部版本,模型代码[点击查看](https://github.com/modelscope/FunASR/tree/main/funasr/models/sense_voice)。
+- `vad_model`:表示开启VAD,VAD的作用是将长音频切割成短音频,此时推理耗时包括了VAD与SenseVoice总耗时,为链路耗时,如果需要单独测试SenseVoice模型耗时,可以关闭VAD模型。
+- `vad_kwargs`:表示VAD模型配置,`max_single_segment_time`: 表示`vad_model`最大切割音频时长, 单位是毫秒ms。
+- `use_itn`:输出结果中是否包含标点与逆文本正则化。
+- `batch_size_s` 表示采用动态batch,batch中总音频时长,单位为秒s。
+- `merge_vad`:是否将 vad 模型切割的短音频碎片合成,合并后长度为`merge_length_s`,单位为秒s。
+- `ban_emo_unk`:禁用emo_unk标签,禁用后所有的句子都会被赋与情感标签。默认`False`
+
+```python
+model = AutoModel(model=model_dir, trust_remote_code=True, device="cuda:0")
+
+res = model.generate(
+ input=f"{model.model_path}/example/en.mp3",
+ cache={},
+ language="auto", # "zn", "en", "yue", "ja", "ko", "nospeech"
+ use_itn=True,
+ batch_size=64,
+)
+```
+
+更多详细用法,请参考 [文档](https://github.com/modelscope/FunASR/blob/main/docs/tutorial/README.md)
+
+
+
+## 模型下载
+上面代码会自动下载模型,如果您需要离线下载好模型,可以通过下面代码,手动下载,之后指定模型本地路径即可。
+
+SDK下载
+```bash
+#安装ModelScope
+pip install modelscope
+```
+```python
+#SDK模型下载
+from modelscope import snapshot_download
+model_dir = snapshot_download('iic/SenseVoiceSmall')
+```
+Git下载
+```
+#Git模型下载
+git clone https://www.modelscope.cn/iic/SenseVoiceSmall.git
+```
+
+## 服务部署
+
+Undo
+
+# Performance
+
+## 语音识别效果
+我们在开源基准数据集(包括 AISHELL-1、AISHELL-2、Wenetspeech、Librispeech和Common Voice)上比较了SenseVoice与Whisper的多语言语音识别性能和推理效率。在中文和粤语识别效果上,SenseVoice-Small模型具有明显的效果优势。
+
+
+
+
+
+
+
+## 情感识别效果
+由于目前缺乏被广泛使用的情感识别测试指标和方法,我们在多个测试集的多种指标进行测试,并与近年来Benchmark上的多个结果进行了全面的对比。所选取的测试集同时包含中文/英文两种语言以及表演、影视剧、自然对话等多种风格的数据,在不进行目标数据微调的前提下,SenseVoice能够在测试数据上达到和超过目前最佳情感识别模型的效果。
+
+
+
+
+
+同时,我们还在测试集上对多个开源情感识别模型进行对比,结果表明,SenseVoice-Large模型可以在几乎所有数据上都达到了最佳效果,而SenseVoice-Small模型同样可以在多数数据集上取得超越其他开源模型的效果。
+
+
+
+
+
+## 事件检测效果
+
+尽管SenseVoice只在语音数据上进行训练,它仍然可以作为事件检测模型进行单独使用。我们在环境音分类ESC-50数据集上与目前业内广泛使用的BEATS与PANN模型的效果进行了对比。SenseVoice模型能够在这些任务上取得较好的效果,但受限于训练数据与训练方式,其事件分类效果专业的事件检测模型相比仍然有一定的差距。
+
+
+
+
+
+
+
+## 推理效率
+SenseVoice-Small模型采用非自回归端到端架构,推理延迟极低。在参数量与Whisper-Small模型相当的情况下,比Whisper-Small模型推理速度快7倍,比Whisper-Large模型快17倍。同时SenseVoice-small模型在音频时长增加的情况下,推理耗时也无明显增加。
+
+
+
+
+
+
+如果您是本模型的贡献者,我们邀请您根据模型贡献文档 ,及时完善模型卡片内容。
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/am.mvn b/main/xiaozhi-server/models/iic/SenseVoiceSmall/am.mvn
new file mode 100644
index 000000000..681910cd1
--- /dev/null
+++ b/main/xiaozhi-server/models/iic/SenseVoiceSmall/am.mvn
@@ -0,0 +1,8 @@
+
+ 560 560
+[ 0 ]
+ 560 560
+ 0 [ -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 -8.311879 -8.600912 -9.615928 -10.43595 -11.21292 -11.88333 -12.36243 -12.63706 -12.8818 -12.83066 -12.89103 -12.95666 -13.19763 -13.40598 -13.49113 -13.5546 -13.55639 -13.51915 -13.68284 -13.53289 -13.42107 -13.65519 -13.50713 -13.75251 -13.76715 -13.87408 -13.73109 -13.70412 -13.56073 -13.53488 -13.54895 -13.56228 -13.59408 -13.62047 -13.64198 -13.66109 -13.62669 -13.58297 -13.57387 -13.4739 -13.53063 -13.48348 -13.61047 -13.64716 -13.71546 -13.79184 -13.90614 -14.03098 -14.18205 -14.35881 -14.48419 -14.60172 -14.70591 -14.83362 -14.92122 -15.00622 -15.05122 -15.03119 -14.99028 -14.92302 -14.86927 -14.82691 -14.7972 -14.76909 -14.71356 -14.61277 -14.51696 -14.42252 -14.36405 -14.30451 -14.23161 -14.19851 -14.16633 -14.15649 -14.10504 -13.99518 -13.79562 -13.3996 -12.7767 -11.71208 ]
+ 560 560
+ 0 [ 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 0.155775 0.154484 0.1527379 0.1518718 0.1506028 0.1489256 0.147067 0.1447061 0.1436307 0.1443568 0.1451849 0.1455157 0.1452821 0.1445717 0.1439195 0.1435867 0.1436018 0.1438781 0.1442086 0.1448844 0.1454756 0.145663 0.146268 0.1467386 0.1472724 0.147664 0.1480913 0.1483739 0.1488841 0.1493636 0.1497088 0.1500379 0.1502916 0.1505389 0.1506787 0.1507102 0.1505992 0.1505445 0.1505938 0.1508133 0.1509569 0.1512396 0.1514625 0.1516195 0.1516156 0.1515561 0.1514966 0.1513976 0.1512612 0.151076 0.1510596 0.1510431 0.151077 0.1511168 0.1511917 0.151023 0.1508045 0.1505885 0.1503493 0.1502373 0.1501726 0.1500762 0.1500065 0.1499782 0.150057 0.1502658 0.150469 0.1505335 0.1505505 0.1505328 0.1504275 0.1502438 0.1499674 0.1497118 0.1494661 0.1493102 0.1493681 0.1495501 0.1499738 0.1509654 ]
+
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model b/main/xiaozhi-server/models/iic/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model
new file mode 100644
index 000000000..da7e3755c
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/config.yaml b/main/xiaozhi-server/models/iic/SenseVoiceSmall/config.yaml
new file mode 100644
index 000000000..26bb9d3d2
--- /dev/null
+++ b/main/xiaozhi-server/models/iic/SenseVoiceSmall/config.yaml
@@ -0,0 +1,97 @@
+encoder: SenseVoiceEncoderSmall
+encoder_conf:
+ output_size: 512
+ attention_heads: 4
+ linear_units: 2048
+ num_blocks: 50
+ tp_blocks: 20
+ dropout_rate: 0.1
+ positional_dropout_rate: 0.1
+ attention_dropout_rate: 0.1
+ input_layer: pe
+ pos_enc_class: SinusoidalPositionEncoder
+ normalize_before: true
+ kernel_size: 11
+ sanm_shfit: 0
+ selfattention_layer_type: sanm
+
+
+model: SenseVoiceSmall
+model_conf:
+ length_normalized_loss: true
+ sos: 1
+ eos: 2
+ ignore_id: -1
+
+tokenizer: SentencepiecesTokenizer
+tokenizer_conf:
+ bpemodel: null
+ unk_symbol:
+ split_with_space: true
+
+frontend: WavFrontend
+frontend_conf:
+ fs: 16000
+ window: hamming
+ n_mels: 80
+ frame_length: 25
+ frame_shift: 10
+ lfr_m: 7
+ lfr_n: 6
+ cmvn_file: null
+
+
+dataset: SenseVoiceCTCDataset
+dataset_conf:
+ index_ds: IndexDSJsonl
+ batch_sampler: EspnetStyleBatchSampler
+ data_split_num: 32
+ batch_type: token
+ batch_size: 14000
+ max_token_length: 2000
+ min_token_length: 60
+ max_source_length: 2000
+ min_source_length: 60
+ max_target_length: 200
+ min_target_length: 0
+ shuffle: true
+ num_workers: 4
+ sos: ${model_conf.sos}
+ eos: ${model_conf.eos}
+ IndexDSJsonl: IndexDSJsonl
+ retry: 20
+
+train_conf:
+ accum_grad: 1
+ grad_clip: 5
+ max_epoch: 20
+ keep_nbest_models: 10
+ avg_nbest_model: 10
+ log_interval: 100
+ resume: true
+ validate_interval: 10000
+ save_checkpoint_interval: 10000
+
+optim: adamw
+optim_conf:
+ lr: 0.00002
+scheduler: warmuplr
+scheduler_conf:
+ warmup_steps: 25000
+
+specaug: SpecAugLFR
+specaug_conf:
+ apply_time_warp: false
+ time_warp_window: 5
+ time_warp_mode: bicubic
+ apply_freq_mask: true
+ freq_mask_width_range:
+ - 0
+ - 30
+ lfr_rate: 6
+ num_freq_mask: 1
+ apply_time_mask: true
+ time_mask_width_range:
+ - 0
+ - 12
+ num_time_mask: 1
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/configuration.json b/main/xiaozhi-server/models/iic/SenseVoiceSmall/configuration.json
new file mode 100644
index 000000000..264d8171d
--- /dev/null
+++ b/main/xiaozhi-server/models/iic/SenseVoiceSmall/configuration.json
@@ -0,0 +1,14 @@
+{
+ "framework": "pytorch",
+ "task" : "auto-speech-recognition",
+ "model": {"type" : "funasr"},
+ "pipeline": {"type":"funasr-pipeline"},
+ "model_name_in_hub": {
+ "ms":"",
+ "hf":""},
+ "file_path_metas": {
+ "init_param":"model.pt",
+ "config":"config.yaml",
+ "tokenizer_conf": {"bpemodel": "chn_jpn_yue_eng_ko_spectok.bpe.model"},
+ "frontend_conf":{"cmvn_file": "am.mvn"}}
+}
\ No newline at end of file
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/aed_figure.png b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/aed_figure.png
new file mode 100644
index 000000000..995cedf3b
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/aed_figure.png differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/asr_results.png b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/asr_results.png
new file mode 100644
index 000000000..d962606e9
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/asr_results.png differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/inference.png b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/inference.png
new file mode 100644
index 000000000..0af617430
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/inference.png differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/sensevoice.png b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/sensevoice.png
new file mode 100644
index 000000000..8b8786b75
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/sensevoice.png differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/ser_figure.png b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/ser_figure.png
new file mode 100644
index 000000000..e3348900a
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/ser_figure.png differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/ser_table.png b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/ser_table.png
new file mode 100644
index 000000000..da432dfc3
Binary files /dev/null and b/main/xiaozhi-server/models/iic/SenseVoiceSmall/fig/ser_table.png differ
diff --git a/main/xiaozhi-server/models/iic/SenseVoiceSmall/tokens.json b/main/xiaozhi-server/models/iic/SenseVoiceSmall/tokens.json
new file mode 100644
index 000000000..bc0021233
--- /dev/null
+++ b/main/xiaozhi-server/models/iic/SenseVoiceSmall/tokens.json
@@ -0,0 +1,25057 @@
+[
+ "",
+ "",
+ " ",
+ "▁the",
+ "s",
+ "▁to",
+ "▁and",
+ "▁of",
+ "▁a",
+ "'",
+ "▁in",
+ "▁I",
+ "▁that",
+ "▁is",
+ "▁you",
+ "▁it",
+ "t",
+ "▁for",
+ "▁we",
+ "▁was",
+ "▁with",
+ "▁on",
+ "ing",
+ "▁be",
+ "▁are",
+ "▁have",
+ "ed",
+ "d",
+ "▁as",
+ "▁this",
+ "▁not",
+ "▁our",
+ "▁at",
+ "▁your",
+ "▁can",
+ "▁from",
+ "▁The",
+ "▁or",
+ "▁will",
+ "▁but",
+ "▁he",
+ "▁one",
+ "▁an",
+ "re",
+ "▁my",
+ "▁by",
+ "▁his",
+ "▁all",
+ "▁they",
+ "ly",
+ "▁had",
+ "▁her",
+ "▁me",
+ "▁more",
+ "I",
+ "▁were",
+ "▁about",
+ "▁out",
+ "▁do",
+ "▁so",
+ "▁up",
+ "m",
+ "▁has",
+ "▁what",
+ "y",
+ "▁there",
+ "▁time",
+ "▁would",
+ "The",
+ "▁like",
+ "▁their",
+ "er",
+ "▁It",
+ "▁been",
+ "▁just",
+ "▁if",
+ "▁them",
+ "▁some",
+ "▁which",
+ "▁We",
+ "▁she",
+ "▁He",
+ "ve",
+ "▁also",
+ "▁when",
+ "▁two",
+ "▁into",
+ "▁no",
+ "▁other",
+ "▁get",
+ "▁over",
+ "ll",
+ "▁him",
+ "▁us",
+ "n",
+ "▁And",
+ "▁know",
+ "▁think",
+ "▁who",
+ "al",
+ "▁could",
+ "▁see",
+ "▁than",
+ "▁A",
+ "▁very",
+ "▁don",
+ "▁back",
+ "▁how",
+ "e",
+ "▁people",
+ "▁new",
+ "▁these",
+ "▁But",
+ "r",
+ "▁make",
+ "▁any",
+ "▁first",
+ "We",
+ "▁then",
+ "▁only",
+ "▁now",
+ "▁way",
+ "in",
+ "▁You",
+ "▁",
+ "▁In",
+ "▁year",
+ "▁want",
+ "▁good",
+ "▁This",
+ "▁well",
+ "▁need",
+ "▁going",
+ "▁may",
+ "▁work",
+ "es",
+ "▁because",
+ "▁much",
+ "▁even",
+ "▁through",
+ "▁She",
+ "▁where",
+ "▁go",
+ "▁down",
+ "▁So",
+ "It",
+ "A",
+ "▁right",
+ "▁really",
+ "▁those",
+ "▁most",
+ "▁should",
+ "a",
+ "In",
+ "▁three",
+ "▁did",
+ "▁take",
+ "▁many",
+ "▁re",
+ "▁twenty",
+ "▁here",
+ "▁business",
+ "▁use",
+ "▁still",
+ "▁after",
+ "▁too",
+ "▁If",
+ "▁before",
+ "▁made",
+ "or",
+ "▁They",
+ "▁look",
+ "▁years",
+ "▁around",
+ "▁point",
+ "ers",
+ "And",
+ "▁being",
+ "▁day",
+ "▁hundred",
+ "▁last",
+ "▁little",
+ "▁didn",
+ "▁five",
+ "▁said",
+ "▁something",
+ "▁off",
+ "▁things",
+ "▁such",
+ "This",
+ "▁same",
+ "▁help",
+ "▁life",
+ "S",
+ "▁both",
+ "▁different",
+ "ic",
+ "o",
+ "▁find",
+ "▁never",
+ "▁each",
+ "▁got",
+ "He",
+ "▁quarter",
+ "▁come",
+ "l",
+ "▁lot",
+ "▁say",
+ "▁own",
+ "▁its",
+ "▁four",
+ "▁That",
+ "▁long",
+ "▁un",
+ "▁again",
+ "▁great",
+ "▁used",
+ "▁end",
+ "▁S",
+ "▁There",
+ "▁few",
+ "▁better",
+ "▁always",
+ "▁part",
+ "▁while",
+ "▁might",
+ "But",
+ "▁home",
+ "▁best",
+ "▁between",
+ "▁am",
+ "le",
+ "ation",
+ "▁every",
+ "▁world",
+ "If",
+ "T",
+ "it",
+ "▁feel",
+ "▁love",
+ "▁place",
+ "an",
+ "C",
+ "▁next",
+ "▁market",
+ "able",
+ "▁B",
+ "ion",
+ "▁does",
+ "▁s",
+ "g",
+ "P",
+ "▁number",
+ "▁found",
+ "▁another",
+ "▁growth",
+ "▁second",
+ "▁believe",
+ "▁thing",
+ "You",
+ "▁away",
+ "▁put",
+ "▁continue",
+ "c",
+ "▁must",
+ "ity",
+ "▁results",
+ "▁give",
+ "ar",
+ "▁under",
+ "on",
+ "il",
+ "▁sure",
+ "▁thought",
+ "▁head",
+ "▁hand",
+ "▁important",
+ "▁thousand",
+ "▁man",
+ "▁For",
+ "▁without",
+ "So",
+ "▁data",
+ "▁T",
+ "▁keep",
+ "▁call",
+ "▁able",
+ "▁As",
+ "▁company",
+ "▁information",
+ "▁bit",
+ "▁de",
+ "▁What",
+ "M",
+ "▁let",
+ "▁why",
+ "▁E",
+ "▁during",
+ "D",
+ "▁case",
+ "i",
+ "▁high",
+ "▁six",
+ "▁kind",
+ "▁When",
+ "▁change",
+ "▁course",
+ "▁nineteen",
+ "▁team",
+ "▁start",
+ "p",
+ "and",
+ "F",
+ "▁set",
+ "▁though",
+ "As",
+ "el",
+ "B",
+ "▁done",
+ "▁hard",
+ "▁using",
+ "▁against",
+ "▁small",
+ "E",
+ "▁system",
+ "▁left",
+ "▁doing",
+ "th",
+ "▁face",
+ "▁side",
+ "▁water",
+ "▁enough",
+ "b",
+ "▁came",
+ "▁F",
+ "ch",
+ "R",
+ "▁fact",
+ "▁looking",
+ "▁car",
+ "▁since",
+ "en",
+ "▁went",
+ "ra",
+ "ent",
+ "▁took",
+ "L",
+ "▁order",
+ "▁room",
+ "▁ten",
+ "▁today",
+ "▁doesn",
+ "ment",
+ "▁process",
+ "▁non",
+ "▁line",
+ "▁No",
+ "▁past",
+ "▁D",
+ "▁far",
+ "ness",
+ "▁family",
+ "▁big",
+ "▁looked",
+ "▁show",
+ "ur",
+ "▁already",
+ "▁support",
+ "▁anything",
+ "▁experience",
+ "▁until",
+ "▁My",
+ "▁eight",
+ "▁tell",
+ "▁making",
+ "▁strong",
+ "▁open",
+ "▁actually",
+ "▁provide",
+ "▁play",
+ "▁working",
+ "▁seven",
+ "▁seen",
+ "▁game",
+ "G",
+ "▁care",
+ "▁across",
+ "▁real",
+ "She",
+ "▁expect",
+ "h",
+ "▁eyes",
+ "▁customers",
+ "▁wanted",
+ "▁future",
+ "▁mean",
+ "▁less",
+ "▁value",
+ "They",
+ "ri",
+ "us",
+ "▁together",
+ "▁night",
+ "at",
+ "▁free",
+ "▁money",
+ "▁ever",
+ "▁C",
+ "est",
+ "▁G",
+ "k",
+ "▁full",
+ "te",
+ "▁con",
+ "▁e",
+ "▁getting",
+ "▁level",
+ "ive",
+ "▁days",
+ "▁question",
+ "is",
+ "▁within",
+ "as",
+ "▁To",
+ "▁wasn",
+ "▁percent",
+ "▁mind",
+ "man",
+ "▁house",
+ "ry",
+ "O",
+ "▁power",
+ "▁large",
+ "▁try",
+ "▁top",
+ "▁understand",
+ "▁having",
+ "▁study",
+ "▁several",
+ "lo",
+ "▁everything",
+ "ro",
+ "▁P",
+ "▁cost",
+ "to",
+ "▁nothing",
+ "ies",
+ "▁light",
+ "▁run",
+ "▁forward",
+ "▁won",
+ "ter",
+ "▁saw",
+ "▁pre",
+ "▁started",
+ "▁service",
+ "▁possible",
+ "▁often",
+ "▁once",
+ "▁control",
+ "▁body",
+ "▁knew",
+ "▁product",
+ "▁felt",
+ "▁problem",
+ "▁talk",
+ "▁person",
+ "▁become",
+ "▁old",
+ "▁performance",
+ "u",
+ "▁group",
+ "▁read",
+ "▁co",
+ "▁state",
+ "There",
+ "▁half",
+ "▁book",
+ "▁later",
+ "▁nine",
+ "▁post",
+ "▁thirty",
+ "▁turn",
+ "▁trying",
+ "▁However",
+ "ia",
+ "▁Re",
+ "na",
+ "▁per",
+ "▁week",
+ "For",
+ "▁least",
+ "▁told",
+ "When",
+ "▁available",
+ "▁yet",
+ "N",
+ "id",
+ "▁move",
+ "▁food",
+ "ta",
+ "▁someone",
+ "▁R",
+ "▁probably",
+ "▁including",
+ "▁children",
+ "▁share",
+ "▁All",
+ "ist",
+ "▁patients",
+ "▁given",
+ "▁God",
+ "▁higher",
+ "▁impact",
+ "▁plan",
+ "▁quite",
+ "▁area",
+ "▁example",
+ "ted",
+ "▁increase",
+ "▁school",
+ "f",
+ "▁close",
+ "rs",
+ "▁products",
+ "▁result",
+ "That",
+ "▁job",
+ "ne",
+ "ate",
+ "ary",
+ "▁name",
+ "▁coming",
+ "▁live",
+ "age",
+ "▁local",
+ "▁model",
+ "ine",
+ "et",
+ "▁O",
+ "▁space",
+ "▁terms",
+ "▁door",
+ "▁Do",
+ "▁along",
+ "▁asked",
+ "▁financial",
+ "▁further",
+ "▁sales",
+ "co",
+ "▁due",
+ "ul",
+ "▁whole",
+ "se",
+ "▁clear",
+ "▁pretty",
+ "▁moment",
+ "▁months",
+ "▁matter",
+ "▁lower",
+ "▁New",
+ "▁else",
+ "▁early",
+ "▁significant",
+ "▁whether",
+ "▁key",
+ "▁present",
+ "ling",
+ "▁pro",
+ "me",
+ "▁H",
+ "ty",
+ "▁based",
+ "▁means",
+ "▁reason",
+ "▁At",
+ "▁development",
+ "we",
+ "▁times",
+ "la",
+ "▁focus",
+ "ie",
+ "▁almost",
+ "▁easy",
+ "▁idea",
+ "H",
+ "▁heart",
+ "▁myself",
+ "▁create",
+ "▁pay",
+ "ism",
+ "▁either",
+ "▁sense",
+ "ating",
+ "▁view",
+ "ma",
+ "▁story",
+ "▁design",
+ "▁N",
+ "▁front",
+ "ant",
+ "ton",
+ "▁bad",
+ "▁fifty",
+ "▁current",
+ "less",
+ "▁third",
+ "▁K",
+ "▁ask",
+ "▁His",
+ "▁turned",
+ "▁project",
+ "▁couple",
+ "▁rest",
+ "▁however",
+ "▁position",
+ "▁behind",
+ "▁p",
+ "ce",
+ "▁rate",
+ "▁dollars",
+ "tic",
+ "▁couldn",
+ "ous",
+ "▁country",
+ "x",
+ "▁makes",
+ "ol",
+ "▁Then",
+ "V",
+ "▁price",
+ "ally",
+ "ance",
+ "▁government",
+ "▁men",
+ "ge",
+ "um",
+ "▁hope",
+ "However",
+ "▁certain",
+ "▁everyone",
+ "▁health",
+ "▁isn",
+ "▁quality",
+ "li",
+ "▁others",
+ "▁needs",
+ "▁short",
+ "▁women",
+ "ized",
+ "▁add",
+ "Our",
+ "im",
+ "▁public",
+ "▁stop",
+ "▁needed",
+ "ial",
+ "ated",
+ "▁customer",
+ "▁taking",
+ "ad",
+ "ci",
+ "▁form",
+ "▁services",
+ "▁called",
+ "▁risk",
+ "▁Now",
+ "▁friends",
+ "▁yourself",
+ "▁ago",
+ "▁comes",
+ "▁dis",
+ "▁Not",
+ "▁L",
+ "▁addition",
+ "ian",
+ "the",
+ "▁true",
+ "▁These",
+ "▁low",
+ "▁cannot",
+ "▁f",
+ "▁season",
+ "▁One",
+ "▁After",
+ "▁human",
+ "▁site",
+ "▁capital",
+ "▁program",
+ "▁table",
+ "▁Or",
+ "▁amount",
+ "▁forty",
+ "▁size",
+ "▁Our",
+ "▁zero",
+ "▁opportunity",
+ "▁sort",
+ "▁maybe",
+ "w",
+ "▁list",
+ "W",
+ "▁content",
+ "▁longer",
+ "▁taken",
+ "▁specific",
+ "▁minutes",
+ "▁W",
+ "▁deal",
+ "led",
+ "▁single",
+ "▁revenue",
+ "▁potential",
+ "▁leave",
+ "▁mother",
+ "▁How",
+ "▁inside",
+ "▁questions",
+ "▁drive",
+ "▁above",
+ "▁treatment",
+ "▁remember",
+ "▁stay",
+ "▁changes",
+ "▁wrong",
+ "▁simple",
+ "▁especially",
+ "▁positive",
+ "▁similar",
+ "▁court",
+ "▁outside",
+ "▁interest",
+ "▁words",
+ "▁offer",
+ "un",
+ "▁young",
+ "▁tried",
+ "▁hands",
+ "▁bring",
+ "▁rather",
+ "▁ninety",
+ "▁social",
+ "To",
+ "▁seems",
+ "▁website",
+ "▁industry",
+ "ck",
+ "▁phone",
+ "▁black",
+ "▁type",
+ "▁grow",
+ "▁answer",
+ "▁learn",
+ "▁buy",
+ "▁access",
+ "▁issue",
+ "▁energy",
+ "▁known",
+ "▁build",
+ "▁air",
+ "▁demand",
+ "son",
+ "▁research",
+ "▁morning",
+ "▁building",
+ "▁heard",
+ "▁additional",
+ "▁period",
+ "▁sub",
+ "▁white",
+ "▁hear",
+ "line",
+ "▁general",
+ "▁voice",
+ "am",
+ "▁difficult",
+ "▁check",
+ "ful",
+ "▁simply",
+ "▁effect",
+ "▁approach",
+ "▁gave",
+ "▁expected",
+ "▁M",
+ "▁likely",
+ "▁en",
+ "▁age",
+ "▁include",
+ "▁De",
+ "▁happy",
+ "▁hair",
+ "▁major",
+ "▁special",
+ "▁soon",
+ "▁opportunities",
+ "▁cash",
+ "▁Co",
+ "de",
+ "▁hours",
+ "▁woman",
+ "ization",
+ "▁test",
+ "▁personal",
+ "▁lost",
+ "▁online",
+ "▁On",
+ "▁quickly",
+ "▁media",
+ "▁anyone",
+ "▁himself",
+ "▁role",
+ "▁child",
+ "▁return",
+ "▁environment",
+ "▁fun",
+ "▁management",
+ "min",
+ "▁continued",
+ "ping",
+ "▁range",
+ "▁began",
+ "▁war",
+ "▁cut",
+ "▁Some",
+ "ver",
+ "▁win",
+ "▁ground",
+ "▁improve",
+ "▁wouldn",
+ "▁happen",
+ "▁city",
+ "▁US",
+ "▁step",
+ "▁technology",
+ "▁hit",
+ "be",
+ "▁U",
+ "▁With",
+ "▁perfect",
+ "What",
+ "▁meet",
+ "ut",
+ "▁sixty",
+ "▁American",
+ "▁history",
+ "▁father",
+ "▁law",
+ "These",
+ "▁levels",
+ "▁particular",
+ "ir",
+ "▁review",
+ "▁music",
+ "▁community",
+ "▁anti",
+ "▁office",
+ "▁allow",
+ "▁paper",
+ "▁ability",
+ "▁field",
+ "▁increased",
+ "▁thinking",
+ "▁chance",
+ "▁Her",
+ "▁talking",
+ "▁cause",
+ "up",
+ "▁running",
+ "▁death",
+ "▁living",
+ "▁w",
+ "▁seeing",
+ "▁flow",
+ "▁Le",
+ "▁issues",
+ "▁gone",
+ "▁happened",
+ "▁nice",
+ "▁hold",
+ "ish",
+ "op",
+ "▁seemed",
+ "▁success",
+ "▁held",
+ "▁various",
+ "▁evidence",
+ "▁contact",
+ "▁st",
+ "ac",
+ "▁account",
+ "▁companies",
+ "▁progress",
+ "▁seem",
+ "ities",
+ "▁eighty",
+ "▁An",
+ "z",
+ "▁pain",
+ "▁among",
+ "U",
+ "▁main",
+ "▁b",
+ "▁areas",
+ "▁common",
+ "con",
+ "di",
+ "▁sound",
+ "▁walk",
+ "▁consider",
+ "▁following",
+ "▁activity",
+ "▁class",
+ "per",
+ "▁strategy",
+ "▁complete",
+ "▁itself",
+ "▁red",
+ "▁act",
+ "ite",
+ "ize",
+ "▁color",
+ "▁Just",
+ "▁upon",
+ "▁friend",
+ "ative",
+ "ti",
+ "▁related",
+ "ni",
+ "▁ready",
+ "▁operating",
+ "▁below",
+ "▁beautiful",
+ "▁blood",
+ "▁V",
+ "vi",
+ "▁seventy",
+ "▁month",
+ "▁break",
+ "▁cases",
+ "pe",
+ "▁alone",
+ "▁lead",
+ "▁fourth",
+ "▁attention",
+ "▁entire",
+ "▁near",
+ "▁bar",
+ "▁weeks",
+ "ner",
+ "▁dark",
+ "▁fall",
+ "▁students",
+ "▁costs",
+ "ig",
+ "▁cr",
+ "▁required",
+ "▁Ma",
+ "▁Well",
+ "▁date",
+ "▁remain",
+ "▁final",
+ "▁action",
+ "po",
+ "▁road",
+ "▁worked",
+ "▁function",
+ "▁fire",
+ "▁La",
+ "ard",
+ "▁problems",
+ "▁individual",
+ "▁stuff",
+ "▁base",
+ "go",
+ "▁floor",
+ "▁writing",
+ "▁feeling",
+ "▁skin",
+ "▁became",
+ "▁eighteen",
+ "▁production",
+ "▁page",
+ "▁situation",
+ "At",
+ "sh",
+ "mo",
+ "▁film",
+ "▁markets",
+ "▁benefit",
+ "▁decision",
+ "▁deep",
+ "▁recent",
+ "▁term",
+ "▁certainly",
+ "▁art",
+ "▁tax",
+ "My",
+ "va",
+ "ning",
+ "▁ex",
+ "▁credit",
+ "After",
+ "▁toward",
+ "▁normal",
+ "▁kids",
+ "▁cell",
+ "▁report",
+ "▁watch",
+ "▁clean",
+ "▁usually",
+ "▁enjoy",
+ "▁total",
+ "▁o",
+ "▁write",
+ "▁moving",
+ "K",
+ "▁please",
+ "▁visit",
+ "▁track",
+ "▁decided",
+ "▁late",
+ "▁analysis",
+ "▁follow",
+ "▁fifteen",
+ "▁exactly",
+ "No",
+ "▁subject",
+ "▁goes",
+ "v",
+ "▁fine",
+ "▁Ro",
+ "▁United",
+ "With",
+ "▁network",
+ "▁guess",
+ "▁sometimes",
+ "▁store",
+ "▁completely",
+ "▁oil",
+ "▁choose",
+ "▁investment",
+ "▁structure",
+ "▁fear",
+ "ny",
+ "▁bed",
+ "▁d",
+ "▁ways",
+ "▁speak",
+ "▁looks",
+ "▁cross",
+ "ow",
+ "▁growing",
+ "On",
+ "ide",
+ "our",
+ "▁app",
+ "▁begin",
+ "▁overall",
+ "▁release",
+ "▁conditions",
+ "▁method",
+ "▁practice",
+ "ors",
+ "▁material",
+ "▁record",
+ "▁code",
+ "▁natural",
+ "▁factors",
+ "▁basis",
+ "he",
+ "▁unique",
+ "▁cells",
+ "▁pressure",
+ "ex",
+ "▁feet",
+ "▁event",
+ "▁members",
+ "no",
+ "▁events",
+ "▁balance",
+ "▁twelve",
+ "▁statements",
+ "▁address",
+ "▁themselves",
+ "▁moved",
+ "▁knowledge",
+ "▁relationship",
+ "▁Be",
+ "om",
+ "ber",
+ "▁video",
+ "▁word",
+ "▁Ba",
+ "▁center",
+ "▁party",
+ "▁response",
+ "▁Sa",
+ "▁path",
+ "▁changed",
+ "▁Con",
+ "out",
+ "▁difference",
+ "▁wait",
+ "▁safe",
+ "ence",
+ "▁choice",
+ "ot",
+ "bb",
+ "▁training",
+ "▁fit",
+ "▁studies",
+ "▁Me",
+ "▁fast",
+ "▁kept",
+ "Now",
+ "▁sat",
+ "▁patient",
+ "▁Mo",
+ "▁eye",
+ "ster",
+ "▁land",
+ "▁email",
+ "▁instead",
+ "▁works",
+ "▁spend",
+ "▁Even",
+ "▁takes",
+ "▁lives",
+ "▁points",
+ "▁weight",
+ "▁associated",
+ "ha",
+ "▁throughout",
+ "▁interesting",
+ "▁touch",
+ "▁avoid",
+ "▁global",
+ "land",
+ "▁travel",
+ "▁towards",
+ "▁parents",
+ "▁mentioned",
+ "▁dead",
+ "▁necessary",
+ "▁says",
+ "▁Ca",
+ "▁brand",
+ "▁ca",
+ "bo",
+ "▁Your",
+ "▁board",
+ "one",
+ "▁beginning",
+ "hi",
+ "▁Li",
+ "way",
+ "▁million",
+ "▁multiple",
+ "▁Q",
+ "▁political",
+ "▁ahead",
+ "▁police",
+ "▁c",
+ "▁brought",
+ "▁earlier",
+ "▁respect",
+ "▁t",
+ "ten",
+ "os",
+ "▁Ra",
+ "▁included",
+ "ical",
+ "▁met",
+ "▁focused",
+ "▁provided",
+ "▁involved",
+ "▁considered",
+ "▁huge",
+ "▁v",
+ "▁section",
+ "▁cool",
+ "▁blog",
+ "▁particularly",
+ "▁stand",
+ "While",
+ "▁multi",
+ "▁Don",
+ "▁games",
+ "▁extra",
+ "▁systems",
+ "▁playing",
+ "▁economic",
+ "nt",
+ "▁reading",
+ "▁sign",
+ "▁search",
+ "▁pick",
+ "▁image",
+ "▁direction",
+ "▁easily",
+ "ward",
+ "les",
+ "ron",
+ "▁worth",
+ "▁language",
+ "▁features",
+ "▁nature",
+ "▁ra",
+ "▁rates",
+ "mi",
+ "ag",
+ "ho",
+ "▁professional",
+ "▁finally",
+ "▁goal",
+ "ga",
+ "▁details",
+ "do",
+ "▁strength",
+ "▁beyond",
+ "▁received",
+ "▁mix",
+ "▁hospital",
+ "▁Can",
+ "▁advantage",
+ "▁property",
+ "▁average",
+ "▁girl",
+ "▁disease",
+ "▁haven",
+ "▁Bo",
+ "▁effects",
+ "und",
+ "▁players",
+ "▁standard",
+ "▁hot",
+ "▁ensure",
+ "▁sleep",
+ "▁America",
+ "▁deliver",
+ "▁Let",
+ "▁style",
+ "▁saying",
+ "▁prior",
+ "▁clients",
+ "king",
+ "dy",
+ "▁culture",
+ "▁eat",
+ "▁di",
+ "▁created",
+ "▁town",
+ "▁compared",
+ "em",
+ "All",
+ "▁super",
+ "mer",
+ "▁staff",
+ "▁security",
+ "▁sit",
+ "▁private",
+ "ley",
+ "▁cold",
+ "ring",
+ "▁Why",
+ "▁truth",
+ "ak",
+ "▁fully",
+ "▁solution",
+ "▁currently",
+ "▁round",
+ "▁shows",
+ "▁reach",
+ "ions",
+ "▁Po",
+ "▁computer",
+ "▁platform",
+ "lu",
+ "▁businesses",
+ "▁China",
+ "▁starting",
+ "▁St",
+ "▁lack",
+ "▁slow",
+ "by",
+ "ff",
+ "▁added",
+ "▁loved",
+ "▁save",
+ "▁previous",
+ "▁projects",
+ "end",
+ "▁guy",
+ "▁medical",
+ "▁cover",
+ "▁serve",
+ "▁Al",
+ "ably",
+ "▁mo",
+ "▁States",
+ "▁fight",
+ "▁effective",
+ "▁directly",
+ "▁loss",
+ "iv",
+ "▁showed",
+ "▁population",
+ "▁source",
+ "ap",
+ "▁explain",
+ "▁learning",
+ "▁portfolio",
+ "▁By",
+ "▁contract",
+ "▁application",
+ "▁warm",
+ "▁mid",
+ "▁picture",
+ "▁physical",
+ "▁la",
+ "▁commercial",
+ "▁wish",
+ "▁stood",
+ "▁count",
+ "▁groups",
+ "ger",
+ "▁First",
+ "▁original",
+ "▁Mar",
+ "ip",
+ "▁piece",
+ "▁guys",
+ "▁imp",
+ "▁surface",
+ "▁clinical",
+ "▁arm",
+ "▁reported",
+ "▁Maybe",
+ "▁version",
+ "▁wide",
+ "▁condition",
+ "▁recently",
+ "▁ran",
+ "▁negative",
+ "▁spent",
+ "▁reduce",
+ "▁series",
+ "▁stopped",
+ "der",
+ "▁actual",
+ "▁existing",
+ "▁summer",
+ "▁hour",
+ "▁brain",
+ "▁wall",
+ "ship",
+ "▁Trump",
+ "▁X",
+ "▁giving",
+ "▁clearly",
+ "▁shape",
+ "▁items",
+ "▁news",
+ "▁limited",
+ "▁successful",
+ "▁ball",
+ "▁national",
+ "▁trust",
+ "ise",
+ "ee",
+ "▁stage",
+ "▁sent",
+ "▁card",
+ "▁direct",
+ "▁income",
+ "▁receive",
+ "▁note",
+ "▁quick",
+ "▁hurt",
+ "▁trial",
+ "▁built",
+ "▁spot",
+ "ub",
+ "▁While",
+ "▁green",
+ "com",
+ "▁inter",
+ "time",
+ "▁gas",
+ "▁policy",
+ "▁benefits",
+ "▁Because",
+ "▁although",
+ "▁books",
+ "▁force",
+ "bi",
+ "▁followed",
+ "ab",
+ "▁lose",
+ "▁screen",
+ "▁expression",
+ "▁po",
+ "▁options",
+ "▁effort",
+ "▁perhaps",
+ "▁Yes",
+ "▁sp",
+ "▁numbers",
+ "ca",
+ "▁heat",
+ "▁countries",
+ "▁organization",
+ "▁immediately",
+ "▁played",
+ "▁seat",
+ "▁highly",
+ "ud",
+ "▁Z",
+ "▁lines",
+ "▁text",
+ "▁larger",
+ "▁press",
+ "▁understanding",
+ "▁agree",
+ "▁opened",
+ "▁doubt",
+ "▁stock",
+ "▁movement",
+ "tro",
+ "▁mouth",
+ "One",
+ "lin",
+ "▁trade",
+ "▁activities",
+ "▁marketing",
+ "let",
+ "▁sell",
+ "▁walked",
+ "▁trip",
+ "▁window",
+ "▁figure",
+ "▁soft",
+ "▁fresh",
+ "▁wife",
+ "▁son",
+ "▁character",
+ "▁smile",
+ "▁host",
+ "▁prevent",
+ "▁send",
+ "▁thank",
+ "▁plans",
+ "tri",
+ "mon",
+ "▁whatever",
+ "▁Pro",
+ "▁blue",
+ "▁box",
+ "▁gun",
+ "▁gives",
+ "▁digital",
+ "▁affect",
+ "ations",
+ "▁complex",
+ "side",
+ "▁speed",
+ "▁ho",
+ "▁user",
+ "▁comment",
+ "▁greater",
+ "▁Europe",
+ "ke",
+ "▁straight",
+ "▁waiting",
+ "▁definitely",
+ "Then",
+ "▁aren",
+ "ging",
+ "fe",
+ "▁guidance",
+ "▁onto",
+ "▁remains",
+ "▁York",
+ "▁Go",
+ "▁breath",
+ "▁scale",
+ "▁target",
+ "▁reached",
+ "▁im",
+ "ect",
+ "▁prices",
+ "▁closed",
+ "▁meeting",
+ "ens",
+ "▁damage",
+ "▁led",
+ "▁pulled",
+ "ight",
+ "ang",
+ "▁distribution",
+ "da",
+ "▁attack",
+ "▁notice",
+ "▁driving",
+ "▁sixteen",
+ "▁supply",
+ "▁tend",
+ "▁happens",
+ "▁core",
+ "ice",
+ "▁provides",
+ "▁shot",
+ "tor",
+ "▁claim",
+ "▁volume",
+ "que",
+ "▁develop",
+ "▁significantly",
+ "▁bo",
+ "▁efforts",
+ "▁shown",
+ "▁vi",
+ "▁comments",
+ "▁ideas",
+ "▁cancer",
+ "▁resources",
+ "▁match",
+ "▁web",
+ "▁solid",
+ "cing",
+ "tion",
+ "ped",
+ "▁allowed",
+ "▁herself",
+ "▁shop",
+ "fi",
+ "▁purpose",
+ "▁reasons",
+ "ick",
+ "▁international",
+ "▁purchase",
+ "▁written",
+ "▁fair",
+ "▁according",
+ "▁May",
+ "▁amazing",
+ "▁brother",
+ "▁appear",
+ "▁healthy",
+ "▁slightly",
+ "izing",
+ "▁bottom",
+ "▁mine",
+ "pa",
+ "▁edge",
+ "▁legal",
+ "▁operations",
+ "▁race",
+ "▁J",
+ "▁therefore",
+ "▁sun",
+ "▁drink",
+ "ious",
+ "▁Vi",
+ "▁John",
+ "▁article",
+ "▁g",
+ "▁types",
+ "▁k",
+ "▁pass",
+ "▁Of",
+ "▁insurance",
+ "▁learned",
+ "act",
+ "oc",
+ "▁capacity",
+ "▁flat",
+ "▁talked",
+ "▁require",
+ "▁margin",
+ "▁designed",
+ "▁scene",
+ "▁serious",
+ "▁paid",
+ "ea",
+ "▁easier",
+ "▁plant",
+ "▁arms",
+ "▁nearly",
+ "▁ourselves",
+ "bu",
+ "▁interested",
+ "▁hadn",
+ "▁stories",
+ "▁correct",
+ "▁Ha",
+ "▁allows",
+ "▁software",
+ "▁behavior",
+ "▁passed",
+ "Some",
+ "▁solutions",
+ "▁middle",
+ "ph",
+ "lic",
+ "▁shift",
+ "▁region",
+ "ey",
+ "▁improvement",
+ "▁discuss",
+ "▁Court",
+ "▁spread",
+ "▁option",
+ "▁eleven",
+ "▁update",
+ "▁appropriate",
+ "▁Most",
+ "▁expectations",
+ "Not",
+ "▁file",
+ "▁drop",
+ "▁generally",
+ "▁husband",
+ "▁produce",
+ "▁includes",
+ "▁developed",
+ "▁stick",
+ "▁charge",
+ "ology",
+ "▁poor",
+ "▁favorite",
+ "▁State",
+ "▁excited",
+ "▁Ho",
+ "▁campaign",
+ "▁mis",
+ "▁Here",
+ "▁comp",
+ "▁comfortable",
+ "▁leading",
+ "nd",
+ "▁achieve",
+ "ft",
+ "ier",
+ "▁kitchen",
+ "▁performed",
+ "▁yes",
+ "▁request",
+ "gu",
+ "▁English",
+ "ified",
+ "▁trouble",
+ "▁Pa",
+ "ath",
+ "▁stress",
+ "▁dog",
+ "▁traditional",
+ "▁mark",
+ "▁suggest",
+ "▁challenge",
+ "▁message",
+ "▁wind",
+ "▁manage",
+ "▁career",
+ "▁chair",
+ "▁ma",
+ "▁baby",
+ "ction",
+ "▁parts",
+ "▁Lo",
+ "▁strategic",
+ "▁increasing",
+ "▁programs",
+ "▁conference",
+ "▁Car",
+ "▁critical",
+ "▁watching",
+ "▁em",
+ "▁died",
+ "that",
+ "▁Ta",
+ "mb",
+ "▁worse",
+ "ries",
+ "▁location",
+ "▁detail",
+ "▁education",
+ "ah",
+ "▁click",
+ "▁dry",
+ "▁safety",
+ "▁protect",
+ "▁extremely",
+ "▁taste",
+ "▁perspective",
+ "▁fourteen",
+ "io",
+ "ble",
+ "ual",
+ "▁improved",
+ "▁helped",
+ "▁boy",
+ "▁corner",
+ "▁bill",
+ "▁band",
+ "ile",
+ "▁dream",
+ "▁competitive",
+ "oo",
+ "▁pull",
+ "ability",
+ "ple",
+ "▁bank",
+ "▁earnings",
+ "▁presence",
+ "His",
+ "▁steps",
+ "▁device",
+ "▁Once",
+ "▁sc",
+ "▁worry",
+ "▁train",
+ "ru",
+ "▁seventeen",
+ "▁obviously",
+ "▁agreement",
+ "▁meant",
+ "▁pleased",
+ "▁useful",
+ "▁net",
+ "▁rule",
+ "ator",
+ "▁truly",
+ "▁th",
+ "▁ro",
+ "▁debt",
+ "▁Ne",
+ "Re",
+ "▁prepared",
+ "uff",
+ "J",
+ "▁initial",
+ "▁active",
+ "▁users",
+ "▁accept",
+ "ba",
+ "▁player",
+ "▁South",
+ "▁guide",
+ "ible",
+ "▁determine",
+ "▁variety",
+ "▁dollar",
+ "▁modern",
+ "▁excellent",
+ "▁sitting",
+ "▁retail",
+ "▁secret",
+ "▁glass",
+ "▁continues",
+ "▁ship",
+ "nc",
+ "▁values",
+ "▁Ka",
+ "ill",
+ "▁investments",
+ "▁gl",
+ "▁primary",
+ "▁memory",
+ "▁gets",
+ "▁equipment",
+ "▁fl",
+ "▁tools",
+ "▁cl",
+ "▁Please",
+ "▁sex",
+ "▁basic",
+ "▁segment",
+ "▁catch",
+ "▁respond",
+ "qui",
+ "▁Also",
+ "ach",
+ "▁lo",
+ "▁sheet",
+ "▁exercise",
+ "▁temperature",
+ "▁factor",
+ "▁daily",
+ "▁block",
+ "▁maintain",
+ "▁City",
+ "for",
+ "▁handle",
+ "▁street",
+ "▁vote",
+ "▁wonderful",
+ "▁decide",
+ "men",
+ "▁combination",
+ "▁assets",
+ "▁die",
+ "▁rock",
+ "ear",
+ "▁se",
+ "▁hotel",
+ "ign",
+ "▁Thank",
+ "▁counter",
+ "▁micro",
+ "▁providing",
+ "▁popular",
+ "mp",
+ "▁Sp",
+ "▁reality",
+ "tter",
+ "▁experienced",
+ "▁h",
+ "▁star",
+ "▁fell",
+ "gg",
+ "▁sweet",
+ "▁motion",
+ "▁standing",
+ "▁Like",
+ "▁machine",
+ "▁smaller",
+ "▁apply",
+ "▁sea",
+ "▁profit",
+ "▁length",
+ "▁bi",
+ "▁Gr",
+ "▁display",
+ "▁offers",
+ "▁regular",
+ "▁generation",
+ "▁unit",
+ "▁foot",
+ "▁perform",
+ "▁movie",
+ "au",
+ "ure",
+ "▁link",
+ "▁pricing",
+ "▁planning",
+ "▁finding",
+ "ists",
+ "▁heavy",
+ "▁club",
+ "▁methods",
+ "▁client",
+ "▁daughter",
+ "▁TV",
+ "cur",
+ "▁listen",
+ "▁majority",
+ "▁concept",
+ "▁models",
+ "▁powerful",
+ "▁partner",
+ "▁driven",
+ "▁states",
+ "▁distance",
+ "▁observed",
+ "▁skills",
+ "▁weather",
+ "▁photo",
+ "ever",
+ "ient",
+ "▁farm",
+ "▁kill",
+ "▁via",
+ "▁thirteen",
+ "▁interview",
+ "▁suit",
+ "▁influence",
+ "▁bright",
+ "▁firm",
+ "ric",
+ "aw",
+ "▁creating",
+ "▁rules",
+ "▁realize",
+ "▁wants",
+ "ler",
+ "▁spoke",
+ "▁War",
+ "▁park",
+ "ps",
+ "▁instance",
+ "▁Jesus",
+ "▁wonder",
+ "port",
+ "▁station",
+ "▁Are",
+ "▁closer",
+ "▁places",
+ "pt",
+ "▁older",
+ "▁holding",
+ "▁wood",
+ "▁University",
+ "▁European",
+ "▁cycle",
+ "ium",
+ "▁launch",
+ "▁collection",
+ "▁images",
+ "▁phase",
+ "Well",
+ "▁tu",
+ "▁college",
+ "▁actions",
+ "▁trans",
+ "dge",
+ "ory",
+ "▁forget",
+ "▁caught",
+ "▁aware",
+ "▁camera",
+ "▁previously",
+ "▁finished",
+ "▁returned",
+ "▁pair",
+ "▁custom",
+ "▁map",
+ "▁signal",
+ "▁El",
+ "▁teams",
+ "board",
+ "▁leaving",
+ "wa",
+ "▁cloud",
+ "▁communication",
+ "▁Na",
+ "form",
+ "▁coffee",
+ "ned",
+ "ition",
+ "av",
+ "▁drug",
+ "▁draw",
+ "▁discussed",
+ "▁presentation",
+ "▁realized",
+ "▁supposed",
+ "▁North",
+ "▁slowly",
+ "▁raised",
+ "▁shut",
+ "▁church",
+ "By",
+ "▁Ga",
+ "lan",
+ "▁member",
+ "▁acquisition",
+ "▁despite",
+ "▁opinion",
+ "che",
+ "▁rich",
+ "▁tough",
+ "▁wear",
+ "▁imagine",
+ "▁consistent",
+ "vo",
+ "▁killed",
+ "▁regarding",
+ "ose",
+ "▁properties",
+ "▁sister",
+ "▁employees",
+ "▁described",
+ "▁West",
+ "nk",
+ "▁rain",
+ "▁treat",
+ "▁appeal",
+ "▁conversation",
+ "▁internal",
+ "▁relative",
+ "▁measures",
+ "ological",
+ "▁traffic",
+ "▁ta",
+ "▁push",
+ "ged",
+ "▁crowd",
+ "ng",
+ "light",
+ "▁finish",
+ "uc",
+ "▁reference",
+ "▁construction",
+ "▁confidence",
+ "▁degree",
+ "▁goals",
+ "▁former",
+ "▁audience",
+ "but",
+ "Even",
+ "gen",
+ "den",
+ "ade",
+ "▁cat",
+ "▁mass",
+ "▁smooth",
+ "▁lay",
+ "▁relatively",
+ "ase",
+ "▁setting",
+ "▁Pe",
+ "▁Di",
+ "▁Many",
+ "▁confident",
+ "▁doctor",
+ "▁thoughts",
+ "ification",
+ "▁From",
+ "▁happening",
+ "How",
+ "▁statement",
+ "over",
+ "▁spending",
+ "▁thus",
+ "od",
+ "▁Per",
+ "▁separate",
+ "▁minute",
+ "▁roll",
+ "▁garden",
+ "▁chain",
+ "▁alternative",
+ "▁enter",
+ "▁covered",
+ "▁watched",
+ "ki",
+ "ren",
+ "▁anyway",
+ "▁absolutely",
+ "▁judge",
+ "right",
+ "▁completed",
+ "▁walking",
+ "back",
+ "▁forwardlooking",
+ "▁frame",
+ "▁science",
+ "▁changing",
+ "▁ch",
+ "Although",
+ "▁becomes",
+ "▁mostly",
+ "lar",
+ "▁pan",
+ "▁Man",
+ "▁reduction",
+ "▁House",
+ "▁budget",
+ "▁gain",
+ "▁Se",
+ "▁ring",
+ "▁background",
+ "▁rise",
+ "▁increases",
+ "▁People",
+ "▁independent",
+ "▁Who",
+ "ep",
+ "▁requires",
+ "X",
+ "▁presented",
+ "▁tea",
+ "▁carry",
+ "▁bag",
+ "▁na",
+ "▁profile",
+ "▁putting",
+ "▁stream",
+ "▁Mc",
+ "▁discussion",
+ "▁smart",
+ "▁Ar",
+ "▁transition",
+ "▁gr",
+ "▁ha",
+ "Yes",
+ "▁India",
+ "▁mobile",
+ "▁offered",
+ "ral",
+ "▁pe",
+ "▁li",
+ "▁feature",
+ "▁fix",
+ "fa",
+ "▁election",
+ "▁Oh",
+ "▁London",
+ "▁opening",
+ "▁Although",
+ "▁sounds",
+ "▁cap",
+ "▁asking",
+ "▁recommend",
+ "▁World",
+ "▁reflect",
+ "▁double",
+ "tan",
+ "▁task",
+ "▁camp",
+ "▁hate",
+ "▁differ",
+ "of",
+ "▁tree",
+ "▁dinner",
+ "▁sh",
+ "▁fish",
+ "tting",
+ "▁challenges",
+ "▁bus",
+ "▁Sha",
+ "▁sold",
+ "▁lu",
+ "▁caused",
+ "ze",
+ "▁engine",
+ "▁exist",
+ "▁load",
+ "ay",
+ "▁applications",
+ "▁military",
+ "▁lived",
+ "▁exchange",
+ "▁noticed",
+ "▁nor",
+ "▁weekend",
+ "▁January",
+ "▁advice",
+ "▁smell",
+ "▁identify",
+ "ened",
+ "▁driver",
+ "▁filled",
+ "▁Jo",
+ "Do",
+ "▁smiled",
+ "▁eventually",
+ "ris",
+ "▁Bar",
+ "▁keeping",
+ "▁title",
+ "▁economy",
+ "▁determined",
+ "▁biggest",
+ "▁Ki",
+ "▁mu",
+ "▁quiet",
+ "low",
+ "▁sa",
+ "▁battle",
+ "▁hearing",
+ "▁desire",
+ "▁announced",
+ "ther",
+ "▁assume",
+ "▁context",
+ "▁society",
+ "▁join",
+ "▁materials",
+ "▁offering",
+ "▁cha",
+ "▁trend",
+ "▁meaning",
+ "▁glance",
+ "▁vision",
+ "▁pen",
+ "▁Christian",
+ "▁sites",
+ "▁advance",
+ "▁object",
+ "▁explore",
+ "off",
+ "▁vehicle",
+ "▁expand",
+ "▁families",
+ "▁except",
+ "▁fan",
+ "▁March",
+ "▁primarily",
+ "▁relevant",
+ "▁fat",
+ "▁nation",
+ "▁radio",
+ "▁student",
+ "▁evening",
+ "▁sample",
+ "▁managed",
+ "▁welcome",
+ "▁Ri",
+ "az",
+ "▁reduced",
+ "▁devices",
+ "▁limit",
+ "▁relationships",
+ "▁faster",
+ "row",
+ "▁weak",
+ "▁proud",
+ "▁ob",
+ "▁essential",
+ "▁shared",
+ "▁repair",
+ "▁beat",
+ "▁enable",
+ "ments",
+ "▁Pi",
+ "▁measure",
+ "▁fill",
+ "▁released",
+ "▁continuing",
+ "▁sta",
+ "ult",
+ "▁placed",
+ "▁remove",
+ "▁girls",
+ "gi",
+ "▁shook",
+ "▁differences",
+ "▁responsible",
+ "▁sale",
+ "tu",
+ "▁competition",
+ "▁metal",
+ "▁decline",
+ "ised",
+ "tra",
+ "▁reaction",
+ "▁fruit",
+ "▁error",
+ "▁individuals",
+ "▁select",
+ "▁connection",
+ "▁rec",
+ "▁initiatives",
+ "▁none",
+ "▁Since",
+ "▁stores",
+ "▁tool",
+ "▁grew",
+ "▁California",
+ "▁Christ",
+ "▁central",
+ "▁mention",
+ "▁fe",
+ "▁president",
+ "cent",
+ "▁pieces",
+ "▁novel",
+ "▁par",
+ "▁prefer",
+ "▁appears",
+ "▁parties",
+ "▁Every",
+ "▁picked",
+ "▁status",
+ "▁Christmas",
+ "vis",
+ "▁identified",
+ "▁holiday",
+ "▁surprise",
+ "▁delivery",
+ "▁June",
+ "▁letter",
+ "▁decisions",
+ "cc",
+ "▁telling",
+ "ran",
+ "▁ba",
+ "▁failure",
+ "▁plenty",
+ "▁package",
+ "▁Chinese",
+ "▁suddenly",
+ "▁miss",
+ "▁bigger",
+ "▁ended",
+ "Of",
+ "▁becoming",
+ "▁pattern",
+ "▁President",
+ "▁foreign",
+ "▁largest",
+ "▁testing",
+ "Be",
+ "▁helps",
+ "▁plate",
+ "▁Pre",
+ "▁gift",
+ "▁journey",
+ "▁describe",
+ "▁channel",
+ "▁promise",
+ "med",
+ "An",
+ "▁born",
+ "▁horse",
+ "pi",
+ "▁established",
+ "▁chest",
+ "▁helpful",
+ "ery",
+ "▁consumer",
+ "part",
+ "▁knows",
+ "▁author",
+ "▁defendant",
+ "▁elements",
+ "▁mode",
+ "▁British",
+ "▁proceed",
+ "▁ride",
+ "▁arrived",
+ "▁fingers",
+ "▁cup",
+ "▁failed",
+ "▁Mi",
+ "▁bought",
+ "uck",
+ "▁recipe",
+ "rk",
+ "▁jump",
+ "fer",
+ "▁applied",
+ "▁missing",
+ "▁wine",
+ "▁schedule",
+ "▁broken",
+ "▁winter",
+ "▁appeared",
+ "istic",
+ "▁selling",
+ "▁organic",
+ "▁shoulder",
+ "▁dress",
+ "▁mission",
+ "▁partners",
+ "▁highest",
+ "▁expansion",
+ "▁leg",
+ "▁pool",
+ "▁whose",
+ "▁annual",
+ "▁shall",
+ "▁afternoon",
+ "▁otherwise",
+ "▁September",
+ "▁solve",
+ "▁comfort",
+ "▁Park",
+ "▁Sc",
+ "▁pop",
+ "▁rep",
+ "▁seek",
+ "▁Gu",
+ "▁San",
+ "▁prove",
+ "▁raise",
+ "▁nu",
+ "▁Ex",
+ "bs",
+ "ug",
+ "ox",
+ "▁typically",
+ "▁processes",
+ "▁download",
+ "▁risks",
+ "▁pictures",
+ "▁guard",
+ "▁generate",
+ "▁animals",
+ "work",
+ "gan",
+ "hy",
+ "▁National",
+ "▁leadership",
+ "▁fixed",
+ "▁December",
+ "str",
+ "▁master",
+ "her",
+ "▁ideal",
+ "par",
+ "▁portion",
+ "▁spring",
+ "pp",
+ "▁faith",
+ "ina",
+ "▁expenses",
+ "▁sight",
+ "▁requirements",
+ "▁lock",
+ "▁bio",
+ "▁ci",
+ "▁snow",
+ "Just",
+ "▁Google",
+ "▁weren",
+ "▁ice",
+ "▁surprised",
+ "▁Da",
+ "▁command",
+ "Because",
+ "▁efficiency",
+ "▁showing",
+ "▁invest",
+ "▁sha",
+ "kin",
+ "▁eating",
+ "▁leader",
+ "▁operation",
+ "▁legs",
+ "ake",
+ "▁tight",
+ "▁offset",
+ "▁sick",
+ "▁pa",
+ "▁Will",
+ "▁committed",
+ "▁button",
+ "▁theory",
+ "rc",
+ "▁federal",
+ "nce",
+ "val",
+ "▁Paul",
+ "▁married",
+ "▁random",
+ "▁technical",
+ "▁empty",
+ "▁wrote",
+ "▁latest",
+ "▁visual",
+ "pro",
+ "▁neck",
+ "▁sector",
+ "pl",
+ "Or",
+ "▁recognize",
+ "▁truck",
+ "▁tissue",
+ "▁okay",
+ "▁accident",
+ "▁efficient",
+ "▁Did",
+ "▁noise",
+ "▁aim",
+ "▁Ben",
+ "▁clothes",
+ "▁Indian",
+ "▁Cor",
+ "cy",
+ "▁timing",
+ "▁stronger",
+ "▁photos",
+ "▁commitment",
+ "▁April",
+ "my",
+ "▁remind",
+ "▁leverage",
+ "Also",
+ "ically",
+ "▁margins",
+ "▁honest",
+ "▁obvious",
+ "▁afraid",
+ "▁Obama",
+ "mark",
+ "▁published",
+ "First",
+ "▁stone",
+ "▁served",
+ "▁appreciate",
+ "▁pet",
+ "▁document",
+ "▁murder",
+ "▁sad",
+ "▁helping",
+ "▁expensive",
+ "▁busy",
+ "▁bone",
+ "use",
+ "▁familiar",
+ "wi",
+ "▁French",
+ "▁loan",
+ "▁Y",
+ "▁David",
+ "▁protection",
+ "cr",
+ "▁located",
+ "▁therapy",
+ "Once",
+ "▁Each",
+ "▁treated",
+ "▁specifically",
+ "▁conclusion",
+ "▁claims",
+ "▁gra",
+ "▁kid",
+ "▁trees",
+ "▁song",
+ "▁collect",
+ "▁earth",
+ "▁selection",
+ "▁switch",
+ "▁transfer",
+ "▁characters",
+ "▁somewhere",
+ "▁peace",
+ "▁England",
+ "▁throw",
+ "▁DNA",
+ "▁buying",
+ "▁strange",
+ "▁Sunday",
+ "▁bottle",
+ "▁gold",
+ "▁route",
+ "▁connect",
+ "▁mail",
+ "▁species",
+ "ched",
+ "▁August",
+ "▁attempt",
+ "▁protein",
+ "▁reports",
+ "▁impossible",
+ "▁improving",
+ "▁auto",
+ "▁football",
+ "▁slide",
+ "▁Su",
+ "▁boat",
+ "app",
+ "▁Internet",
+ "▁developing",
+ "▁fuel",
+ "▁removed",
+ "▁totally",
+ "▁Sometimes",
+ "▁unless",
+ "▁fans",
+ "▁threat",
+ "▁remained",
+ "▁proper",
+ "▁crack",
+ "▁October",
+ "▁argument",
+ "▁mental",
+ "▁anymore",
+ "▁Day",
+ "▁element",
+ "▁liked",
+ "ute",
+ "▁pocket",
+ "▁root",
+ "▁More",
+ "▁cast",
+ "▁dance",
+ "▁Act",
+ "ec",
+ "▁Where",
+ "▁En",
+ "▁combined",
+ "▁defense",
+ "▁carried",
+ "▁wild",
+ "▁nodded",
+ "▁label",
+ "▁represent",
+ "ration",
+ "▁pace",
+ "▁server",
+ "▁soul",
+ "▁female",
+ "▁thick",
+ "▁mom",
+ "▁expense",
+ "▁thin",
+ "▁Instead",
+ "▁fundamental",
+ "▁spirit",
+ "▁operational",
+ "▁concerned",
+ "fully",
+ "▁carefully",
+ "▁lots",
+ "Since",
+ "▁decrease",
+ "▁sharp",
+ "▁regard",
+ "▁laugh",
+ "▁coach",
+ "▁conduct",
+ "▁speaking",
+ "ture",
+ "▁adding",
+ "rus",
+ "▁calm",
+ "ency",
+ "▁connected",
+ "ney",
+ "▁feels",
+ "eg",
+ "▁crime",
+ "▁emotional",
+ "▁contrast",
+ "▁su",
+ "▁Black",
+ "amp",
+ "▁dropped",
+ "▁sorry",
+ "▁manner",
+ "▁promote",
+ "▁exciting",
+ "St",
+ "▁July",
+ "ome",
+ "ern",
+ "ctor",
+ "ker",
+ "rate",
+ "▁UK",
+ "▁leaves",
+ "▁creative",
+ "▁investigation",
+ "▁infection",
+ "▁produced",
+ "za",
+ "▁Their",
+ "▁sexual",
+ "▁obtained",
+ "▁lips",
+ "▁lie",
+ "▁leaders",
+ "▁workers",
+ "▁entirely",
+ "car",
+ "▁secure",
+ "▁estate",
+ "▁willing",
+ "From",
+ "▁sharing",
+ "▁Mu",
+ "▁Hu",
+ "ane",
+ "▁layer",
+ "▁November",
+ "▁Facebook",
+ "▁German",
+ "▁Dr",
+ "▁odd",
+ "▁affected",
+ "▁Have",
+ "▁PC",
+ "▁findings",
+ "▁escape",
+ "▁fail",
+ "▁turning",
+ "▁crazy",
+ "so",
+ "cu",
+ "▁pushed",
+ "▁capabilities",
+ "field",
+ "ham",
+ "▁loud",
+ "▁severe",
+ "▁anywhere",
+ "▁plants",
+ "▁score",
+ "▁East",
+ "ants",
+ "▁bear",
+ "lf",
+ "▁fund",
+ "tain",
+ "ew",
+ "▁obtain",
+ "▁possibly",
+ "har",
+ "▁discover",
+ "▁ti",
+ "▁freedom",
+ "▁mistake",
+ "▁strategies",
+ "▁pipeline",
+ "▁miles",
+ "▁shouldn",
+ "Your",
+ "▁prison",
+ "▁everybody",
+ "▁cur",
+ "nu",
+ "▁brief",
+ "▁classes",
+ "▁sky",
+ "▁inventory",
+ "▁missed",
+ "▁innovation",
+ "▁apart",
+ "▁comparison",
+ "▁Ju",
+ "▁entered",
+ "▁planned",
+ "▁Therefore",
+ "serv",
+ "▁percentage",
+ "▁calls",
+ "▁beside",
+ "▁usual",
+ "▁Mon",
+ "▁occur",
+ "▁transaction",
+ "▁sources",
+ "▁properly",
+ "▁Good",
+ "fo",
+ "▁wearing",
+ "▁delivered",
+ "▁print",
+ "During",
+ "▁express",
+ "▁corporate",
+ "▁exposure",
+ "▁lunch",
+ "ces",
+ "▁male",
+ "▁refer",
+ "▁understood",
+ "▁knowing",
+ "▁believed",
+ "▁remaining",
+ "fin",
+ "▁Two",
+ "▁constant",
+ "▁Sam",
+ "▁dad",
+ "▁internet",
+ "▁flash",
+ "▁tour",
+ "▁mountain",
+ "▁dangerous",
+ "▁pack",
+ "▁Before",
+ "▁ongoing",
+ "▁twice",
+ "▁Other",
+ "ai",
+ "▁license",
+ "▁demonstrate",
+ "▁mi",
+ "▁Tra",
+ "▁wedding",
+ "iness",
+ "comp",
+ "▁fairly",
+ "▁forced",
+ "if",
+ "▁stable",
+ "pped",
+ "▁yield",
+ "▁trends",
+ "▁jobs",
+ "▁functions",
+ "wn",
+ "▁surgery",
+ "▁harm",
+ "▁animal",
+ "▁Those",
+ "▁returns",
+ "▁Col",
+ "▁broad",
+ "ates",
+ "Before",
+ "▁Both",
+ "which",
+ "▁Great",
+ "▁smoke",
+ "▁cook",
+ "▁apartment",
+ "▁earn",
+ "ja",
+ "▁White",
+ "▁recovery",
+ "ace",
+ "▁circumstances",
+ "cus",
+ "▁Fa",
+ "▁alive",
+ "▁marriage",
+ "▁extend",
+ "▁brown",
+ "▁challenging",
+ "▁belong",
+ "▁operate",
+ "Let",
+ "press",
+ "ue",
+ "▁intention",
+ "Most",
+ "▁rose",
+ "▁contain",
+ "▁talent",
+ "▁attractive",
+ "▁colour",
+ "▁reasonable",
+ "▁necessarily",
+ "▁payment",
+ "▁glad",
+ "▁concern",
+ "▁whom",
+ "▁symptoms",
+ "▁Americans",
+ "▁cards",
+ "ify",
+ "▁degrees",
+ "air",
+ "▁sugar",
+ "▁coverage",
+ "▁flight",
+ "▁importance",
+ "▁fashion",
+ "▁infrastructure",
+ "▁responsibility",
+ "▁turns",
+ "▁director",
+ "▁tired",
+ "▁assist",
+ "▁storage",
+ "▁components",
+ "▁Washington",
+ "ians",
+ "▁hell",
+ "▁enjoyed",
+ "ole",
+ "top",
+ "▁See",
+ "▁waste",
+ "qu",
+ "▁insight",
+ "▁bowl",
+ "ix",
+ "▁pounds",
+ "▁bedroom",
+ "▁concentration",
+ "▁salt",
+ "▁wave",
+ "▁mess",
+ "▁organ",
+ "▁techniques",
+ "Her",
+ "▁speech",
+ "▁basically",
+ "▁versus",
+ "▁sin",
+ "▁copy",
+ "▁quarters",
+ "ctic",
+ "▁predict",
+ "▁Red",
+ "▁Har",
+ "▁tumor",
+ "▁reveal",
+ "▁administration",
+ "▁accounts",
+ "▁enhance",
+ "▁coat",
+ "▁Ja",
+ "▁restaurant",
+ "▁largely",
+ "▁drugs",
+ "▁spin",
+ "▁bringing",
+ "▁lift",
+ "▁trail",
+ "▁department",
+ "▁struggle",
+ "▁topic",
+ "▁Cha",
+ "▁shareholders",
+ "▁detailed",
+ "▁birth",
+ "▁teach",
+ "▁sequence",
+ "▁Friday",
+ "▁input",
+ "hu",
+ "▁Che",
+ "▁sports",
+ "▁narrow",
+ "▁deposit",
+ "▁self",
+ "house",
+ "▁deserve",
+ "▁February",
+ "▁judgment",
+ "▁rights",
+ "ered",
+ "▁silence",
+ "mate",
+ "▁log",
+ "▁item",
+ "▁leads",
+ "▁friendly",
+ "ax",
+ "▁feed",
+ "▁selected",
+ "▁tail",
+ "▁sufficient",
+ "bar",
+ "du",
+ "▁cream",
+ "▁Ch",
+ "room",
+ "▁perfectly",
+ "▁teeth",
+ "▁extent",
+ "▁achieved",
+ "▁underlying",
+ "▁boys",
+ "Y",
+ "▁beach",
+ "▁proposed",
+ "▁encourage",
+ "▁Canada",
+ "▁circle",
+ "▁le",
+ "▁rent",
+ "▁plastic",
+ "▁asset",
+ "▁paying",
+ "▁High",
+ "▁facility",
+ "▁outcome",
+ "▁paint",
+ "▁debate",
+ "▁desk",
+ "▁wondering",
+ "▁equal",
+ "▁prop",
+ "▁participants",
+ "▁manager",
+ "▁kick",
+ "▁France",
+ "▁panel",
+ "ash",
+ "▁fighting",
+ "▁shoot",
+ "down",
+ "▁schools",
+ "▁joy",
+ "▁Lord",
+ "▁flavor",
+ "▁square",
+ "▁row",
+ "▁meat",
+ "▁concerns",
+ "▁names",
+ "▁suggested",
+ "▁outlook",
+ "▁thanks",
+ "ties",
+ "▁depend",
+ "▁matters",
+ "▁district",
+ "▁favor",
+ "▁views",
+ "lor",
+ "▁studied",
+ "▁establish",
+ "▁signs",
+ "▁starts",
+ "Here",
+ "▁opposite",
+ "▁da",
+ "▁fiscal",
+ "▁worst",
+ "▁Ru",
+ "▁adjust",
+ "▁mar",
+ "▁Another",
+ "▁sentence",
+ "▁teaching",
+ "▁acid",
+ "all",
+ "▁possibility",
+ "▁execution",
+ "▁indeed",
+ "▁joint",
+ "▁rid",
+ "yn",
+ "▁injury",
+ "▁Street",
+ "▁conflict",
+ "ky",
+ "win",
+ "▁regions",
+ "▁bond",
+ "▁reward",
+ "▁pitch",
+ "▁laws",
+ "▁laughed",
+ "▁communities",
+ "cor",
+ "▁du",
+ "▁somewhat",
+ "▁Only",
+ "▁river",
+ "▁billion",
+ "▁County",
+ "▁discovered",
+ "▁argue",
+ "▁qua",
+ "▁samples",
+ "▁Nor",
+ "▁Yet",
+ "▁category",
+ "▁survey",
+ "▁named",
+ "▁official",
+ "illa",
+ "▁facilities",
+ "▁component",
+ "▁rare",
+ "▁effectively",
+ "▁advanced",
+ "nie",
+ "▁parent",
+ "▁angry",
+ "▁gap",
+ "▁roof",
+ "▁install",
+ "▁foundation",
+ "▁tri",
+ "▁occurred",
+ "late",
+ "gged",
+ "nal",
+ "▁strike",
+ "▁agreed",
+ "▁Si",
+ "▁border",
+ "▁defend",
+ "▁filter",
+ "▁ultimately",
+ "▁ne",
+ "▁sand",
+ "▁meaningful",
+ "▁procedure",
+ "ject",
+ "▁Thus",
+ "▁experiment",
+ "oma",
+ "▁massive",
+ "▁stuck",
+ "ju",
+ "ening",
+ "▁careful",
+ "▁tiny",
+ "▁intended",
+ "▁During",
+ "▁Pri",
+ "▁finger",
+ "point",
+ "▁century",
+ "▁shopping",
+ "▁beauty",
+ "▁depending",
+ "▁introduced",
+ "log",
+ "▁spa",
+ "▁Ti",
+ "▁calling",
+ "▁Second",
+ "▁pot",
+ "ters",
+ "▁stepped",
+ "▁cars",
+ "rr",
+ "▁App",
+ "▁investors",
+ "▁Str",
+ "▁hi",
+ "▁Cl",
+ "▁hall",
+ "▁protest",
+ "rry",
+ "▁fi",
+ "▁closely",
+ "▁broke",
+ "▁Was",
+ "▁grown",
+ "▁labor",
+ "▁Take",
+ "▁Jack",
+ "▁worried",
+ "▁cu",
+ "▁adapt",
+ "▁medium",
+ "▁Perhaps",
+ "▁neither",
+ "▁routine",
+ "▁m",
+ "▁patterns",
+ "▁feelings",
+ "▁experiences",
+ "ob",
+ "▁appearance",
+ "▁forms",
+ "▁abuse",
+ "▁gotten",
+ "▁bike",
+ "▁nose",
+ "tive",
+ "▁diet",
+ "can",
+ "▁x",
+ "▁dynamic",
+ "▁listening",
+ "▁explained",
+ "▁mod",
+ "▁units",
+ "▁shock",
+ "▁wheel",
+ "▁Tom",
+ "▁ear",
+ "▁pointed",
+ "▁admit",
+ "yl",
+ "▁allowing",
+ "▁monitor",
+ "lation",
+ "▁adult",
+ "▁Make",
+ "▁King",
+ "▁Saturday",
+ "▁habit",
+ "▁blow",
+ "▁brands",
+ "▁constantly",
+ "▁harder",
+ "Therefore",
+ "▁burn",
+ "▁contains",
+ "▁grade",
+ "▁Ad",
+ "▁chemical",
+ "▁Fi",
+ "▁momentum",
+ "▁files",
+ "▁stayed",
+ "▁string",
+ "▁contribute",
+ "▁milk",
+ "▁database",
+ "▁island",
+ "▁everywhere",
+ "▁orders",
+ "▁tomorrow",
+ "▁exact",
+ "▁agent",
+ "book",
+ "▁delay",
+ "▁religious",
+ "▁silent",
+ "▁bound",
+ "▁chart",
+ "ulation",
+ "▁losing",
+ "▁strengthen",
+ "▁tests",
+ "▁fees",
+ "▁defined",
+ "▁numerous",
+ "eration",
+ "rop",
+ "▁split",
+ "▁gu",
+ "▁Finally",
+ "Many",
+ "▁Earth",
+ "▁moral",
+ "▁seriously",
+ "▁standards",
+ "▁Russian",
+ "▁external",
+ "▁planet",
+ "▁recognized",
+ "▁supported",
+ "▁tro",
+ "▁Michael",
+ "▁funny",
+ "▁James",
+ "▁fabric",
+ "uring",
+ "▁bra",
+ "▁walls",
+ "▁hang",
+ "▁Am",
+ "▁integration",
+ "▁feedback",
+ "▁iron",
+ "▁maintenance",
+ "▁Fo",
+ "roll",
+ "▁vary",
+ "▁conclude",
+ "▁pages",
+ "▁plane",
+ "ets",
+ "▁funds",
+ "▁mainly",
+ "▁closing",
+ "▁transformation",
+ "▁Tri",
+ "▁considering",
+ "▁reserve",
+ "▁mini",
+ "▁cheap",
+ "▁gate",
+ "▁occasion",
+ "▁storm",
+ "▁signed",
+ "▁forces",
+ "▁plus",
+ "▁manufacturing",
+ "▁transport",
+ "vent",
+ "▁instrument",
+ "▁depends",
+ "▁curve",
+ "▁bathroom",
+ "han",
+ "▁joined",
+ "Con",
+ "▁recall",
+ "▁valuable",
+ "▁aspects",
+ "▁capture",
+ "▁shirt",
+ "▁Israel",
+ "▁consumers",
+ "▁proof",
+ "▁accepted",
+ "▁improvements",
+ "▁revealed",
+ "▁decades",
+ "▁unable",
+ "▁owner",
+ "lk",
+ "▁react",
+ "▁ratio",
+ "▁grand",
+ "▁somehow",
+ "ators",
+ "▁association",
+ "▁craft",
+ "▁description",
+ "▁format",
+ "▁Ser",
+ "Thank",
+ "▁fer",
+ "▁blame",
+ "▁compare",
+ "▁tall",
+ "▁bread",
+ "▁Texas",
+ "cal",
+ "▁forever",
+ "▁Time",
+ "rie",
+ "▁parameters",
+ "▁School",
+ "▁aside",
+ "▁shadow",
+ "▁bodies",
+ "▁gene",
+ "▁Bu",
+ "ack",
+ "▁winning",
+ "▁Russia",
+ "▁evolution",
+ "▁ph",
+ "how",
+ "▁recorded",
+ "▁resulting",
+ "▁colors",
+ "▁incident",
+ "▁para",
+ "▁surrounding",
+ "▁gaze",
+ "▁practical",
+ "▁stared",
+ "▁cities",
+ "▁television",
+ "Ma",
+ "▁chicken",
+ "lon",
+ "▁taught",
+ "▁Wi",
+ "ister",
+ "▁def",
+ "ung",
+ "ement",
+ "some",
+ "▁folks",
+ "▁hasn",
+ "▁processing",
+ "▁moments",
+ "▁brush",
+ "▁Fe",
+ "▁Which",
+ "▁hoping",
+ "▁indicate",
+ "▁tears",
+ "▁stretch",
+ "▁al",
+ "▁dig",
+ "▁pray",
+ "▁repeat",
+ "▁script",
+ "▁electronic",
+ "▁senior",
+ "▁Mac",
+ "▁Fl",
+ "▁historical",
+ "▁windows",
+ "ford",
+ "▁Any",
+ "▁afford",
+ "▁episode",
+ "▁Air",
+ "▁policies",
+ "▁z",
+ "▁magic",
+ "▁terrible",
+ "▁substantial",
+ "Finally",
+ "▁answers",
+ "atory",
+ "▁pin",
+ "▁thousands",
+ "Q",
+ "▁consideration",
+ "ana",
+ "with",
+ "▁measured",
+ "uch",
+ "Please",
+ "▁profitability",
+ "▁Joe",
+ "▁runs",
+ "▁peak",
+ "▁r",
+ "cho",
+ "▁funding",
+ "▁guarantee",
+ "▁flu",
+ "▁Get",
+ "▁tested",
+ "▁Germany",
+ "▁honor",
+ "▁Still",
+ "oid",
+ "▁relief",
+ "▁Department",
+ "Don",
+ "▁rat",
+ "af",
+ "▁teacher",
+ "▁potentially",
+ "▁counsel",
+ "well",
+ "matic",
+ "ef",
+ "ken",
+ "▁sweat",
+ "▁indicated",
+ "▁photograph",
+ "▁semi",
+ "try",
+ "▁filed",
+ "▁Japan",
+ "▁shoes",
+ "▁prepare",
+ "▁blind",
+ "ette",
+ "load",
+ "▁alcohol",
+ "▁drove",
+ "day",
+ "▁climate",
+ "▁Africa",
+ "▁trick",
+ "lam",
+ "▁Comp",
+ "▁records",
+ "▁deals",
+ "▁violence",
+ "▁advertising",
+ "▁vast",
+ "read",
+ "▁expressed",
+ "▁functional",
+ "▁technique",
+ "▁barely",
+ "nes",
+ "emp",
+ "▁increasingly",
+ "▁definition",
+ "▁Congress",
+ "▁Australia",
+ "▁partnership",
+ "▁politics",
+ "▁Florida",
+ "▁Add",
+ "▁creation",
+ "▁plaintiff",
+ "▁adjusted",
+ "▁assessment",
+ "▁greatest",
+ "▁industrial",
+ "▁cop",
+ "▁environmental",
+ "lay",
+ "pon",
+ "▁algorithm",
+ "▁breakfast",
+ "▁diagnosis",
+ "▁entry",
+ "Like",
+ "▁loose",
+ "▁lean",
+ "▁Look",
+ "▁George",
+ "▁Center",
+ "▁upper",
+ "▁motor",
+ "▁frequently",
+ "▁agents",
+ "▁approximately",
+ "▁Monday",
+ "De",
+ "▁neuro",
+ "nder",
+ "▁stupid",
+ "▁younger",
+ "▁Western",
+ "▁Use",
+ "▁fly",
+ "▁passion",
+ "▁Church",
+ "▁j",
+ "▁nervous",
+ "len",
+ "▁Com",
+ "▁William",
+ "Ex",
+ "▁mirror",
+ "lly",
+ "▁typical",
+ "▁sport",
+ "ied",
+ "▁generated",
+ "▁symbol",
+ "▁cheese",
+ "▁ski",
+ "▁yesterday",
+ "▁assess",
+ "▁Over",
+ "ular",
+ "bil",
+ "▁ease",
+ "▁contribution",
+ "▁Thanks",
+ "▁disorder",
+ "▁chosen",
+ "▁hide",
+ "▁fee",
+ "▁choices",
+ "▁village",
+ "▁fantastic",
+ "aries",
+ "▁accurate",
+ "Maybe",
+ "▁session",
+ "▁Ed",
+ "▁trigger",
+ "▁dogs",
+ "▁causes",
+ "▁fifth",
+ "▁throat",
+ "▁pla",
+ "▁fo",
+ "▁sides",
+ "▁revenues",
+ "▁den",
+ "▁extended",
+ "des",
+ "▁luck",
+ "▁painting",
+ "▁division",
+ "ising",
+ "▁waited",
+ "▁medicine",
+ "ump",
+ "mic",
+ "▁resolution",
+ "ka",
+ "▁criminal",
+ "▁successfully",
+ "▁provision",
+ "▁materially",
+ "▁output",
+ "▁extensive",
+ "▁fellow",
+ "▁capable",
+ "▁peer",
+ "▁savings",
+ "▁technologies",
+ "▁Green",
+ "▁skill",
+ "▁religion",
+ "▁nurse",
+ "tel",
+ "▁arrive",
+ "cept",
+ "▁Today",
+ "▁chi",
+ "▁album",
+ "▁compete",
+ "▁forth",
+ "▁Everyone",
+ "▁ver",
+ "▁Peter",
+ "▁notes",
+ "Thus",
+ "▁str",
+ "gue",
+ "▁chose",
+ "▁fault",
+ "▁genetic",
+ "▁kiss",
+ "▁relax",
+ "▁locations",
+ "▁anger",
+ "▁dedicated",
+ "▁Lu",
+ "ttle",
+ "▁conservative",
+ "▁neighbor",
+ "▁scenario",
+ "▁Pat",
+ "▁stated",
+ "pri",
+ "▁complicated",
+ "▁engagement",
+ "▁domain",
+ "▁stars",
+ "▁volumes",
+ "fu",
+ "▁chat",
+ "▁hole",
+ "▁evaluate",
+ "▁bomb",
+ "rac",
+ "▁exception",
+ "▁approval",
+ "▁muscle",
+ "▁posted",
+ "▁somebody",
+ "▁identity",
+ "dding",
+ "▁comm",
+ "▁fields",
+ "▁Cr",
+ "▁mechanism",
+ "▁dozen",
+ "▁longterm",
+ "▁domestic",
+ "vol",
+ "▁library",
+ "ale",
+ "▁minimum",
+ "▁brings",
+ "long",
+ "▁According",
+ "▁bridge",
+ "jo",
+ "▁demonstrated",
+ "▁lawyer",
+ "▁shake",
+ "▁lucky",
+ "▁highlight",
+ "▁premium",
+ "▁suspect",
+ "▁conducted",
+ "▁retain",
+ "▁drawing",
+ "▁cultural",
+ "▁origin",
+ "▁Art",
+ "phy",
+ "▁officer",
+ "▁stomach",
+ "zz",
+ "▁frequency",
+ "▁famous",
+ "▁succeed",
+ "▁pure",
+ "▁define",
+ "▁dimension",
+ "▁Does",
+ "▁owners",
+ "▁liquid",
+ "According",
+ "cycl",
+ "▁objects",
+ "▁facts",
+ "▁agency",
+ "▁variation",
+ "cer",
+ "▁doors",
+ "▁officers",
+ "▁reform",
+ "▁charges",
+ "▁outcomes",
+ "▁facing",
+ "▁replace",
+ "▁nobody",
+ "▁column",
+ "▁practices",
+ "gra",
+ "▁intervention",
+ "▁dust",
+ "▁formal",
+ "▁drivers",
+ "gar",
+ "▁explanation",
+ "▁cheek",
+ "▁north",
+ "struct",
+ "▁danger",
+ "▁expert",
+ "▁i",
+ "▁represents",
+ "▁confirmed",
+ "▁Bill",
+ "▁bother",
+ "▁south",
+ "nic",
+ "▁height",
+ "▁serving",
+ "▁cry",
+ "▁hyper",
+ "▁objective",
+ "▁wire",
+ "▁Mary",
+ "▁minor",
+ "▁recover",
+ "lia",
+ "▁resistance",
+ "▁existence",
+ "▁hardly",
+ "ugh",
+ "ons",
+ "▁guests",
+ "▁meal",
+ "ray",
+ "▁plays",
+ "wood",
+ "▁ramp",
+ "▁MM",
+ "▁witness",
+ "▁acquisitions",
+ "▁readers",
+ "▁lights",
+ "▁collected",
+ "▁depth",
+ "▁officials",
+ "pers",
+ "▁Gi",
+ "▁thread",
+ "▁spiritual",
+ "▁cho",
+ "▁crew",
+ "▁crash",
+ "▁mad",
+ "▁Un",
+ "itive",
+ "▁cake",
+ "mar",
+ "▁award",
+ "osis",
+ "▁Sal",
+ "▁cluster",
+ "duct",
+ "▁tie",
+ "▁implementation",
+ "▁Mark",
+ "ov",
+ "▁dealing",
+ "▁poll",
+ "▁contracts",
+ "▁pleasure",
+ "▁experts",
+ "▁discount",
+ "▁quote",
+ "▁landscape",
+ "▁colon",
+ "ock",
+ "▁delivering",
+ "▁wondered",
+ "▁steel",
+ "ez",
+ "▁Commission",
+ "▁butter",
+ "▁communicate",
+ "▁strain",
+ "▁breast",
+ "▁awesome",
+ "▁yellow",
+ "▁crisis",
+ "▁tip",
+ "▁attitude",
+ "ella",
+ "▁suffer",
+ "▁et",
+ "▁confirm",
+ "▁links",
+ "old",
+ "▁automatically",
+ "▁documents",
+ "▁uses",
+ "▁blend",
+ "▁squ",
+ "▁false",
+ "▁lung",
+ "▁attend",
+ "▁incredible",
+ "▁expertise",
+ "▁approved",
+ "hood",
+ "▁strongly",
+ "▁joke",
+ "▁shower",
+ "▁categories",
+ "▁disc",
+ "rg",
+ "▁Frank",
+ "▁Ni",
+ "▁draft",
+ "▁shoulders",
+ "▁supplement",
+ "▁evil",
+ "mal",
+ "▁Reg",
+ "▁lovely",
+ "▁port",
+ "▁deeply",
+ "▁visitors",
+ "▁purposes",
+ "ches",
+ "▁unknown",
+ "▁tips",
+ "▁sets",
+ "▁Je",
+ "▁Bank",
+ "sp",
+ "▁channels",
+ "▁deeper",
+ "aving",
+ "▁summary",
+ "▁rev",
+ "ev",
+ "▁literature",
+ "ya",
+ "▁tonight",
+ "▁pi",
+ "▁General",
+ "▁plot",
+ "▁rank",
+ "▁Nothing",
+ "▁flexibility",
+ "▁scheme",
+ "▁formed",
+ "▁pursue",
+ "▁suffering",
+ "▁n",
+ "▁laid",
+ "▁raw",
+ "▁Dan",
+ "▁sensor",
+ "ivity",
+ "▁Apple",
+ "▁authority",
+ "▁Last",
+ "▁Min",
+ "▁Bi",
+ "▁obligation",
+ "▁weird",
+ "▁checked",
+ "▁personally",
+ "▁mixed",
+ "▁lying",
+ "▁gear",
+ "▁shooting",
+ "▁uncertainties",
+ "▁commission",
+ "▁cooking",
+ "▁god",
+ "▁forest",
+ "▁exit",
+ "▁Ter",
+ "▁grip",
+ "▁Again",
+ "▁wh",
+ "▁regulatory",
+ "▁maximum",
+ "▁angle",
+ "▁coast",
+ "▁curious",
+ "▁drinking",
+ "▁ingredients",
+ "▁normally",
+ "▁zone",
+ "▁complain",
+ "▁taxes",
+ "▁ordered",
+ "mat",
+ "▁investing",
+ "▁suppose",
+ "▁Cla",
+ "▁Japanese",
+ "▁menu",
+ "▁seeking",
+ "▁currency",
+ "▁forecast",
+ "▁exceed",
+ "atic",
+ "▁publish",
+ "ib",
+ "ked",
+ "Instead",
+ "▁Cal",
+ "▁reliable",
+ "Every",
+ "▁integrated",
+ "rant",
+ "▁chip",
+ "bal",
+ "▁writer",
+ "▁Mr",
+ "gy",
+ "Go",
+ "▁remarks",
+ "▁formation",
+ "box",
+ "▁executive",
+ "▁sauce",
+ "ily",
+ "▁grabbed",
+ "lie",
+ "▁Would",
+ "▁Muslim",
+ "▁positions",
+ "▁robust",
+ "▁volunteer",
+ "▁civil",
+ "nda",
+ "rous",
+ "▁humans",
+ "▁execute",
+ "▁convert",
+ "▁Asia",
+ "▁bunch",
+ "▁alter",
+ "▁decade",
+ "▁suggests",
+ "▁boost",
+ "Co",
+ "▁slip",
+ "▁tells",
+ "▁Right",
+ "▁organizations",
+ "▁permanent",
+ "▁homes",
+ "▁Keep",
+ "▁attorney",
+ "▁finance",
+ "▁classic",
+ "▁bath",
+ "▁wake",
+ "▁hip",
+ "▁equity",
+ "▁ill",
+ "▁mono",
+ "lit",
+ "▁poly",
+ "▁rush",
+ "▁unusual",
+ "▁rapidly",
+ "▁Mike",
+ "▁epi",
+ "▁attract",
+ "▁decor",
+ "▁tank",
+ "▁nearby",
+ "▁aspect",
+ "▁electric",
+ "▁falling",
+ "▁apparently",
+ "▁grass",
+ "▁neighborhood",
+ "▁trained",
+ "▁strip",
+ "▁priority",
+ "▁anticipate",
+ "▁encouraged",
+ "state",
+ "▁Mor",
+ "▁characteristics",
+ "▁upgrade",
+ "▁complaint",
+ "▁prayer",
+ "▁leaned",
+ "▁cleaning",
+ "▁Star",
+ "▁launched",
+ "▁tap",
+ "▁teachers",
+ "▁Big",
+ "▁flag",
+ "▁productivity",
+ "▁reducing",
+ "▁Ken",
+ "rup",
+ "otic",
+ "▁plain",
+ "▁extract",
+ "▁passing",
+ "▁hill",
+ "▁lies",
+ "gr",
+ "▁justice",
+ "▁aid",
+ "▁sum",
+ "▁rolled",
+ "▁recommended",
+ "cl",
+ "▁introduce",
+ "▁exc",
+ "▁lit",
+ "vin",
+ "▁regularly",
+ "▁celebrate",
+ "▁proposal",
+ "▁array",
+ "▁Hi",
+ "▁mood",
+ "een",
+ "▁supporting",
+ "▁tradition",
+ "▁index",
+ "▁transform",
+ "▁saved",
+ "▁hidden",
+ "▁attribute",
+ "▁targets",
+ "▁medication",
+ "pha",
+ "▁dev",
+ "▁Mer",
+ "▁memories",
+ "▁evaluation",
+ "▁Rob",
+ "▁exp",
+ "▁pump",
+ "▁slight",
+ "▁adults",
+ "erson",
+ "▁compound",
+ "▁shit",
+ "hen",
+ "▁warrant",
+ "▁adjustment",
+ "lies",
+ "▁circuit",
+ "▁dish",
+ "▁articles",
+ "lock",
+ "▁chocolate",
+ "turn",
+ "▁latter",
+ "▁eliminate",
+ "▁posts",
+ "▁sensitive",
+ "▁scientific",
+ "▁chapter",
+ "▁virus",
+ "▁engage",
+ "are",
+ "bit",
+ "net",
+ "▁physician",
+ "cap",
+ "▁merely",
+ "▁wound",
+ "▁fu",
+ "▁examples",
+ "▁wrap",
+ "▁segments",
+ "bl",
+ "▁CD",
+ "▁banks",
+ "▁nuclear",
+ "▁movies",
+ "▁deck",
+ "▁Health",
+ "lect",
+ "▁ju",
+ "▁dose",
+ "gging",
+ "▁positioned",
+ "not",
+ "▁Te",
+ "▁destroy",
+ "▁wing",
+ "▁variable",
+ "▁Unfortunately",
+ "▁representative",
+ "▁intra",
+ "▁genes",
+ "ook",
+ "▁dividend",
+ "▁Mexico",
+ "▁listed",
+ "tz",
+ "dent",
+ "▁survive",
+ "▁br",
+ "▁scan",
+ "▁refused",
+ "▁emergency",
+ "▁hat",
+ "▁parking",
+ "▁acknowledge",
+ "▁silver",
+ "itch",
+ "▁Everything",
+ "ddle",
+ "flow",
+ "▁estimate",
+ "▁syn",
+ "▁rely",
+ "▁Win",
+ "▁enterprise",
+ "▁graduate",
+ "▁payments",
+ "ica",
+ "rb",
+ "▁Alex",
+ "▁y",
+ "▁touched",
+ "▁uniform",
+ "▁decent",
+ "vic",
+ "▁Part",
+ "▁noted",
+ "▁disagree",
+ "▁importantly",
+ "▁framework",
+ "▁resource",
+ "▁outdoor",
+ "van",
+ "▁beer",
+ "▁follows",
+ "▁participate",
+ "▁Roman",
+ "▁intend",
+ "▁intense",
+ "while",
+ "vy",
+ "▁exhibit",
+ "ino",
+ "▁defeat",
+ "▁tone",
+ "tract",
+ "▁Robert",
+ "▁songs",
+ "▁loans",
+ "stand",
+ "▁experiments",
+ "▁updated",
+ "bel",
+ "▁incredibly",
+ "▁awareness",
+ "▁River",
+ "▁Sch",
+ "▁interests",
+ "▁Super",
+ "▁reverse",
+ "chan",
+ "▁centre",
+ "▁situations",
+ "▁examination",
+ "▁enemy",
+ "▁Canadian",
+ "▁artist",
+ "▁begins",
+ "▁Union",
+ "▁flowers",
+ "▁suck",
+ "ography",
+ "▁examine",
+ "▁receiving",
+ "▁mask",
+ "▁furniture",
+ "▁anybody",
+ "▁loop",
+ "▁charged",
+ "▁limitations",
+ "▁engaged",
+ "▁reporting",
+ "▁superior",
+ "graph",
+ "▁expecting",
+ "cle",
+ "eth",
+ "▁Bay",
+ "▁correlation",
+ "▁interaction",
+ "▁permit",
+ "stone",
+ "▁belief",
+ "▁messages",
+ "▁steady",
+ "▁Life",
+ "▁Ph",
+ "ong",
+ "▁cent",
+ "▁duty",
+ "▁mal",
+ "▁newspaper",
+ "▁crucial",
+ "xi",
+ "▁conversion",
+ "▁housing",
+ "▁ga",
+ "▁vital",
+ "▁drawn",
+ "▁remote",
+ "bri",
+ "▁killing",
+ "fl",
+ "equ",
+ "▁immediate",
+ "Can",
+ "▁inform",
+ "▁EU",
+ "▁tremendous",
+ "▁vehicles",
+ "pen",
+ "ional",
+ "▁essentially",
+ "▁candidate",
+ "▁stands",
+ "▁lease",
+ "▁mechanisms",
+ "▁streets",
+ "▁trading",
+ "list",
+ "▁exists",
+ "▁literally",
+ "▁rising",
+ "▁saving",
+ "▁pur",
+ "▁Du",
+ "▁intelligence",
+ "▁Sun",
+ "OS",
+ "▁era",
+ "▁warning",
+ "Each",
+ "▁remembered",
+ "▁academic",
+ "▁creature",
+ "ote",
+ "path",
+ "ith",
+ "bin",
+ "▁contained",
+ "pir",
+ "▁Hol",
+ "▁implement",
+ "▁Inter",
+ "▁absolute",
+ "▁Tuesday",
+ "▁manufacturer",
+ "▁scared",
+ "▁pilot",
+ "▁damn",
+ "▁proportion",
+ "▁ref",
+ "▁delicious",
+ "ball",
+ "▁bias",
+ "▁emotions",
+ "▁drain",
+ "▁Home",
+ "▁league",
+ "▁prompt",
+ "▁employee",
+ "▁visible",
+ "▁rear",
+ "▁Up",
+ "ville",
+ "Ca",
+ "▁rarely",
+ "▁bull",
+ "▁extreme",
+ "▁fulfill",
+ "▁performing",
+ "▁studio",
+ "▁videos",
+ "▁naturally",
+ "▁bug",
+ "▁burden",
+ "ware",
+ "▁pal",
+ "▁impacted",
+ "▁structures",
+ "▁ignore",
+ "▁knee",
+ "▁Though",
+ "▁inner",
+ "▁recognition",
+ "▁League",
+ "▁Yeah",
+ "▁cutting",
+ "▁critic",
+ "▁authors",
+ "▁Twitter",
+ "▁figures",
+ "▁informed",
+ "▁ancient",
+ "▁grab",
+ "▁comprehensive",
+ "▁anxiety",
+ "▁regional",
+ "▁Bro",
+ "▁variables",
+ "▁managing",
+ "▁residents",
+ "▁Board",
+ "▁Bea",
+ "▁whenever",
+ "▁approaches",
+ "▁carrying",
+ "▁tra",
+ "▁filing",
+ "▁extension",
+ "▁subjects",
+ "▁node",
+ "▁suitable",
+ "▁adventure",
+ "▁losses",
+ "▁Under",
+ "▁Very",
+ "▁headed",
+ "shed",
+ "▁hook",
+ "▁gentle",
+ "▁Work",
+ "bble",
+ "▁upset",
+ "▁rum",
+ "▁ri",
+ "▁controlled",
+ "▁knock",
+ "▁struck",
+ "▁lap",
+ "▁equation",
+ "▁replaced",
+ "▁expanding",
+ "▁attacks",
+ "▁universe",
+ "don",
+ "▁anticipated",
+ "▁ban",
+ "▁initially",
+ "▁proteins",
+ "igh",
+ "head",
+ "▁Read",
+ "▁joining",
+ "▁flood",
+ "▁hero",
+ "▁wage",
+ "▁scar",
+ "▁Shi",
+ "▁rooms",
+ "chi",
+ "▁causing",
+ "▁seconds",
+ "tail",
+ "gress",
+ "▁kinds",
+ "▁stack",
+ "onic",
+ "▁privacy",
+ "bra",
+ "▁Web",
+ "▁Group",
+ "▁weapons",
+ "▁tag",
+ "▁detect",
+ "▁buildings",
+ "▁survival",
+ "▁Plan",
+ "▁spell",
+ "▁threw",
+ "▁Ke",
+ "▁kit",
+ "▁letting",
+ "ese",
+ "▁settings",
+ "▁discipline",
+ "▁networks",
+ "▁sustainable",
+ "itis",
+ "▁clinic",
+ "lig",
+ "▁holds",
+ "▁acquired",
+ "▁Ab",
+ "▁tape",
+ "▁paused",
+ "▁stability",
+ "▁exposed",
+ "▁searching",
+ "▁rating",
+ "▁reviews",
+ "▁Lake",
+ "▁mixture",
+ "▁cookies",
+ "▁guilty",
+ "▁inhibit",
+ "▁installed",
+ "Any",
+ "▁letters",
+ "▁interact",
+ "▁rational",
+ "▁cor",
+ "▁Republican",
+ "▁wealth",
+ "▁chronic",
+ "▁MS",
+ "▁fluid",
+ "▁breaking",
+ "▁African",
+ "▁soil",
+ "▁l",
+ "▁Brazil",
+ "lea",
+ "▁hire",
+ "▁involve",
+ "▁focusing",
+ "▁dreams",
+ "▁Va",
+ "ough",
+ "▁default",
+ "▁stain",
+ "▁procedures",
+ "▁Love",
+ "▁grant",
+ "ulated",
+ "▁Tu",
+ "▁assistance",
+ "▁heavily",
+ "▁millions",
+ "▁Em",
+ "▁experimental",
+ "▁density",
+ "▁favorable",
+ "▁bow",
+ "▁atmosphere",
+ "▁conventional",
+ "Okay",
+ "▁assumptions",
+ "▁id",
+ "ili",
+ "▁attached",
+ "▁candidates",
+ "▁illegal",
+ "▁AM",
+ "▁distinct",
+ "▁interpret",
+ "▁discussions",
+ "▁arch",
+ "▁beneath",
+ "▁Next",
+ "▁locked",
+ "▁swing",
+ "▁native",
+ "▁Wednesday",
+ "▁absorb",
+ "▁moon",
+ "oe",
+ "▁breathing",
+ "▁clock",
+ "▁instructions",
+ "▁u",
+ "▁faced",
+ "▁franchise",
+ "▁revolution",
+ "▁mon",
+ "▁mortgage",
+ "▁birthday",
+ "▁Tru",
+ "sure",
+ "pre",
+ "▁consequences",
+ "▁confused",
+ "▁Come",
+ "▁preparation",
+ "▁Smith",
+ "▁hum",
+ "▁statistical",
+ "▁recording",
+ "▁boss",
+ "▁pushing",
+ "▁Despite",
+ "play",
+ "▁aggressive",
+ "▁linear",
+ "▁issued",
+ "▁AC",
+ "uous",
+ "zy",
+ "▁pathway",
+ "▁Island",
+ "▁register",
+ "▁everyday",
+ "▁proven",
+ "▁reader",
+ "▁widely",
+ "▁Britain",
+ "▁investigate",
+ "▁magazine",
+ "▁van",
+ "▁soldiers",
+ "▁scratch",
+ "▁moves",
+ "▁Op",
+ "▁reputation",
+ "ria",
+ "pher",
+ "▁impressive",
+ "py",
+ "fall",
+ "▁marketplace",
+ "▁minimal",
+ "▁Bible",
+ "▁linked",
+ "▁sink",
+ "▁Chicago",
+ "▁consult",
+ "▁container",
+ "▁restaurants",
+ "wo",
+ "▁import",
+ "▁responses",
+ "▁regardless",
+ "▁pad",
+ "▁resulted",
+ "▁Such",
+ "▁differently",
+ "▁Dad",
+ "▁acting",
+ "▁eggs",
+ "▁university",
+ "▁secondary",
+ "ching",
+ "▁rough",
+ "Both",
+ "▁assumed",
+ "pper",
+ "▁dec",
+ "oke",
+ "▁lifted",
+ "▁gonna",
+ "▁recruit",
+ "▁Bri",
+ "▁reflected",
+ "▁Clinton",
+ "▁possess",
+ "▁etc",
+ "▁arrangement",
+ "▁organized",
+ "▁profitable",
+ "▁union",
+ "▁intent",
+ "▁mat",
+ "▁jury",
+ "met",
+ "▁Something",
+ "▁absence",
+ "▁destination",
+ "▁embrace",
+ "▁employer",
+ "▁consistently",
+ "where",
+ "▁appointment",
+ "▁combine",
+ "▁tasks",
+ "mination",
+ "die",
+ "▁examined",
+ "▁carrier",
+ "▁borrow",
+ "▁shipping",
+ "cra",
+ "▁provider",
+ "▁competitors",
+ "▁transactions",
+ "▁resist",
+ "dia",
+ "▁army",
+ "▁Bob",
+ "▁knees",
+ "▁leak",
+ "▁PM",
+ "▁flying",
+ "▁grateful",
+ "▁targeted",
+ "▁op",
+ "▁incremental",
+ "rated",
+ "▁opt",
+ "arch",
+ "▁melt",
+ "ancy",
+ "▁limits",
+ "▁gender",
+ "▁staying",
+ "▁giant",
+ "meter",
+ "ux",
+ "▁sleeping",
+ "▁formula",
+ "▁trace",
+ "▁replacement",
+ "▁consent",
+ "put",
+ "▁submit",
+ "▁darkness",
+ "▁settled",
+ "▁airport",
+ "Second",
+ "▁valid",
+ "▁Him",
+ "▁maintaining",
+ "▁sounded",
+ "Se",
+ "▁expanded",
+ "▁victim",
+ "▁Jewish",
+ "rating",
+ "▁hanging",
+ "▁citizens",
+ "▁cable",
+ "▁visiting",
+ "▁Dar",
+ "▁slid",
+ "▁Thursday",
+ "▁Sta",
+ "▁Adam",
+ "▁Council",
+ "▁occurs",
+ "▁encounter",
+ "▁outstanding",
+ "position",
+ "▁criteria",
+ "▁protocol",
+ "▁inspired",
+ "▁immune",
+ "▁boil",
+ "▁commit",
+ "▁denied",
+ "ene",
+ "▁youth",
+ "▁stroke",
+ "▁indication",
+ "▁impression",
+ "▁diseases",
+ "▁depression",
+ "▁Paris",
+ "▁fri",
+ "▁platforms",
+ "▁excuse",
+ "▁instant",
+ "▁vessel",
+ "▁sal",
+ "table",
+ "▁Brown",
+ "▁Four",
+ "▁rapid",
+ "▁Trans",
+ "▁fleet",
+ "▁principle",
+ "▁loving",
+ "▁vertical",
+ "lish",
+ "range",
+ "▁crystal",
+ "▁dynamics",
+ "▁Iraq",
+ "▁exceptional",
+ "▁browser",
+ "▁graphic",
+ "▁guest",
+ "▁authorities",
+ "▁partially",
+ "▁implemented",
+ "▁Service",
+ "▁doctors",
+ "▁Dis",
+ "More",
+ "▁lifestyle",
+ "▁Grand",
+ "▁sudden",
+ "▁desired",
+ "▁battery",
+ "▁originally",
+ "▁burst",
+ "▁suffered",
+ "▁engineering",
+ "▁supplier",
+ "▁optimize",
+ "▁Without",
+ "▁Government",
+ "Other",
+ "▁completion",
+ "like",
+ "▁sending",
+ "▁Could",
+ "▁dear",
+ "hor",
+ "rov",
+ "▁mount",
+ "▁settle",
+ "▁wash",
+ "▁dealer",
+ "▁engineer",
+ "▁sixth",
+ "▁staring",
+ "▁dependent",
+ "own",
+ "aging",
+ "ett",
+ "▁knife",
+ "▁hunt",
+ "Another",
+ "▁ID",
+ "▁diverse",
+ "▁household",
+ "▁owned",
+ "ologist",
+ "new",
+ "▁interpretation",
+ "▁equally",
+ "▁scrap",
+ "▁emerge",
+ "▁wise",
+ "▁moderate",
+ "▁disappear",
+ "▁passenger",
+ "▁drew",
+ "▁preferred",
+ "▁inflation",
+ "▁installation",
+ "▁ocean",
+ "▁patch",
+ "▁calculation",
+ "▁Play",
+ "▁juice",
+ "▁lady",
+ "▁figured",
+ "▁spark",
+ "▁cheer",
+ "▁pit",
+ "▁div",
+ "▁pepper",
+ "▁Sea",
+ "▁consumption",
+ "▁pretend",
+ "▁Amazon",
+ "▁shade",
+ "▁alarm",
+ "▁granted",
+ "uction",
+ "▁professionals",
+ "▁committee",
+ "▁supplies",
+ "wise",
+ "iff",
+ "Despite",
+ "▁essay",
+ "▁weakness",
+ "▁corresponding",
+ "▁reflects",
+ "▁Sure",
+ "▁speaker",
+ "▁excess",
+ "PS",
+ "▁stairs",
+ "▁Party",
+ "▁Steve",
+ "iz",
+ "▁ruin",
+ "▁painful",
+ "▁Italian",
+ "▁interface",
+ "▁Richard",
+ "▁rental",
+ "▁casual",
+ "▁Ge",
+ "▁subsequent",
+ "▁providers",
+ "▁estimated",
+ "▁hardware",
+ "▁marked",
+ "▁Catholic",
+ "▁institutions",
+ "▁injuries",
+ "▁sought",
+ "▁papers",
+ "▁plea",
+ "▁Cu",
+ "▁childhood",
+ "▁king",
+ "▁International",
+ "▁programme",
+ "▁answered",
+ "▁jo",
+ "▁hung",
+ "▁clo",
+ "char",
+ "▁innovative",
+ "▁Jim",
+ "oon",
+ "Today",
+ "▁mill",
+ "ital",
+ "▁accuracy",
+ "▁Middle",
+ "umb",
+ "▁nerve",
+ "▁branch",
+ "▁stages",
+ "ore",
+ "▁tear",
+ "gle",
+ "▁pink",
+ "▁ears",
+ "▁fiber",
+ "▁panic",
+ "▁modest",
+ "▁relation",
+ "▁updates",
+ "fil",
+ "▁bird",
+ "▁enhanced",
+ "gene",
+ "▁pulling",
+ "▁compensation",
+ "▁regret",
+ "▁capability",
+ "▁lens",
+ "▁wore",
+ "▁bat",
+ "▁Whether",
+ "▁comparable",
+ "▁snap",
+ "▁ir",
+ "pot",
+ "▁bake",
+ "▁Old",
+ "▁inspiration",
+ "▁CS",
+ "▁gently",
+ "▁Democrats",
+ "isation",
+ "▁principles",
+ "▁illness",
+ "IS",
+ "▁steal",
+ "▁seal",
+ "▁Windows",
+ "loc",
+ "▁disturb",
+ "▁interior",
+ "rick",
+ "▁charm",
+ "▁nail",
+ "▁winner",
+ "cut",
+ "▁vacation",
+ "place",
+ "▁pressed",
+ "Li",
+ "Their",
+ "▁introduction",
+ "▁shame",
+ "▁Chris",
+ "▁correctly",
+ "sha",
+ "▁collapse",
+ "PA",
+ "omic",
+ "▁Martin",
+ "▁satisfaction",
+ "▁structural",
+ "▁decreased",
+ "vari",
+ "▁Pan",
+ "▁respectively",
+ "▁Hill",
+ "▁fewer",
+ "▁advise",
+ "▁grace",
+ "▁leather",
+ "▁representation",
+ "▁barrier",
+ "▁Moreover",
+ "▁pound",
+ "▁insert",
+ "▁satisfied",
+ "▁enormous",
+ "lash",
+ "▁convenient",
+ "▁satisfy",
+ "▁Jeff",
+ "nge",
+ "▁heading",
+ "fr",
+ "▁composition",
+ "▁export",
+ "▁protected",
+ "Pa",
+ "▁handed",
+ "▁begun",
+ "▁visited",
+ "▁awful",
+ "ulate",
+ "▁scope",
+ "▁clothing",
+ "▁preference",
+ "▁chief",
+ "▁biological",
+ "▁arise",
+ "▁Ly",
+ "▁pu",
+ "Lo",
+ "▁transmission",
+ "▁audio",
+ "water",
+ "▁grave",
+ "Com",
+ "▁yard",
+ "▁fold",
+ "▁dressed",
+ "ero",
+ "▁pride",
+ "icle",
+ "▁errors",
+ "▁artists",
+ "▁tied",
+ "▁restore",
+ "▁hoped",
+ "▁logic",
+ "▁flexible",
+ "direct",
+ "▁prim",
+ "Those",
+ "▁overcome",
+ "cro",
+ "▁Harry",
+ "▁preserve",
+ "▁ordinary",
+ "▁accounting",
+ "▁returning",
+ "▁tune",
+ "iding",
+ "▁mild",
+ "▁sponsor",
+ "▁liver",
+ "▁Sw",
+ "▁invited",
+ "▁permission",
+ "Over",
+ "▁rang",
+ "▁maintained",
+ "elle",
+ "▁adequate",
+ "▁Bra",
+ "▁consume",
+ "▁ray",
+ "▁blocks",
+ "ively",
+ "▁periods",
+ "▁scheduled",
+ "▁editor",
+ "▁authentic",
+ "nne",
+ "▁monthly",
+ "▁represented",
+ "▁lifetime",
+ "▁unexpected",
+ "▁involves",
+ "▁spectrum",
+ "▁prediction",
+ "▁jacket",
+ "▁announcement",
+ "▁forgotten",
+ "▁Ko",
+ "▁pleasant",
+ "▁bid",
+ "▁tension",
+ "▁Pla",
+ "▁texture",
+ "▁Three",
+ "▁legacy",
+ "▁personality",
+ "▁mistakes",
+ "▁punch",
+ "▁victory",
+ "▁Matt",
+ "▁orange",
+ "▁pile",
+ "▁estimates",
+ "▁crossed",
+ "zo",
+ "▁participation",
+ "▁Wa",
+ "▁pie",
+ "▁designer",
+ "▁opposed",
+ "▁ni",
+ "▁sail",
+ "▁sighed",
+ "▁Queen",
+ "▁lake",
+ "▁gray",
+ "▁fallen",
+ "hal",
+ "▁greatly",
+ "▁radical",
+ "▁module",
+ "▁tongue",
+ "▁Bur",
+ "Yet",
+ "▁carbon",
+ "▁clip",
+ "▁Out",
+ "▁detection",
+ "▁edit",
+ "▁reaching",
+ "body",
+ "▁regulation",
+ "▁destroyed",
+ "▁venture",
+ "▁evaluated",
+ "▁icon",
+ "▁DC",
+ "▁OK",
+ "▁weapon",
+ "nate",
+ "▁detected",
+ "▁Ste",
+ "▁Furthermore",
+ "▁actively",
+ "▁simulation",
+ "▁render",
+ "▁opponent",
+ "▁entertainment",
+ "▁ticket",
+ "hel",
+ "▁expectation",
+ "▁affordable",
+ "▁adopt",
+ "▁jumped",
+ "▁slice",
+ "▁Remember",
+ "▁rolling",
+ "▁College",
+ "▁agencies",
+ "▁happiness",
+ "▁accelerate",
+ "▁publication",
+ "▁investigated",
+ "▁chill",
+ "▁Miss",
+ "arian",
+ "▁seventh",
+ "▁crop",
+ "▁tech",
+ "Z",
+ "▁screw",
+ "▁graph",
+ "▁Game",
+ "▁muscles",
+ "▁convinced",
+ "AC",
+ "▁purchased",
+ "▁Australian",
+ "▁tube",
+ "▁continuous",
+ "▁scores",
+ "▁signals",
+ "▁concrete",
+ "▁dining",
+ "ature",
+ "▁Rock",
+ "▁brilliant",
+ "▁Try",
+ "▁Gar",
+ "▁pipe",
+ "▁ought",
+ "▁meetings",
+ "▁Thomas",
+ "Furthermore",
+ "▁promotion",
+ "▁proved",
+ "▁fired",
+ "▁corn",
+ "▁unlikely",
+ "▁Mom",
+ "▁invention",
+ "▁surgical",
+ "▁birds",
+ "cast",
+ "j",
+ "▁boxes",
+ "▁trials",
+ "▁calculated",
+ "▁violent",
+ "▁Chi",
+ "▁asleep",
+ "▁Luc",
+ "▁gains",
+ "Sometimes",
+ "▁availability",
+ "▁construct",
+ "▁Los",
+ "▁weigh",
+ "▁employment",
+ "▁translate",
+ "ele",
+ "ache",
+ "▁observation",
+ "▁Er",
+ "▁architecture",
+ "▁choosing",
+ "▁claimed",
+ "▁producing",
+ "▁Bel",
+ "▁tin",
+ "▁monitoring",
+ "▁powder",
+ "▁Think",
+ "▁Ver",
+ "ocyte",
+ "▁deny",
+ "you",
+ "▁contributed",
+ "▁healing",
+ "▁Slide",
+ "wing",
+ "print",
+ "▁climb",
+ "▁audit",
+ "▁acquire",
+ "▁Mil",
+ "▁CT",
+ "▁crush",
+ "claim",
+ "▁analyzed",
+ "▁elsewhere",
+ "▁Men",
+ "▁gut",
+ "▁lab",
+ "▁confront",
+ "▁bars",
+ "▁shell",
+ "▁Had",
+ "▁Law",
+ "cious",
+ "▁cancel",
+ "▁difficulty",
+ "▁IP",
+ "berg",
+ "▁highlights",
+ "▁Scott",
+ "▁ceiling",
+ "▁Henry",
+ "Oh",
+ "▁uncertainty",
+ "▁rail",
+ "▁belt",
+ "▁duration",
+ "▁struggling",
+ "▁promised",
+ "▁molecular",
+ "▁awake",
+ "Ch",
+ "▁crying",
+ "▁prime",
+ "▁producer",
+ "▁alleged",
+ "▁west",
+ "▁parallel",
+ "▁fiction",
+ "▁Hall",
+ "cker",
+ "▁immuno",
+ "▁molecule",
+ "Moreover",
+ "▁Central",
+ "emia",
+ "war",
+ "▁cigarette",
+ "▁suppress",
+ "cher",
+ "▁operator",
+ "▁surely",
+ "▁temporary",
+ "▁egg",
+ "▁conversations",
+ "▁rip",
+ "▁AD",
+ "▁quit",
+ "▁behaviour",
+ "▁accomplish",
+ "▁palm",
+ "▁urban",
+ "▁entrance",
+ "▁Tim",
+ "▁arrest",
+ "▁asterisk",
+ "▁interactions",
+ "▁Cup",
+ "▁lessons",
+ "Al",
+ "▁emerging",
+ "cate",
+ "▁neutral",
+ "▁bump",
+ "ality",
+ "▁refuse",
+ "▁substance",
+ "RS",
+ "▁Wall",
+ "▁urge",
+ "People",
+ "▁Open",
+ "▁Republicans",
+ "▁measurements",
+ "▁burning",
+ "▁spec",
+ "▁ultimate",
+ "▁affair",
+ "▁waves",
+ "pic",
+ "▁solar",
+ "▁lesson",
+ "▁covers",
+ "▁unlike",
+ "▁till",
+ "▁smoking",
+ "▁stored",
+ "▁heaven",
+ "▁wrapped",
+ "▁Cho",
+ "Pro",
+ "▁Put",
+ "▁broader",
+ "▁emission",
+ "▁colleagues",
+ "▁Han",
+ "▁approached",
+ "▁cock",
+ "▁pig",
+ "▁directed",
+ "▁diversity",
+ "▁alert",
+ "▁Services",
+ "urg",
+ "CC",
+ "▁determination",
+ "▁addressed",
+ "qua",
+ "▁correspond",
+ "cade",
+ "view",
+ "▁filling",
+ "▁fought",
+ "Additionally",
+ "▁Free",
+ "▁glow",
+ "▁briefly",
+ "▁dying",
+ "Mar",
+ "▁repeated",
+ "verse",
+ "ifying",
+ "▁beam",
+ "▁Spanish",
+ "▁Char",
+ "▁ya",
+ "▁agenda",
+ "▁distinguish",
+ "▁shots",
+ "▁tire",
+ "▁Jen",
+ "▁machines",
+ "hand",
+ "▁gay",
+ "▁assert",
+ "ek",
+ "▁optimal",
+ "▁shrugged",
+ "▁Post",
+ "▁opinions",
+ "▁Pu",
+ "▁magnetic",
+ "▁apple",
+ "▁apparent",
+ "▁coin",
+ "▁bonus",
+ "▁Find",
+ "▁disconnect",
+ "▁delete",
+ "▁Max",
+ "▁tower",
+ "Le",
+ "cha",
+ "▁CA",
+ "▁drunk",
+ "RNA",
+ "▁configuration",
+ "▁Office",
+ "▁consist",
+ "▁whereas",
+ "▁toxic",
+ "ik",
+ "break",
+ "▁researchers",
+ "▁hack",
+ "rog",
+ "acy",
+ "▁settlement",
+ "▁AS",
+ "▁vendor",
+ "▁metrics",
+ "▁eighth",
+ "▁intensity",
+ "▁hopefully",
+ "▁template",
+ "▁bulk",
+ "▁refresh",
+ "▁stranger",
+ "▁broadcast",
+ "▁pose",
+ "▁Plus",
+ "Unfortunately",
+ "▁si",
+ "▁contest",
+ "▁oh",
+ "▁adopted",
+ "▁stem",
+ "▁Italy",
+ "bro",
+ "▁gesture",
+ "▁Senate",
+ "ural",
+ "▁injured",
+ "▁ce",
+ "▁achievement",
+ "▁Company",
+ "Mo",
+ "▁disaster",
+ "▁Johnson",
+ "▁victims",
+ "look",
+ "q",
+ "lum",
+ "▁regime",
+ "▁beliefs",
+ "▁tender",
+ "▁lip",
+ "▁passage",
+ "▁divorce",
+ "▁reminder",
+ "▁binding",
+ "▁Besides",
+ "▁writers",
+ "front",
+ "▁disappointed",
+ "▁initiative",
+ "▁minister",
+ "▁CO",
+ "▁layers",
+ "▁illustrate",
+ "▁Supreme",
+ "▁reflection",
+ "▁fur",
+ "▁Year",
+ "▁Through",
+ "away",
+ "▁evident",
+ "▁checking",
+ "▁transportation",
+ "▁gar",
+ "ara",
+ "▁bite",
+ "▁concerning",
+ "▁principal",
+ "▁east",
+ "▁therapeutic",
+ "▁bench",
+ "▁breathe",
+ "▁electrical",
+ "▁squeeze",
+ "▁tele",
+ "▁couch",
+ "lip",
+ "▁campus",
+ "▁rice",
+ "▁pregnant",
+ "▁physically",
+ "▁Latin",
+ "▁distract",
+ "▁specialist",
+ "▁listened",
+ "▁enjoying",
+ "▁observe",
+ "▁rescue",
+ "▁ignored",
+ "Where",
+ "▁indicator",
+ "▁regulations",
+ "▁educational",
+ "▁Mag",
+ "▁Blue",
+ "Sa",
+ "what",
+ "▁calendar",
+ "▁defect",
+ "▁pause",
+ "▁conscious",
+ "stream",
+ "▁petition",
+ "▁philosophy",
+ "▁robot",
+ "▁refine",
+ "▁measurement",
+ "even",
+ "▁Par",
+ "▁offense",
+ "▁resume",
+ "more",
+ "▁booking",
+ "▁guidelines",
+ "▁hypo",
+ "ush",
+ "▁universal",
+ "▁dating",
+ "▁sacrifice",
+ "RA",
+ "▁Power",
+ "▁grain",
+ "▁cow",
+ "mun",
+ "▁apps",
+ "▁studying",
+ "▁wander",
+ "▁golf",
+ "pho",
+ "▁trauma",
+ "▁Stan",
+ "shop",
+ "pect",
+ "▁pale",
+ "arrow",
+ "ibility",
+ "gie",
+ "▁virtual",
+ "▁picking",
+ "▁perception",
+ "▁Should",
+ "▁liberal",
+ "▁dive",
+ "▁compromise",
+ "▁Back",
+ "▁pat",
+ "▁fool",
+ "▁complexity",
+ "▁twin",
+ "▁pun",
+ "▁desert",
+ "ula",
+ "ok",
+ "▁scientists",
+ "▁carpet",
+ "▁commonly",
+ "▁bags",
+ "▁demon",
+ "▁bitter",
+ "▁telephone",
+ "▁aircraft",
+ "▁encouraging",
+ "▁oven",
+ "▁trap",
+ "▁Anyway",
+ "▁covering",
+ "▁acute",
+ "▁requirement",
+ "▁optimistic",
+ "▁Greek",
+ "▁Microsoft",
+ "▁excitement",
+ "▁gross",
+ "▁disappeared",
+ "▁twist",
+ "▁combat",
+ "▁wooden",
+ "▁Arab",
+ "▁journalist",
+ "▁elected",
+ "▁raising",
+ "▁Ref",
+ "▁gathered",
+ "▁Father",
+ "▁Asian",
+ "▁surrounded",
+ "▁hint",
+ "▁Never",
+ "inate",
+ "▁quantum",
+ "▁yell",
+ "▁usage",
+ "▁impressed",
+ "▁garage",
+ "▁adoption",
+ "ari",
+ "▁Daniel",
+ "▁bullet",
+ "icular",
+ "▁spoken",
+ "▁guitar",
+ "▁healthcare",
+ "▁intellectual",
+ "▁Sur",
+ "migrant",
+ "▁whisper",
+ "▁sensitivity",
+ "▁connections",
+ "▁Prince",
+ "hold",
+ "▁steam",
+ "AP",
+ "mus",
+ "▁Charles",
+ "▁programming",
+ "▁voters",
+ "poli",
+ "▁gained",
+ "▁laughing",
+ "▁Check",
+ "▁earned",
+ "▁topics",
+ "▁gym",
+ "upp",
+ "Two",
+ "▁managers",
+ "▁iPhone",
+ "▁admitted",
+ "▁footprint",
+ "just",
+ "▁legislation",
+ "▁bur",
+ "▁min",
+ "▁occasionally",
+ "▁Rose",
+ "▁Turn",
+ "sses",
+ "▁Committee",
+ "▁analyze",
+ "Un",
+ "▁Jews",
+ "▁arguments",
+ "▁privilege",
+ "▁gal",
+ "▁restrict",
+ "▁courage",
+ "▁collective",
+ "▁Boston",
+ "▁Cat",
+ "▁visibility",
+ "▁employed",
+ "▁subscribe",
+ "▁genuine",
+ "▁facilitate",
+ "▁tourist",
+ "▁offerings",
+ "town",
+ "pan",
+ "▁indicates",
+ "▁pour",
+ "lysis",
+ "▁info",
+ "▁isolated",
+ "▁nutrition",
+ "▁badly",
+ "bed",
+ "▁vitamin",
+ "▁mice",
+ "▁registered",
+ "▁sake",
+ "▁meals",
+ "Last",
+ "▁arrested",
+ "▁matches",
+ "eb",
+ "▁holes",
+ "▁Val",
+ "▁financing",
+ "▁priorities",
+ "band",
+ "▁mature",
+ "▁puzzle",
+ "▁translation",
+ "▁tab",
+ "ena",
+ "▁removal",
+ "▁leap",
+ "maker",
+ "▁dirt",
+ "▁Water",
+ "▁containing",
+ "▁resolve",
+ "Thanks",
+ "▁hated",
+ "▁accessible",
+ "▁undertake",
+ "▁Too",
+ "▁demo",
+ "▁Having",
+ "▁contributions",
+ "▁analyses",
+ "▁tournament",
+ "▁Iran",
+ "▁fuck",
+ "ending",
+ "▁journal",
+ "▁hungry",
+ "unk",
+ "▁ridiculous",
+ "▁drag",
+ "▁Light",
+ "▁exam",
+ "▁assignment",
+ "▁Call",
+ "▁District",
+ "▁attempts",
+ "▁vegetables",
+ "Ne",
+ "▁negotiation",
+ "▁entering",
+ "▁mile",
+ "▁registration",
+ "▁clue",
+ "dom",
+ "nel",
+ "▁gifts",
+ "▁favourite",
+ "▁ja",
+ "▁Market",
+ "▁Whatever",
+ "▁hydro",
+ "▁assault",
+ "▁motivation",
+ "rine",
+ "▁fraction",
+ "▁rig",
+ "▁monster",
+ "Me",
+ "▁utilize",
+ "▁blanket",
+ "ama",
+ "▁spare",
+ "▁dispute",
+ "▁upcoming",
+ "▁cute",
+ "inated",
+ "▁concluded",
+ "▁referred",
+ "▁Virginia",
+ "▁drift",
+ "▁rot",
+ "▁EBITDA",
+ "▁receptor",
+ "▁laptop",
+ "▁proposition",
+ "▁alongside",
+ "▁smiling",
+ "▁cried",
+ "▁Brad",
+ "▁invite",
+ "▁honestly",
+ "Ha",
+ "▁mechanical",
+ "▁caution",
+ "▁Jane",
+ "▁quarterly",
+ "▁fade",
+ "▁comic",
+ "▁breed",
+ "izer",
+ "▁yards",
+ "▁flesh",
+ "▁Ana",
+ "▁imaging",
+ "▁uncomfortable",
+ "▁jail",
+ "▁beneficial",
+ "▁considerable",
+ "▁gradually",
+ "▁blink",
+ "▁damaged",
+ "ison",
+ "▁attempted",
+ "▁reviewed",
+ "▁testimony",
+ "▁preparing",
+ "▁ending",
+ "▁spray",
+ "▁password",
+ "▁cave",
+ "▁interrupt",
+ "▁relaxed",
+ "ola",
+ "▁threshold",
+ "▁underscore",
+ "▁prospects",
+ "▁utility",
+ "▁balanced",
+ "▁Ac",
+ "▁eager",
+ "plan",
+ "▁surprising",
+ "▁Wood",
+ "ode",
+ "▁worldwide",
+ "▁involving",
+ "▁seasonal",
+ "▁blade",
+ "▁precise",
+ "▁Master",
+ "there",
+ "▁collaboration",
+ "▁alien",
+ "▁particles",
+ "▁salad",
+ "than",
+ "▁assigned",
+ "▁wrist",
+ "▁vulnerable",
+ "word",
+ "▁emphasize",
+ "▁packed",
+ "▁tickets",
+ "▁divided",
+ "▁shout",
+ "▁Jones",
+ "▁Data",
+ "▁undergo",
+ "Still",
+ "▁membrane",
+ "▁publicly",
+ "▁greet",
+ "▁Android",
+ "▁exploit",
+ "▁experiencing",
+ "▁backward",
+ "▁seeds",
+ "▁developers",
+ "▁pregnancy",
+ "▁glasses",
+ "bol",
+ "▁Lee",
+ "Again",
+ "▁qualified",
+ "▁residential",
+ "train",
+ "▁golden",
+ "▁lesion",
+ "ami",
+ "▁attended",
+ "▁dramatic",
+ "▁disclose",
+ "▁subtle",
+ "▁gathering",
+ "▁thrown",
+ "▁sew",
+ "▁cellular",
+ "▁Carl",
+ "▁diabetes",
+ "▁tries",
+ "▁stake",
+ "Though",
+ "▁fake",
+ "▁employ",
+ "▁traveling",
+ "▁screening",
+ "▁horrible",
+ "▁roughly",
+ "MS",
+ "▁imagination",
+ "▁overwhelming",
+ "▁GP",
+ "▁remainder",
+ "▁slot",
+ "▁worship",
+ "▁grasp",
+ "▁Okay",
+ "▁math",
+ "Perhaps",
+ "▁trait",
+ "▁Book",
+ "▁relations",
+ "▁harvest",
+ "▁dishes",
+ "▁ser",
+ "▁vac",
+ "▁march",
+ "run",
+ "▁burned",
+ "▁handling",
+ "▁relates",
+ "▁equivalent",
+ "▁None",
+ "▁frozen",
+ "▁correction",
+ "Whether",
+ "▁Real",
+ "▁opposition",
+ "▁progressive",
+ "▁efficiently",
+ "non",
+ "▁fist",
+ "▁incentive",
+ "▁narrative",
+ "▁ninth",
+ "▁applying",
+ "▁instantly",
+ "mbling",
+ "▁terminal",
+ "Only",
+ "▁retirement",
+ "▁distributed",
+ "gate",
+ "▁bare",
+ "▁stiff",
+ "oli",
+ "▁observations",
+ "▁discovery",
+ "Da",
+ "▁arrival",
+ "▁dirty",
+ "▁OS",
+ "▁fence",
+ "▁Angel",
+ "▁Nick",
+ "▁emphasis",
+ "▁jurisdiction",
+ "▁dominate",
+ "Ro",
+ "▁radiation",
+ "▁gather",
+ "▁NA",
+ "▁fucking",
+ "▁nonGAAP",
+ "mato",
+ "▁Ham",
+ "▁nowhere",
+ "▁Spain",
+ "▁shifted",
+ "▁woke",
+ "▁pulse",
+ "▁lighting",
+ "▁associate",
+ "cular",
+ "▁slipped",
+ "▁Anna",
+ "ddy",
+ "▁objectives",
+ "zi",
+ "▁frequent",
+ "▁owe",
+ "▁SS",
+ "▁corporation",
+ "▁suggestions",
+ "▁assessed",
+ "▁Sarah",
+ "▁flame",
+ "▁boots",
+ "▁compelling",
+ "▁athlete",
+ "▁ads",
+ "▁productive",
+ "▁reply",
+ "▁sessions",
+ "active",
+ "rink",
+ "eller",
+ "▁friendship",
+ "▁lowest",
+ "▁mouse",
+ "▁Cy",
+ "▁banking",
+ "▁constitute",
+ "▁coordinate",
+ "▁realistic",
+ "▁exclusive",
+ "▁conviction",
+ "▁forum",
+ "▁thumb",
+ "▁bin",
+ "▁drill",
+ "burg",
+ "ience",
+ "shot",
+ "▁rural",
+ "▁shortly",
+ "▁patent",
+ "▁Being",
+ "▁neo",
+ "▁Mal",
+ "▁riding",
+ "▁flower",
+ "izz",
+ "Given",
+ "rack",
+ "▁Fu",
+ "▁cautious",
+ "hole",
+ "▁soup",
+ "▁museum",
+ "▁PS",
+ "▁deploy",
+ "▁PA",
+ "▁notion",
+ "iate",
+ "▁tracking",
+ "▁Long",
+ "under",
+ "▁skip",
+ "▁ownership",
+ "▁Jackson",
+ "▁ham",
+ "▁endless",
+ "▁adverse",
+ "▁shelter",
+ "▁towel",
+ "▁slave",
+ "▁Care",
+ "logy",
+ "▁refuge",
+ "▁shaking",
+ "▁cabinet",
+ "▁passionate",
+ "Such",
+ "▁declined",
+ "▁possibilities",
+ "plication",
+ "▁extraordinary",
+ "ground",
+ "▁Donald",
+ "▁aimed",
+ "▁parameter",
+ "▁honey",
+ "▁fishing",
+ "▁horror",
+ "▁precisely",
+ "▁Fri",
+ "▁Spring",
+ "▁insist",
+ "▁invested",
+ "▁System",
+ "▁sustain",
+ "▁Hy",
+ "▁emotion",
+ "▁Den",
+ "▁inches",
+ "▁Spirit",
+ "▁Port",
+ "▁Club",
+ "▁defensive",
+ "▁impose",
+ "▁ur",
+ "▁hitting",
+ "▁concert",
+ "▁cents",
+ "▁wisdom",
+ "▁operators",
+ "▁Learn",
+ "▁toilet",
+ "▁MP",
+ "▁assumption",
+ "▁reminded",
+ "▁sword",
+ "gram",
+ "▁statistics",
+ "▁resort",
+ "▁Obviously",
+ "▁diagnostic",
+ "▁struggled",
+ "▁trusted",
+ "▁captured",
+ "▁subscription",
+ "▁enemies",
+ "▁boot",
+ "▁swimming",
+ "▁CR",
+ "▁possession",
+ "▁personnel",
+ "▁Tell",
+ "wl",
+ "Through",
+ "▁analog",
+ "▁Army",
+ "▁Wal",
+ "▁accomplished",
+ "▁Down",
+ "▁virtually",
+ "▁royal",
+ "▁Association",
+ "▁Cri",
+ "▁compliance",
+ "▁curl",
+ "yle",
+ "▁bun",
+ "▁pants",
+ "▁baseball",
+ "▁desperate",
+ "▁flick",
+ "▁displayed",
+ "▁laser",
+ "▁activation",
+ "▁Additionally",
+ "▁professor",
+ "▁southern",
+ "▁infant",
+ "▁smartphone",
+ "▁Ryan",
+ "esis",
+ "▁suggesting",
+ "ulating",
+ "▁Road",
+ "▁violation",
+ "▁coal",
+ "▁relate",
+ "▁ghost",
+ "gon",
+ "▁propose",
+ "▁cleared",
+ "▁hiding",
+ "▁Vo",
+ "ographic",
+ "▁sing",
+ "▁dump",
+ "▁branches",
+ "▁exhaust",
+ "▁overnight",
+ "▁responded",
+ "▁tick",
+ "▁instinct",
+ "Under",
+ "▁vent",
+ "▁ultra",
+ "▁cord",
+ "▁Angeles",
+ "▁kissed",
+ "▁submitted",
+ "▁blast",
+ "ifies",
+ "▁Ya",
+ "▁Korea",
+ "▁Exp",
+ "▁flip",
+ "▁Social",
+ "▁discussing",
+ "▁thoroughly",
+ "▁gang",
+ "▁wireless",
+ "scribe",
+ "aught",
+ "▁confusion",
+ "▁signature",
+ "omy",
+ "▁singing",
+ "spec",
+ "▁sur",
+ "▁tackle",
+ "▁Islam",
+ "▁bold",
+ "▁generating",
+ "▁Business",
+ "▁logo",
+ "▁Start",
+ "▁Pay",
+ "▁Someone",
+ "cation",
+ "▁Valley",
+ "▁tunnel",
+ "ific",
+ "▁priest",
+ "▁statute",
+ "▁contractor",
+ "▁Pacific",
+ "▁silly",
+ "▁quietly",
+ "▁rug",
+ "▁electricity",
+ "▁freeze",
+ "▁HIV",
+ "▁marry",
+ "▁crawl",
+ "▁RA",
+ "▁dare",
+ "▁venue",
+ "▁fed",
+ "ution",
+ "▁stare",
+ "▁classical",
+ "based",
+ "▁span",
+ "▁peaceful",
+ "▁innocent",
+ "▁Charlie",
+ "▁remarkable",
+ "▁hug",
+ "▁hired",
+ "▁substantially",
+ "▁CC",
+ "▁lover",
+ "▁oxygen",
+ "astic",
+ "▁identification",
+ "▁persist",
+ "▁sequential",
+ "▁companion",
+ "▁sooner",
+ "▁Olympic",
+ "▁vector",
+ "operative",
+ "▁advocate",
+ "▁promising",
+ "▁Sub",
+ "▁Qui",
+ "Did",
+ "▁sandwich",
+ "▁morph",
+ "▁phrase",
+ "▁setup",
+ "▁diagnosed",
+ "▁buck",
+ "▁complications",
+ "▁abstract",
+ "▁utilization",
+ "▁fragment",
+ "rian",
+ "▁bubble",
+ "▁Democratic",
+ "▁offensive",
+ "▁Mother",
+ "▁derived",
+ "uce",
+ "▁precious",
+ "▁painted",
+ "Po",
+ "▁Ireland",
+ "▁separated",
+ "▁Southern",
+ "▁Nu",
+ "Custom",
+ "▁luxury",
+ "▁significance",
+ "▁optical",
+ "▁USA",
+ "▁chin",
+ "▁CP",
+ "▁acceptable",
+ "▁industries",
+ "En",
+ "See",
+ "▁implications",
+ "▁attending",
+ "ou",
+ "▁matrix",
+ "▁criticism",
+ "▁tighten",
+ "▁manual",
+ "ibly",
+ "organ",
+ "▁identical",
+ "▁strict",
+ "▁HD",
+ "▁fitness",
+ "▁Chief",
+ "▁dip",
+ "lude",
+ "▁loaded",
+ "▁Indeed",
+ "▁prohibit",
+ "Qu",
+ "▁ge",
+ "▁convenience",
+ "pin",
+ "rap",
+ "pat",
+ "▁imagined",
+ "▁Pakistan",
+ "▁faint",
+ "▁troops",
+ "▁blank",
+ "Looking",
+ "holder",
+ "▁weekly",
+ "▁intelligent",
+ "▁allocation",
+ "▁manuscript",
+ "▁Dave",
+ "agin",
+ "▁territory",
+ "▁dash",
+ "▁polar",
+ "▁Ash",
+ "▁Cur",
+ "▁Coast",
+ "▁unlock",
+ "▁waist",
+ "▁modification",
+ "ception",
+ "ura",
+ "▁affirm",
+ "▁prize",
+ "▁confess",
+ "▁CM",
+ "▁executed",
+ "▁membership",
+ "ita",
+ "▁requested",
+ "eng",
+ "▁Pol",
+ "▁consciousness",
+ "▁admission",
+ "▁standpoint",
+ "▁PD",
+ "▁baking",
+ "▁humor",
+ "▁nicely",
+ "▁harsh",
+ "▁Watch",
+ "▁Ten",
+ "▁manufacture",
+ "▁awkward",
+ "▁reinforce",
+ "▁fate",
+ "▁Scotland",
+ "Next",
+ "▁institution",
+ "▁abandoned",
+ "▁maximize",
+ "▁frankly",
+ "▁achieving",
+ "▁plasma",
+ "▁throwing",
+ "gling",
+ "▁mutual",
+ "▁Arch",
+ "▁modified",
+ "▁council",
+ "▁musical",
+ "Good",
+ "▁assistant",
+ "▁participating",
+ "fire",
+ "▁peri",
+ "▁Royal",
+ "▁county",
+ "▁unclear",
+ "▁Class",
+ "▁Gen",
+ "▁drama",
+ "▁Mari",
+ "▁talented",
+ "▁buried",
+ "▁Georgia",
+ "▁recommendations",
+ "▁disk",
+ "▁Research",
+ "▁distant",
+ "▁mor",
+ "▁Security",
+ "▁Far",
+ "▁mutation",
+ "▁western",
+ "▁Gold",
+ "▁Land",
+ "▁functionality",
+ "▁lymph",
+ "▁tale",
+ "▁vaccine",
+ "▁Word",
+ "▁scream",
+ "▁drum",
+ "▁executing",
+ "metric",
+ "ko",
+ "▁Nobody",
+ "▁upside",
+ "▁captain",
+ "▁dismiss",
+ "▁theater",
+ "▁dim",
+ "▁logical",
+ "▁Click",
+ "▁Institute",
+ "▁organisation",
+ "▁inherent",
+ "▁brave",
+ "▁slower",
+ "▁grey",
+ "▁dancing",
+ "▁trim",
+ "▁sensation",
+ "▁electro",
+ "▁dough",
+ "iel",
+ "▁reporter",
+ "▁enzyme",
+ "▁behalf",
+ "▁Earl",
+ "▁emerged",
+ "amine",
+ "▁Ven",
+ "▁Meanwhile",
+ "▁deployment",
+ "ime",
+ "▁cognitive",
+ "▁quo",
+ "▁simultaneously",
+ "▁passes",
+ "▁probability",
+ "▁Israeli",
+ "▁printed",
+ "market",
+ "▁Tony",
+ "▁restrictions",
+ "▁Phil",
+ "▁appreciated",
+ "▁brow",
+ "▁suite",
+ "▁Brian",
+ "power",
+ "▁involvement",
+ "▁ven",
+ "▁upload",
+ "▁Andrew",
+ "▁Dev",
+ "▁workshop",
+ "▁neat",
+ "clo",
+ "▁Several",
+ "▁classroom",
+ "▁abilities",
+ "avi",
+ "▁wider",
+ "▁efficiencies",
+ "▁chamber",
+ "▁shorter",
+ "▁suicide",
+ "▁cabin",
+ "▁SE",
+ "count",
+ "▁politicians",
+ "▁deliberate",
+ "▁Cro",
+ "▁myth",
+ "▁worn",
+ "▁democracy",
+ "▁Science",
+ "▁snack",
+ "▁Sky",
+ "▁handful",
+ "▁Human",
+ "▁rhythm",
+ "▁teen",
+ "▁liability",
+ "▁Give",
+ "▁clarity",
+ "▁dialogue",
+ "▁gen",
+ "▁purchasing",
+ "▁outfit",
+ "▁mold",
+ "▁mining",
+ "▁naked",
+ "▁landing",
+ "▁factory",
+ "▁lamp",
+ "▁govern",
+ "▁mystery",
+ "▁jar",
+ "imp",
+ "▁contemporary",
+ "▁applies",
+ "▁Show",
+ "▁rap",
+ "▁dramatically",
+ "▁compassion",
+ "cin",
+ "▁disrupt",
+ "▁Adv",
+ "▁babies",
+ "▁abnormal",
+ "▁RNA",
+ "▁boring",
+ "▁temple",
+ "▁appellant",
+ "uk",
+ "▁unde",
+ "▁Police",
+ "▁shareholder",
+ "▁consists",
+ "▁tar",
+ "Build",
+ "▁gorgeous",
+ "▁tile",
+ "▁sentiment",
+ "▁praise",
+ "▁lemon",
+ "lim",
+ "▁echo",
+ "▁swim",
+ "▁poison",
+ "▁nano",
+ "ulator",
+ "phone",
+ "▁mag",
+ "▁Federal",
+ "▁EC",
+ "▁minimize",
+ "▁grid",
+ "▁blur",
+ "▁hiring",
+ "▁GAAP",
+ "▁difficulties",
+ "▁cure",
+ "▁workout",
+ "▁citizen",
+ "Similar",
+ "▁mortality",
+ "▁assuming",
+ "Sure",
+ "Get",
+ "▁bend",
+ "▁yeah",
+ "RC",
+ "▁optimization",
+ "▁Tech",
+ "▁convey",
+ "▁qualify",
+ "▁rope",
+ "nova",
+ "▁electron",
+ "▁artificial",
+ "▁scent",
+ "▁interval",
+ "▁girlfriend",
+ "▁Form",
+ "born",
+ "▁digest",
+ "▁ES",
+ "Take",
+ "▁admire",
+ "mod",
+ "▁lib",
+ "▁consequence",
+ "▁elevated",
+ "▁cru",
+ "▁disciplined",
+ "▁progression",
+ "▁Walk",
+ "▁rejected",
+ "▁contrary",
+ "▁Eric",
+ "▁Trust",
+ "▁Irish",
+ "▁anxious",
+ "▁ethnic",
+ "▁cooked",
+ "▁Count",
+ "related",
+ "▁generous",
+ "▁equi",
+ "▁psycho",
+ "▁engaging",
+ "▁arranged",
+ "▁tenant",
+ "▁rival",
+ "▁barrel",
+ "▁sneak",
+ "roid",
+ "▁psychological",
+ "▁cousin",
+ "▁flour",
+ "▁discharge",
+ "▁Louis",
+ "▁norm",
+ "▁comb",
+ "key",
+ "▁festival",
+ "▁Food",
+ "▁tub",
+ "▁applicable",
+ "▁injection",
+ "▁historically",
+ "▁receiver",
+ "▁poem",
+ "▁Things",
+ "▁sustained",
+ "▁accent",
+ "▁rub",
+ "▁loo",
+ "ologies",
+ "▁sir",
+ "▁humanity",
+ "▁magnitude",
+ "▁restructuring",
+ "▁northern",
+ "▁polish",
+ "▁CEO",
+ "▁historic",
+ "col",
+ "▁needle",
+ "▁SA",
+ "▁exploring",
+ "ington",
+ "▁steep",
+ "▁plug",
+ "▁safely",
+ "▁integrity",
+ "leg",
+ "▁washed",
+ "through",
+ "▁kicked",
+ "▁evolve",
+ "▁logistic",
+ "Ja",
+ "▁attacked",
+ "▁enforcement",
+ "ense",
+ "▁incorporate",
+ "▁Jon",
+ "ji",
+ "▁Syria",
+ "▁Place",
+ "▁killer",
+ "▁Soviet",
+ "ule",
+ "▁tan",
+ "▁unfortunately",
+ "▁Celsius",
+ "uel",
+ "▁casino",
+ "▁Carolina",
+ "▁Little",
+ "▁Santa",
+ "▁separation",
+ "▁Gal",
+ "▁Minister",
+ "Having",
+ "▁voltage",
+ "▁patience",
+ "▁volatility",
+ "space",
+ "▁migration",
+ "ban",
+ "▁targeting",
+ "▁Note",
+ "▁systematic",
+ "▁respective",
+ "▁assay",
+ "▁legend",
+ "▁Northern",
+ "berry",
+ "worth",
+ "▁Ve",
+ "▁grin",
+ "▁bent",
+ "▁Fer",
+ "▁repeatedly",
+ "▁behave",
+ "after",
+ "▁orbit",
+ "▁Fred",
+ "▁cheaper",
+ "▁horizon",
+ "▁induced",
+ "▁pillow",
+ "▁Wo",
+ "▁macro",
+ "▁creep",
+ "Car",
+ "▁angel",
+ "▁enabled",
+ "▁jaw",
+ "▁stopping",
+ "▁whisk",
+ "▁announce",
+ "pparently",
+ "▁organize",
+ "▁contend",
+ "▁advertise",
+ "▁brew",
+ "▁guilt",
+ "▁merit",
+ "▁entrepreneur",
+ "▁screaming",
+ "▁champion",
+ "▁Victoria",
+ "▁predicted",
+ "▁neighbour",
+ "▁viewed",
+ "▁Gro",
+ "▁celebration",
+ "▁retreat",
+ "▁threatened",
+ "▁nest",
+ "Vi",
+ "▁bacteria",
+ "▁knocked",
+ "▁resolved",
+ "▁inspect",
+ "▁shocked",
+ "▁Pen",
+ "Mi",
+ "▁racing",
+ "▁influenced",
+ "▁intake",
+ "▁descend",
+ "▁serum",
+ "▁Tro",
+ "ifier",
+ "erate",
+ "▁creativity",
+ "▁argued",
+ "▁instruction",
+ "▁tru",
+ "star",
+ "▁pizza",
+ "▁Francisco",
+ "▁candle",
+ "▁stamp",
+ "▁Fire",
+ "encies",
+ "▁glove",
+ "▁upward",
+ "lusion",
+ "▁constructed",
+ "▁laboratory",
+ "▁Fr",
+ "Have",
+ "▁elbow",
+ "▁dental",
+ "▁rack",
+ "▁nuts",
+ "▁blocked",
+ "rum",
+ "▁FA",
+ "▁romantic",
+ "▁tweet",
+ "▁fancy",
+ "▁forehead",
+ "▁flew",
+ "▁wished",
+ "▁ambition",
+ "▁effectiveness",
+ "imate",
+ "▁terrorist",
+ "▁jet",
+ "▁prominent",
+ "gel",
+ "▁compliment",
+ "▁implant",
+ "▁inflammatory",
+ "mission",
+ "▁Sand",
+ "AT",
+ "▁forgot",
+ "▁rotation",
+ "▁shield",
+ "▁pond",
+ "▁sleeve",
+ "▁convince",
+ "▁bored",
+ "▁reception",
+ "▁accused",
+ "▁offend",
+ "▁mut",
+ "▁immigration",
+ "▁commodity",
+ "▁About",
+ "bie",
+ "▁transferred",
+ "▁grill",
+ "▁ruling",
+ "▁magical",
+ "▁deco",
+ "▁Vietnam",
+ "eno",
+ "▁NFL",
+ "▁elegant",
+ "▁scored",
+ "▁keen",
+ "▁reliability",
+ "▁centuries",
+ "CO",
+ "▁acceptance",
+ "▁ST",
+ "▁steer",
+ "▁Edward",
+ "▁existed",
+ "▁treasure",
+ "cover",
+ "▁AP",
+ "▁solely",
+ "▁addresses",
+ "▁shore",
+ "▁Hollywood",
+ "▁Hunt",
+ "▁stunning",
+ "▁ensuring",
+ "▁basket",
+ "▁chase",
+ "▁Looking",
+ "▁removing",
+ "Sp",
+ "▁frustration",
+ "▁climbed",
+ "▁hike",
+ "▁jerk",
+ "▁substitute",
+ "▁limb",
+ "▁controlling",
+ "▁overhead",
+ "▁sofa",
+ "card",
+ "▁wherever",
+ "▁Michigan",
+ "▁Cook",
+ "▁brick",
+ "▁failing",
+ "▁Actually",
+ "▁refund",
+ "▁leaf",
+ "▁Boy",
+ "▁CB",
+ "▁grandmother",
+ "▁twentieth",
+ "▁PR",
+ "▁Pra",
+ "will",
+ "▁backlog",
+ "▁rust",
+ "▁Kevin",
+ "▁hunting",
+ "▁wallet",
+ "▁temp",
+ "▁mineral",
+ "▁Mad",
+ "vie",
+ "▁seller",
+ "▁spine",
+ "▁squad",
+ "▁feeding",
+ "ctua",
+ "▁trash",
+ "▁spill",
+ "▁discretion",
+ "▁downtown",
+ "most",
+ "▁vice",
+ "ati",
+ "▁certificate",
+ "▁partial",
+ "▁manifest",
+ "▁Women",
+ "▁ugly",
+ "▁gaming",
+ "▁slept",
+ "▁curtain",
+ "▁Ray",
+ "▁hybrid",
+ "▁compile",
+ "une",
+ "▁identifying",
+ "▁consecutive",
+ "▁recognise",
+ "▁veteran",
+ "itude",
+ "▁recovered",
+ "▁Holy",
+ "▁whip",
+ "▁Sudden",
+ "▁empower",
+ "bon",
+ "▁differential",
+ "Ho",
+ "▁layout",
+ "▁ladies",
+ "▁Ohio",
+ "▁favour",
+ "▁overview",
+ "▁attraction",
+ "▁flo",
+ "▁lac",
+ "▁drilling",
+ "▁phenomenon",
+ "▁Simon",
+ "▁liquidity",
+ "▁consistency",
+ "▁scary",
+ "▁basketball",
+ "▁selective",
+ "▁delayed",
+ "▁Eli",
+ "▁ox",
+ "▁cruel",
+ "▁boyfriend",
+ "▁reject",
+ "▁cloth",
+ "▁bud",
+ "▁deadline",
+ "▁armed",
+ "▁Age",
+ "▁bounce",
+ "▁FBI",
+ "▁bundle",
+ "▁ion",
+ "Jo",
+ "▁broker",
+ "▁competing",
+ "▁integrate",
+ "Make",
+ "▁overlap",
+ "▁spite",
+ "▁mud",
+ "▁administrative",
+ "▁homo",
+ "▁damp",
+ "▁analyst",
+ "▁equipped",
+ "▁sophisticated",
+ "▁Mill",
+ "▁Know",
+ "hir",
+ "arily",
+ "▁protecting",
+ "▁apologize",
+ "▁pill",
+ "▁inspire",
+ "▁thereby",
+ "Cl",
+ "▁Greg",
+ "▁NS",
+ "▁dial",
+ "wear",
+ "▁separately",
+ "▁excluded",
+ "post",
+ "▁prospect",
+ "uth",
+ "▁Main",
+ "▁Guard",
+ "▁strive",
+ "▁advisor",
+ "▁yoga",
+ "▁meta",
+ "▁restricted",
+ "hol",
+ "fuse",
+ "▁vanish",
+ "▁Society",
+ "▁duck",
+ "quest",
+ "▁loyalty",
+ "▁sigh",
+ "▁profound",
+ "▁teenager",
+ "▁probe",
+ "FC",
+ "▁hop",
+ "▁terror",
+ "▁treating",
+ "▁Disney",
+ "▁API",
+ "▁thoughtful",
+ "▁sweep",
+ "▁accommodate",
+ "▁surge",
+ "▁pest",
+ "▁pension",
+ "▁grinned",
+ "▁voted",
+ "Will",
+ "▁makeup",
+ "Clearly",
+ "▁Dun",
+ "▁modify",
+ "▁Public",
+ "▁forgive",
+ "▁Force",
+ "▁condo",
+ "▁EM",
+ "▁DM",
+ "▁Rather",
+ "▁Ci",
+ "▁Ever",
+ "▁consolidate",
+ "▁hypothesis",
+ "▁straightforward",
+ "▁stumble",
+ "▁analytics",
+ "▁prospective",
+ "▁col",
+ "▁closest",
+ "▁Kate",
+ "▁infinite",
+ "▁spatial",
+ "▁Rome",
+ "▁automatic",
+ "▁chew",
+ "▁plum",
+ "▁rushed",
+ "▁controller",
+ "▁fraud",
+ "▁SC",
+ "▁landed",
+ "▁temper",
+ "▁mate",
+ "Indeed",
+ "▁fitting",
+ "▁establishment",
+ "▁lane",
+ "EC",
+ "▁lightly",
+ "▁assembly",
+ "▁elderly",
+ "▁Tea",
+ "angle",
+ "▁vet",
+ "▁Eastern",
+ "▁substrate",
+ "▁Best",
+ "▁clever",
+ "▁buzz",
+ "▁complement",
+ "▁inspection",
+ "▁waved",
+ "▁assured",
+ "▁characterized",
+ "▁premise",
+ "▁Labour",
+ "▁beans",
+ "gno",
+ "▁satellite",
+ "▁firmly",
+ "▁bleeding",
+ "▁poverty",
+ "▁strap",
+ "▁Houston",
+ "RP",
+ "▁roast",
+ "▁shine",
+ "▁disclosure",
+ "Further",
+ "▁practically",
+ "media",
+ "▁Rick",
+ "▁nap",
+ "due",
+ "▁dropping",
+ "▁contradict",
+ "▁crisp",
+ "▁transparent",
+ "▁swear",
+ "▁Mountain",
+ "▁investor",
+ "▁vocal",
+ "▁skirt",
+ "▁calculate",
+ "ike",
+ "▁backup",
+ "▁matching",
+ "▁packaging",
+ "each",
+ "▁blessing",
+ "▁affiliate",
+ "▁viral",
+ "▁polite",
+ "▁Dec",
+ "▁Hard",
+ "▁supporters",
+ "phi",
+ "▁max",
+ "▁highlighted",
+ "▁envelope",
+ "ologic",
+ "▁baseline",
+ "▁rib",
+ "▁Program",
+ "▁airline",
+ "▁dread",
+ "vation",
+ "▁fortunate",
+ "▁float",
+ "▁photography",
+ "▁fighter",
+ "▁obstacle",
+ "▁uncertain",
+ "▁SM",
+ "▁prescription",
+ "▁Page",
+ "▁Bell",
+ "▁closure",
+ "▁constraints",
+ "ique",
+ "▁negotiate",
+ "▁mum",
+ "▁spice",
+ "▁Off",
+ "name",
+ "▁Jason",
+ "▁Otherwise",
+ "▁SD",
+ "▁survived",
+ "last",
+ "▁lobby",
+ "▁secured",
+ "▁concentrate",
+ "▁LA",
+ "▁kidney",
+ "▁Until",
+ "▁inflammation",
+ "▁sketch",
+ "▁dressing",
+ "▁shipment",
+ "▁reaches",
+ "▁suspected",
+ "Without",
+ "▁photographer",
+ "▁cheat",
+ "▁Colorado",
+ "▁surf",
+ "▁guaranteed",
+ "▁regression",
+ "▁boundaries",
+ "▁copies",
+ "▁SEC",
+ "▁dried",
+ "▁hormone",
+ "▁challenged",
+ "▁surgeon",
+ "▁cotton",
+ "▁stir",
+ "▁Elizabeth",
+ "▁Sho",
+ "▁entitled",
+ "▁Young",
+ "▁thermal",
+ "▁abroad",
+ "▁outline",
+ "gri",
+ "▁intimate",
+ "▁Nevertheless",
+ "▁frowned",
+ "▁presidential",
+ "RT",
+ "▁differentiation",
+ "▁amongst",
+ "▁trailer",
+ "▁deter",
+ "▁neglect",
+ "▁Beach",
+ "▁Constitution",
+ "▁Ram",
+ "▁uncle",
+ "▁fantasy",
+ "Overall",
+ "▁Later",
+ "▁Cross",
+ "▁skilled",
+ "type",
+ "▁stretched",
+ "▁bolt",
+ "▁exhausted",
+ "▁classification",
+ "▁elect",
+ "▁anchor",
+ "▁folder",
+ "▁betray",
+ "▁printing",
+ "▁voting",
+ "▁Brand",
+ "▁hence",
+ "▁lecture",
+ "▁compact",
+ "▁basement",
+ "▁Taylor",
+ "▁bang",
+ "▁Fair",
+ "▁dense",
+ "▁Parliament",
+ "▁residence",
+ "▁enhancement",
+ "kind",
+ "▁Bush",
+ "▁searched",
+ "▁freak",
+ "▁independence",
+ "▁Korean",
+ "▁elite",
+ "▁mist",
+ "▁Cap",
+ "life",
+ "▁retention",
+ "▁distress",
+ "▁navigate",
+ "▁align",
+ "▁dumb",
+ "▁transplant",
+ "▁grim",
+ "▁edition",
+ "▁motivated",
+ "▁flush",
+ "▁eyebrow",
+ "▁Special",
+ "▁mechanic",
+ "uter",
+ "▁documentation",
+ "▁underneath",
+ "▁compute",
+ "Comp",
+ "▁await",
+ "▁striking",
+ "▁bucket",
+ "▁featured",
+ "ius",
+ "▁cyto",
+ "▁hallway",
+ "▁globe",
+ "▁Director",
+ "▁violate",
+ "▁punish",
+ "▁fortune",
+ "▁constitutional",
+ "▁contributing",
+ "▁headwind",
+ "▁quantity",
+ "▁minus",
+ "▁tightly",
+ "▁Top",
+ "▁poke",
+ "▁nightmare",
+ "▁varied",
+ "▁destruction",
+ "▁efficacy",
+ "▁Given",
+ "▁Project",
+ "▁Joseph",
+ "▁nineteenth",
+ "▁theoretical",
+ "▁theories",
+ "▁chunk",
+ "▁Auto",
+ "▁Sir",
+ "▁Six",
+ "cake",
+ "▁bro",
+ "▁legitimate",
+ "▁governor",
+ "▁vague",
+ "▁fracture",
+ "▁Ron",
+ "▁Cam",
+ "▁appointed",
+ "▁addict",
+ "▁protective",
+ "▁insult",
+ "hou",
+ "▁Justice",
+ "▁massage",
+ "▁beef",
+ "Based",
+ "▁Kim",
+ "▁Egypt",
+ "▁entity",
+ "▁embedded",
+ "▁syndrome",
+ "▁Julia",
+ "▁grind",
+ "▁YouTube",
+ "▁warmth",
+ "▁nursing",
+ "ask",
+ "▁independently",
+ "▁laughter",
+ "▁ER",
+ "▁MA",
+ "▁delicate",
+ "▁Gene",
+ "▁ankle",
+ "▁specialty",
+ "▁withdraw",
+ "▁submission",
+ "▁adhere",
+ "▁hub",
+ "▁gaining",
+ "▁mattress",
+ "morph",
+ "lib",
+ "▁validate",
+ "▁Jordan",
+ "▁penalty",
+ "▁Run",
+ "▁operated",
+ "▁physics",
+ "Invest",
+ "class",
+ "▁coaches",
+ "▁sip",
+ "▁Hospital",
+ "▁depict",
+ "shire",
+ "▁static",
+ "link",
+ "▁UN",
+ "▁indoor",
+ "chemical",
+ "▁accompanied",
+ "▁activist",
+ "mail",
+ "▁crap",
+ "▁pursuing",
+ "miss",
+ "▁essence",
+ "▁genre",
+ "▁exploration",
+ "Moving",
+ "▁unnecessary",
+ "▁Ob",
+ "▁highway",
+ "▁reconciliation",
+ "▁NP",
+ "▁Management",
+ "▁Foundation",
+ "grade",
+ "▁indicating",
+ "▁representing",
+ "craft",
+ "▁grief",
+ "▁disruption",
+ "▁Further",
+ "▁soldier",
+ "asse",
+ "▁linger",
+ "▁dominant",
+ "▁funeral",
+ "▁Design",
+ "▁abortion",
+ "▁GM",
+ "▁accordance",
+ "▁placement",
+ "▁potatoes",
+ "▁finishing",
+ "▁excellence",
+ "ogenesis",
+ "▁supportive",
+ "▁eligible",
+ "Keep",
+ "▁rifle",
+ "▁accurately",
+ "▁spotted",
+ "▁floating",
+ "▁Test",
+ "Consequently",
+ "▁ecosystem",
+ "▁surprisingly",
+ "▁PE",
+ "▁punishment",
+ "▁Fall",
+ "▁Mat",
+ "▁convention",
+ "▁diploma",
+ "▁demographic",
+ "▁renewal",
+ "▁diamond",
+ "▁shy",
+ "▁SEO",
+ "present",
+ "▁CF",
+ "▁implementing",
+ "▁brutal",
+ "▁pra",
+ "▁III",
+ "▁publisher",
+ "▁jam",
+ "▁cohort",
+ "▁dataset",
+ "▁seemingly",
+ "▁lender",
+ "▁vein",
+ "▁cough",
+ "▁conform",
+ "▁fever",
+ "▁BC",
+ "▁encountered",
+ "▁Lib",
+ "Look",
+ "▁fascinating",
+ "▁handled",
+ "▁assure",
+ "ander",
+ "agon",
+ "▁keyboard",
+ "▁diminish",
+ "▁evaluating",
+ "▁Mexican",
+ "▁torture",
+ "▁curse",
+ "bound",
+ "▁declared",
+ "▁comparing",
+ "▁Team",
+ "▁headache",
+ "▁olive",
+ "▁regarded",
+ "▁brace",
+ "▁Uni",
+ "▁MI",
+ "▁civilian",
+ "▁cease",
+ "▁connecting",
+ "▁gauge",
+ "▁excessive",
+ "▁infected",
+ "▁determining",
+ "▁peel",
+ "▁stall",
+ "▁meditation",
+ "▁Medical",
+ "▁vacuum",
+ "▁incidence",
+ "▁LED",
+ "▁tenth",
+ "▁Ali",
+ "▁distinction",
+ "▁Sound",
+ "▁cruise",
+ "▁insisted",
+ "▁lately",
+ "▁rubber",
+ "▁rh",
+ "▁RF",
+ "▁twisted",
+ "▁garlic",
+ "▁preach",
+ "▁Palestinian",
+ "ogni",
+ "ada",
+ "▁bloody",
+ "▁Ze",
+ "▁exclude",
+ "greg",
+ "▁Harris",
+ "▁lawn",
+ "▁upstairs",
+ "▁mentor",
+ "Recently",
+ "▁inevitable",
+ "▁prevalence",
+ "▁wishes",
+ "▁Van",
+ "▁stabilize",
+ "▁officially",
+ "▁MC",
+ "▁loyal",
+ "▁antibiotic",
+ "guard",
+ "▁stolen",
+ "▁nutrient",
+ "▁velocity",
+ "▁Hence",
+ "▁Arizona",
+ "▁hedge",
+ "▁Fox",
+ "▁Especially",
+ "▁milestone",
+ "▁Turkey",
+ "▁urgent",
+ "▁blond",
+ "▁Saint",
+ "▁elaborate",
+ "▁washing",
+ "▁awarded",
+ "▁continuously",
+ "▁commentary",
+ "▁boundary",
+ "▁Sil",
+ "▁Carol",
+ "▁servant",
+ "▁Press",
+ "▁precision",
+ "from",
+ "face",
+ "▁bearing",
+ "▁characteristic",
+ "▁stitch",
+ "▁placing",
+ "▁rage",
+ "▁swell",
+ "▁pub",
+ "▁pole",
+ "▁Consider",
+ "▁deficit",
+ "App",
+ "Regardless",
+ "▁console",
+ "▁merchant",
+ "▁perceived",
+ "▁variant",
+ "▁Alice",
+ "▁retro",
+ "▁Officer",
+ "▁Roger",
+ "▁requiring",
+ "▁strongest",
+ "▁reflecting",
+ "▁measuring",
+ "spiration",
+ "Does",
+ "▁clam",
+ "▁frustrated",
+ "▁Mid",
+ "▁Hope",
+ "▁enforce",
+ "▁Town",
+ "▁spoil",
+ "▁editing",
+ "▁adjacent",
+ "▁meantime",
+ "▁Bitcoin",
+ "▁gi",
+ "▁purple",
+ "▁thankful",
+ "▁Luke",
+ "▁jeans",
+ "▁costume",
+ "▁Bridge",
+ "▁blew",
+ "▁Prime",
+ "▁relating",
+ "therapy",
+ "▁insect",
+ "▁tilt",
+ "▁reasonably",
+ "▁cardiac",
+ "▁attempting",
+ "▁inclusion",
+ "▁chaos",
+ "▁accessories",
+ "▁expenditure",
+ "▁trapped",
+ "▁verify",
+ "▁poured",
+ "▁investigator",
+ "▁Key",
+ "▁belly",
+ "▁occurring",
+ "▁Third",
+ "▁reset",
+ "▁dull",
+ "▁disgust",
+ "▁focuses",
+ "pay",
+ "▁Jacob",
+ "▁Islamic",
+ "▁summarize",
+ "▁soap",
+ "▁regulator",
+ "▁toast",
+ "▁induce",
+ "▁delight",
+ "▁promotional",
+ "▁unfold",
+ "▁bay",
+ "▁generic",
+ "weight",
+ "▁transmit",
+ "New",
+ "▁aligned",
+ "▁copyright",
+ "▁profession",
+ "▁Ask",
+ "▁ritual",
+ "▁distort",
+ "▁disappoint",
+ "▁incorrect",
+ "▁poorly",
+ "▁Seattle",
+ "▁thorough",
+ "▁Camp",
+ "▁Low",
+ "▁Bla",
+ "▁warned",
+ "▁eaten",
+ "▁tract",
+ "▁Head",
+ "▁dragged",
+ "▁unfair",
+ "▁converted",
+ "▁condemn",
+ "▁halt",
+ "▁grocery",
+ "▁developer",
+ "▁explosion",
+ "piece",
+ "▁accordingly",
+ "▁bush",
+ "▁Product",
+ "▁shelf",
+ "▁desirable",
+ "▁gel",
+ "▁Within",
+ "▁sec",
+ "▁boom",
+ "▁bind",
+ "▁Stephen",
+ "▁absent",
+ "▁subsequently",
+ "▁ranking",
+ "▁readily",
+ "▁Jersey",
+ "Use",
+ "▁Kong",
+ "▁invitation",
+ "▁Bru",
+ "▁promoting",
+ "▁Wild",
+ "▁thigh",
+ "▁HR",
+ "▁advised",
+ "▁amendment",
+ "▁attracted",
+ "▁considerably",
+ "▁Qua",
+ "▁specified",
+ "▁endorse",
+ "▁hyp",
+ "▁zip",
+ "▁numerical",
+ "Everyone",
+ "▁explode",
+ "▁scholar",
+ "▁prevention",
+ "▁mock",
+ "▁divide",
+ "▁gig",
+ "▁outrage",
+ "▁orientation",
+ "▁SP",
+ "▁Neither",
+ "▁quant",
+ "▁addiction",
+ "▁Pur",
+ "▁Always",
+ "because",
+ "▁doorway",
+ "▁collar",
+ "▁duties",
+ "▁sym",
+ "▁clutch",
+ "▁Garden",
+ "▁consultant",
+ "▁enthusiasm",
+ "▁Wilson",
+ "Besides",
+ "▁rape",
+ "▁ethic",
+ "▁End",
+ "▁objection",
+ "▁packet",
+ "▁minority",
+ "▁Gil",
+ "▁reservation",
+ "▁Either",
+ "Current",
+ "▁alignment",
+ "▁Zealand",
+ "▁completing",
+ "itz",
+ "ggy",
+ "▁desktop",
+ "omer",
+ "▁PP",
+ "▁accelerated",
+ "▁width",
+ "store",
+ "version",
+ "▁attain",
+ "▁neurons",
+ "▁lump",
+ "La",
+ "▁chop",
+ "▁Ger",
+ "▁annoying",
+ "▁Toronto",
+ "Turning",
+ "▁silk",
+ "▁query",
+ "▁lid",
+ "▁retired",
+ "▁cater",
+ "▁Energy",
+ "▁phenomena",
+ "fish",
+ "fur",
+ "▁metric",
+ "▁rebuild",
+ "▁altogether",
+ "▁permitted",
+ "▁discrimination",
+ "▁preliminary",
+ "▁institutional",
+ "▁trunk",
+ "▁suggestion",
+ "▁whilst",
+ "▁ok",
+ "▁hurry",
+ "▁err",
+ "▁Exchange",
+ "▁rebel",
+ "▁Personal",
+ "▁ortho",
+ "▁poetry",
+ "▁particle",
+ "▁Kingdom",
+ "▁Instagram",
+ "▁ceremony",
+ "▁Stone",
+ "▁confirmation",
+ "▁marijuana",
+ "▁miracle",
+ "▁pine",
+ "▁startup",
+ "▁abandon",
+ "▁testified",
+ "Meanwhile",
+ "▁contributor",
+ "▁shoe",
+ "▁occupation",
+ "▁euro",
+ "▁isolation",
+ "▁stimulate",
+ "▁useless",
+ "fold",
+ "depend",
+ "▁ego",
+ "▁composed",
+ "▁CapEx",
+ "stein",
+ "▁porch",
+ "▁Probably",
+ "▁corridor",
+ "▁moist",
+ "▁fatal",
+ "▁dawn",
+ "▁Doctor",
+ "▁fierce",
+ "▁Brexit",
+ "▁prince",
+ "▁classified",
+ "▁Republic",
+ "▁correlated",
+ "▁hood",
+ "▁Plaintiff",
+ "▁chrom",
+ "▁Pennsylvania",
+ "▁Maria",
+ "▁distributor",
+ "▁continent",
+ "▁Talk",
+ "▁folded",
+ "▁Hillary",
+ "▁entertain",
+ "▁Jay",
+ "▁MRI",
+ "▁restrain",
+ "know",
+ "Would",
+ "▁climbing",
+ "▁dual",
+ "▁Mel",
+ "mobil",
+ "▁accommodation",
+ "▁retrieve",
+ "▁Albert",
+ "▁piano",
+ "▁finest",
+ "▁idiot",
+ "▁participated",
+ "▁Point",
+ "▁jewelry",
+ "▁cult",
+ "▁HC",
+ "▁copper",
+ "▁consultation",
+ "▁newsletter",
+ "▁witnesses",
+ "▁sampling",
+ "▁immense",
+ "▁slope",
+ "▁Secretary",
+ "▁mainstream",
+ "▁tang",
+ "▁accompany",
+ "▁cage",
+ "▁widespread",
+ "▁altered",
+ "Ba",
+ "▁soften",
+ "▁clarify",
+ "▁racial",
+ "▁tray",
+ "script",
+ "this",
+ "▁shrink",
+ "▁gasp",
+ "▁allocate",
+ "▁precede",
+ "▁carries",
+ "▁evolved",
+ "▁HP",
+ "▁Pass",
+ "▁drawer",
+ "▁workplace",
+ "Add",
+ "▁cushion",
+ "▁Helen",
+ "▁traction",
+ "▁wholesale",
+ "▁transformed",
+ "▁cooperation",
+ "▁evolving",
+ "▁transcript",
+ "▁Financial",
+ "▁reluctant",
+ "▁Unlike",
+ "▁Vegas",
+ "▁Control",
+ "▁DO",
+ "▁Hamilton",
+ "▁followers",
+ "Was",
+ "▁Wil",
+ "▁responsive",
+ "▁Jimmy",
+ "▁glimpse",
+ "▁technological",
+ "▁switched",
+ "▁hammer",
+ "▁Education",
+ "Yeah",
+ "▁Evan",
+ "▁buffer",
+ "other",
+ "▁Ban",
+ "▁wounded",
+ "▁blessed",
+ "▁mall",
+ "▁Saudi",
+ "je",
+ "▁accomplishment",
+ "▁Much",
+ "▁Student",
+ "▁severity",
+ "▁sheep",
+ "▁Tour",
+ "▁Live",
+ "▁batch",
+ "▁processor",
+ "▁Media",
+ "▁Kelly",
+ "▁jealous",
+ "▁outlined",
+ "▁valley",
+ "▁breach",
+ "▁finite",
+ "▁worthy",
+ "▁geographic",
+ "▁lawsuit",
+ "▁dedication",
+ "lessness",
+ "▁swap",
+ "▁enrich",
+ "Beyond",
+ "bury",
+ "▁Rachel",
+ "▁implied",
+ "▁decay",
+ "ude",
+ "▁confusing",
+ "▁suspicious",
+ "▁merger",
+ "stock",
+ "▁continually",
+ "▁dessert",
+ "cellular",
+ "▁penetration",
+ "▁reside",
+ "▁Anti",
+ "▁crown",
+ "▁Hong",
+ "lift",
+ "▁grandfather",
+ "Right",
+ "▁nearest",
+ "▁enabling",
+ "▁fibro",
+ "▁regulated",
+ "▁consolidation",
+ "▁churches",
+ "▁Atlantic",
+ "▁mandate",
+ "▁Defendant",
+ "▁beast",
+ "▁Academy",
+ "▁Eventually",
+ "▁strand",
+ "▁tribe",
+ "▁Music",
+ "▁province",
+ "▁hesitate",
+ "▁Civil",
+ "▁Member",
+ "▁haunt",
+ "course",
+ "▁breeze",
+ "▁fond",
+ "▁endure",
+ "clock",
+ "▁cab",
+ "▁abundance",
+ "▁foster",
+ "▁slim",
+ "▁Iowa",
+ "▁Photo",
+ "▁mitigate",
+ "▁scoring",
+ "▁distribute",
+ "▁Lady",
+ "▁demonstration",
+ "▁mysterious",
+ "▁scatter",
+ "▁spike",
+ "▁gentlemen",
+ "▁gallery",
+ "▁integral",
+ "▁generator",
+ "▁exclusively",
+ "▁utilized",
+ "▁lending",
+ "ffer",
+ "▁Billy",
+ "▁threatening",
+ "▁aesthetic",
+ "▁Afghanistan",
+ "▁regulate",
+ "▁Jake",
+ "▁glare",
+ "▁poet",
+ "▁spouse",
+ "▁explicitly",
+ "▁swallowed",
+ "▁disappointment",
+ "▁spectacular",
+ "▁Manchester",
+ "▁brake",
+ "▁Clark",
+ "▁lonely",
+ "▁spoon",
+ "▁Sorry",
+ "▁snake",
+ "▁Five",
+ "▁DS",
+ "▁Really",
+ "Everything",
+ "oscopic",
+ "▁hazard",
+ "▁impairment",
+ "▁concentrated",
+ "▁countless",
+ "▁consensus",
+ "▁Yo",
+ "▁gravity",
+ "sort",
+ "▁capitalize",
+ "▁Xray",
+ "▁surrender",
+ "▁polymer",
+ "▁wipe",
+ "▁fifteenth",
+ "▁firing",
+ "▁Illinois",
+ "▁surveillance",
+ "▁oldest",
+ "▁insane",
+ "▁recipient",
+ "▁occurrence",
+ "▁purely",
+ "▁drank",
+ "▁weaker",
+ "▁skeptic",
+ "▁Children",
+ "▁departure",
+ "▁acceleration",
+ "▁MD",
+ "▁broadly",
+ "source",
+ "▁Network",
+ "▁appliance",
+ "▁sanction",
+ "▁iPad",
+ "▁Gulf",
+ "▁metabolism",
+ "Specifically",
+ "genic",
+ "▁overseas",
+ "▁contaminat",
+ "▁pH",
+ "▁haul",
+ "▁podcast",
+ "▁occupied",
+ "▁fridge",
+ "▁Global",
+ "▁invisible",
+ "▁strictly",
+ "▁glue",
+ "▁transparency",
+ "▁Except",
+ "▁charity",
+ "▁Emma",
+ "▁underground",
+ "▁ML",
+ "▁Family",
+ "▁devoted",
+ "oxic",
+ "wall",
+ "▁Davis",
+ "▁dys",
+ "▁allegations",
+ "▁rode",
+ "▁catalog",
+ "▁snapped",
+ "▁dismissed",
+ "▁thrive",
+ "▁survivor",
+ "▁Dark",
+ "▁popularity",
+ "responsibilities",
+ "▁Nazi",
+ "▁depressed",
+ "▁receipt",
+ "▁lag",
+ "▁Code",
+ "▁beaten",
+ "▁mentally",
+ "▁frustrating",
+ "▁shiver",
+ "▁intact",
+ "▁fatigue",
+ "▁Anne",
+ "▁limitation",
+ "▁Due",
+ "▁valuation",
+ "▁ethical",
+ "▁renal",
+ "▁disadvantage",
+ "▁automation",
+ "▁entertaining",
+ "▁BP",
+ "▁cleaner",
+ "▁Information",
+ "▁dysfunction",
+ "▁elevator",
+ "▁knit",
+ "▁appreciation",
+ "▁dragon",
+ "▁specify",
+ "▁delighted",
+ "▁knot",
+ "▁heels",
+ "Within",
+ "▁Michel",
+ "▁deciding",
+ "▁deployed",
+ "▁junk",
+ "▁insulin",
+ "symmetric",
+ "▁qualities",
+ "▁thrill",
+ "▁likelihood",
+ "▁screamed",
+ "▁Hand",
+ "▁pursuit",
+ "▁swallow",
+ "▁fluctuation",
+ "▁junior",
+ "▁quantitative",
+ "▁verse",
+ "▁purse",
+ "dynamic",
+ "▁shouted",
+ "▁Sen",
+ "▁glory",
+ "▁incorporated",
+ "▁attachment",
+ "▁PT",
+ "▁CN",
+ "▁attach",
+ "▁tossed",
+ "▁Oregon",
+ "Patients",
+ "▁warehouse",
+ "▁Miller",
+ "▁Store",
+ "Following",
+ "▁glucose",
+ "▁Dutch",
+ "▁salary",
+ "▁controversial",
+ "▁pixel",
+ "group",
+ "▁safer",
+ "▁halfway",
+ "▁sunlight",
+ "▁rubbed",
+ "▁Amendment",
+ "▁suburb",
+ "▁distraction",
+ "Certain",
+ "▁championship",
+ "▁Among",
+ "Nothing",
+ "▁cookie",
+ "▁entities",
+ "▁compress",
+ "▁referring",
+ "▁bankruptcy",
+ "▁tariff",
+ "▁debut",
+ "▁certified",
+ "▁divine",
+ "mount",
+ "▁shallow",
+ "▁happily",
+ "▁automotive",
+ "▁Award",
+ "▁accumulate",
+ "▁suspicion",
+ "▁suspension",
+ "▁portrait",
+ "▁justify",
+ "plex",
+ "burn",
+ "▁faculty",
+ "▁singer",
+ "▁Hawaii",
+ "▁Singapore",
+ "▁horizontal",
+ "Whatever",
+ "▁dentist",
+ "▁Report",
+ "▁Marine",
+ "▁hopeful",
+ "▁aggregate",
+ "▁scroll",
+ "▁Lucy",
+ "▁differentiated",
+ "▁horn",
+ "▁crude",
+ "▁occasional",
+ "▁wiped",
+ "▁Overall",
+ "▁coding",
+ "product",
+ "▁shortage",
+ "▁straw",
+ "▁portray",
+ "Remember",
+ "▁tendency",
+ "▁securities",
+ "▁Hotel",
+ "▁queen",
+ "▁variability",
+ "▁implies",
+ "▁metabolic",
+ "▁uncover",
+ "▁statue",
+ "▁invasion",
+ "utter",
+ "▁smash",
+ "▁magnet",
+ "▁thrilled",
+ "▁Miami",
+ "▁quest",
+ "▁bargain",
+ "▁durable",
+ "▁hesitated",
+ "▁NY",
+ "▁computing",
+ "▁prevail",
+ "▁compensate",
+ "▁canvas",
+ "▁therapist",
+ "▁tennis",
+ "▁realizing",
+ "▁educated",
+ "▁facial",
+ "▁tense",
+ "▁vest",
+ "▁Made",
+ "▁dwell",
+ "think",
+ "▁theatre",
+ "▁Philip",
+ "Between",
+ "▁tolerate",
+ "▁amazed",
+ "▁valve",
+ "▁Want",
+ "▁devil",
+ "▁bloom",
+ "▁certification",
+ "▁taxi",
+ "▁farther",
+ "▁tattoo",
+ "▁revised",
+ "▁Lewis",
+ "▁enjoyable",
+ "▁Unless",
+ "▁Matthew",
+ "▁realization",
+ "▁locate",
+ "▁Medicare",
+ "▁unconscious",
+ "▁motive",
+ "▁Based",
+ "▁thermo",
+ "▁Usually",
+ "▁Pack",
+ "▁Que",
+ "▁charging",
+ "Nevertheless",
+ "▁introducing",
+ "▁Susan",
+ "▁genome",
+ "▁Feel",
+ "▁suspended",
+ "▁synthesis",
+ "▁realised",
+ "▁Def",
+ "▁welfare",
+ "▁proactive",
+ "▁Sydney",
+ "▁eleventh",
+ "▁desperately",
+ "▁mobility",
+ "▁Bear",
+ "Lucki",
+ "▁relieved",
+ "▁beverage",
+ "▁interference",
+ "▁Space",
+ "▁harmful",
+ "▁Museum",
+ "▁handsome",
+ "▁aggressively",
+ "▁virtue",
+ "▁thrust",
+ "▁flee",
+ "▁printer",
+ "▁Empire",
+ "▁fabulous",
+ "▁enhancing",
+ "▁scoop",
+ "▁Journal",
+ "▁eighteenth",
+ "▁Christianity",
+ "▁compression",
+ "▁harbor",
+ "▁activated",
+ "▁paragraph",
+ "▁universities",
+ "▁drown",
+ "▁TB",
+ "▁Vol",
+ "▁furnish",
+ "▁prudent",
+ "▁Fund",
+ "▁defence",
+ "▁Navy",
+ "▁predominant",
+ "▁validation",
+ "▁embarrassed",
+ "▁lick",
+ "▁replicate",
+ "▁drip",
+ "▁bark",
+ "▁Para",
+ "▁cocktail",
+ "▁frightened",
+ "▁trajectory",
+ "▁Diego",
+ "structure",
+ "▁Dallas",
+ "▁specialized",
+ "▁antibodies",
+ "▁Bull",
+ "▁curiosity",
+ "▁faithful",
+ "▁flavour",
+ "▁electrode",
+ "▁disability",
+ "▁niche",
+ "▁neural",
+ "▁Chelsea",
+ "Plus",
+ "▁believing",
+ "▁aroma",
+ "▁swift",
+ "▁whistle",
+ "▁Yu",
+ "▁persistent",
+ "Anyway",
+ "▁Avenue",
+ "▁Greece",
+ "▁scattered",
+ "▁Engine",
+ "▁tricky",
+ "▁tutorial",
+ "▁Often",
+ "around",
+ "▁Easter",
+ "▁swung",
+ "▁Sanders",
+ "▁Week",
+ "scale",
+ "▁humble",
+ "▁RE",
+ "▁Natural",
+ "▁Moon",
+ "▁Order",
+ "▁eternal",
+ "▁corruption",
+ "Several",
+ "▁shipped",
+ "▁eighties",
+ "▁sibling",
+ "bone",
+ "▁CV",
+ "▁laundry",
+ "ession",
+ "▁Lincoln",
+ "▁appetite",
+ "▁libraries",
+ "▁Excel",
+ "▁Emily",
+ "▁harass",
+ "▁Author",
+ "▁Bowl",
+ "▁Farm",
+ "▁skull",
+ "▁conceal",
+ "▁recommendation",
+ "▁arrange",
+ "Ultimately",
+ "▁chemistry",
+ "▁leveraging",
+ "▁fasci",
+ "▁recurring",
+ "▁geo",
+ "▁interactive",
+ "▁Captain",
+ "▁dumpster",
+ "Obviously",
+ "▁dislike",
+ "▁revision",
+ "▁wealthy",
+ "▁Steven",
+ "▁terrific",
+ "▁Following",
+ "▁stride",
+ "▁realise",
+ "▁specimen",
+ "▁Everybody",
+ "▁Investor",
+ "▁aunt",
+ "▁Ukraine",
+ "▁overwhelmed",
+ "▁Thr",
+ "▁manually",
+ "▁Square",
+ "▁Beth",
+ "▁archive",
+ "▁swept",
+ "▁goodbye",
+ "▁peripheral",
+ "making",
+ "▁Night",
+ "▁Community",
+ "▁Atlanta",
+ "▁soccer",
+ "▁replacing",
+ "▁stakeholders",
+ "▁remodel",
+ "▁technician",
+ "▁passive",
+ "▁Beck",
+ "Part",
+ "▁Brother",
+ "▁Capital",
+ "▁persuade",
+ "plain",
+ "▁Full",
+ "▁pho",
+ "▁garbage",
+ "▁Common",
+ "▁describing",
+ "▁Opera",
+ "▁mindful",
+ "▁anonymous",
+ "▁instructor",
+ "▁Disc",
+ "▁tolerance",
+ "▁Grace",
+ "▁absurd",
+ "▁splash",
+ "▁Stay",
+ "▁pickup",
+ "▁lazy",
+ "▁chef",
+ "▁Scottish",
+ "▁viable",
+ "▁MB",
+ "▁stove",
+ "▁BBC",
+ "▁GB",
+ "▁Java",
+ "▁hurricane",
+ "▁Almost",
+ "▁stimulation",
+ "▁absorption",
+ "▁coupling",
+ "▁Columbia",
+ "▁wreck",
+ "▁Amy",
+ "▁MT",
+ "cott",
+ "ectomy",
+ "nstru",
+ "▁scare",
+ "▁font",
+ "▁Premier",
+ "▁Line",
+ "▁midnight",
+ "▁LC",
+ "▁athletic",
+ "▁worries",
+ "▁romance",
+ "▁healthier",
+ "▁utilizing",
+ "▁resistant",
+ "▁Sign",
+ "▁necessity",
+ "▁spontaneous",
+ "▁folk",
+ "▁nineties",
+ "▁Division",
+ "▁moisture",
+ "▁batter",
+ "▁assign",
+ "▁pencil",
+ "▁resemble",
+ "▁disposal",
+ "▁Cru",
+ "▁Securities",
+ "▁Conference",
+ "▁Ol",
+ "posed",
+ "▁drone",
+ "▁commence",
+ "▁affection",
+ "▁Kansas",
+ "▁Morgan",
+ "▁Minnesota",
+ "▁Summer",
+ "▁varies",
+ "▁invasive",
+ "hn",
+ "▁lever",
+ "▁racist",
+ "▁footage",
+ "▁symptom",
+ "interest",
+ "▁VA",
+ "▁heritage",
+ "▁regimen",
+ "▁vintage",
+ "▁arguing",
+ "▁automated",
+ "▁regain",
+ "John",
+ "▁coupon",
+ "▁obey",
+ "▁diameter",
+ "▁resident",
+ "▁Small",
+ "▁Labor",
+ "▁Jan",
+ "▁Cameron",
+ "▁methodology",
+ "viv",
+ "▁initiated",
+ "▁updating",
+ "▁thickness",
+ "▁onset",
+ "▁solving",
+ "▁batteries",
+ "▁tomatoes",
+ "▁quilt",
+ "▁beloved",
+ "▁rocket",
+ "▁midst",
+ "▁synergies",
+ "▁circum",
+ "▁Cuba",
+ "▁biology",
+ "▁illusion",
+ "▁rigid",
+ "▁genuinely",
+ "▁eastern",
+ "▁reproduce",
+ "▁stroll",
+ "▁foam",
+ "▁secretary",
+ "Very",
+ "▁vibrant",
+ "▁transit",
+ "▁democratic",
+ "▁Way",
+ "▁vampire",
+ "▁Howard",
+ "▁depart",
+ "▁detective",
+ "▁temporal",
+ "plasm",
+ "▁kingdom",
+ "▁antibody",
+ "▁utter",
+ "▁merchandise",
+ "▁prosecutor",
+ "▁serial",
+ "▁genius",
+ "▁balloon",
+ "▁terrified",
+ "▁masses",
+ "▁entries",
+ "▁discontinu",
+ "▁Philadelphia",
+ "▁inhabit",
+ "▁warrior",
+ "▁disabled",
+ "stead",
+ "▁easiest",
+ "▁fog",
+ "▁proliferation",
+ "▁sacred",
+ "▁ministry",
+ "▁cope",
+ "Due",
+ "▁underway",
+ "▁Charlotte",
+ "▁encrypt",
+ "▁coefficient",
+ "▁simplicity",
+ "▁personalized",
+ "▁Multi",
+ "▁backyard",
+ "▁helmet",
+ "▁enthusiastic",
+ "▁premier",
+ "▁nasty",
+ "▁differentiate",
+ "▁medal",
+ "▁Laura",
+ "▁kilo",
+ "▁tragedy",
+ "▁coconut",
+ "▁Section",
+ "▁dug",
+ "▁Arthur",
+ "▁apparatus",
+ "Cha",
+ "▁supplied",
+ "▁diagram",
+ "▁selfish",
+ "▁custody",
+ "▁illustration",
+ "▁homework",
+ "▁UV",
+ "▁hunger",
+ "▁Major",
+ "▁litigation",
+ "▁compatible",
+ "trans",
+ "▁pathogen",
+ "▁Fun",
+ "▁artistic",
+ "▁foolish",
+ "▁seventies",
+ "▁quarterback",
+ "▁sniff",
+ "▁optional",
+ "▁stepping",
+ "▁simplify",
+ "▁quantities",
+ "▁pivot",
+ "▁animation",
+ "Nonetheless",
+ "▁seventeenth",
+ "▁municipal",
+ "▁inspiring",
+ "▁Fortunately",
+ "▁backpack",
+ "▁emit",
+ "▁intuitive",
+ "▁RP",
+ "▁transcription",
+ "▁Centre",
+ "▁marginal",
+ "▁mathematical",
+ "▁referral",
+ "▁hover",
+ "▁analytical",
+ "▁hatred",
+ "▁tobacco",
+ "▁deemed",
+ "▁unhappy",
+ "ku",
+ "▁intermediate",
+ "Rather",
+ "▁armor",
+ "US",
+ "▁discard",
+ "factor",
+ "▁exhibition",
+ "▁flux",
+ "▁dictate",
+ "▁marine",
+ "▁denial",
+ "▁FDA",
+ "▁sack",
+ "▁notebook",
+ "▁refrigerator",
+ "▁utterly",
+ "▁happier",
+ "Out",
+ "▁Help",
+ "▁bass",
+ "▁corrupt",
+ "dress",
+ "▁scrub",
+ "▁unemployment",
+ "▁Sports",
+ "▁URL",
+ "▁downstairs",
+ "▁underwent",
+ "▁triumph",
+ "▁cricket",
+ "▁rebound",
+ "▁prejudice",
+ "▁cyber",
+ "▁connectivity",
+ "▁bail",
+ "▁Blood",
+ "▁Room",
+ "▁investigating",
+ "Unlike",
+ "Book",
+ "▁Imagine",
+ "▁plugin",
+ "▁Euro",
+ "Great",
+ "▁Kris",
+ "▁scholarship",
+ "▁castle",
+ "▁Ocean",
+ "▁Leave",
+ "▁respiratory",
+ "▁UC",
+ "▁postoperative",
+ "▁alternate",
+ "▁Buck",
+ "▁hurried",
+ "▁vascular",
+ "▁ecommerce",
+ "▁cliff",
+ "▁artwork",
+ "Important",
+ "▁thirtieth",
+ "▁furious",
+ "▁twelfth",
+ "▁pending",
+ "▁sidewalk",
+ "▁intensive",
+ "▁creator",
+ "▁seamless",
+ "▁banned",
+ "▁groan",
+ "▁verbal",
+ "▁explicit",
+ "▁doctrine",
+ "▁heroes",
+ "▁travelling",
+ "▁Julie",
+ "▁porn",
+ "▁ambitious",
+ "▁therapies",
+ "▁duplicate",
+ "▁mindset",
+ "▁superb",
+ "▁predictable",
+ "Hence",
+ "▁ladder",
+ "case",
+ "when",
+ "▁terribly",
+ "▁breakdown",
+ "▁thunder",
+ "Later",
+ "▁stance",
+ "▁Tele",
+ "▁Patrick",
+ "▁despair",
+ "▁analyse",
+ "▁helicopter",
+ "▁administrator",
+ "▁cottage",
+ "▁DVD",
+ "▁vow",
+ "▁Nik",
+ "▁witch",
+ "▁convincing",
+ "▁anniversary",
+ "▁queue",
+ "▁Gary",
+ "▁merge",
+ "▁feather",
+ "▁raid",
+ "▁axis",
+ "▁consuming",
+ "Alternatively",
+ "▁steadily",
+ "▁shelves",
+ "▁portal",
+ "▁memorable",
+ "▁inhibition",
+ "▁declare",
+ "▁questionnaire",
+ "▁Josh",
+ "▁NBA",
+ "▁Wait",
+ "▁derivative",
+ "▁assurance",
+ "▁quantify",
+ "▁sphere",
+ "▁stylish",
+ "▁sixteenth",
+ "▁scarce",
+ "▁simulate",
+ "▁Anyone",
+ "▁Wisconsin",
+ "▁booth",
+ "▁cinema",
+ "▁Austin",
+ "▁Hopefully",
+ "▁fourteenth",
+ "▁applicant",
+ "▁replay",
+ "▁arriving",
+ "▁triple",
+ "▁ME",
+ "▁Short",
+ "▁Girl",
+ "▁nonprofit",
+ "▁categor",
+ "mouth",
+ "▁Detroit",
+ "Different",
+ "▁rude",
+ "▁pollution",
+ "Something",
+ "▁vegetable",
+ "▁renewable",
+ "▁Golden",
+ "▁rally",
+ "▁workforce",
+ "▁patron",
+ "▁blown",
+ "keeper",
+ "▁cardiovascular",
+ "▁originate",
+ "▁contemplate",
+ "▁conservation",
+ "▁Thanksgiving",
+ "Could",
+ "▁void",
+ "▁binary",
+ "▁aluminum",
+ "▁configure",
+ "▁qualification",
+ "▁boast",
+ "▁Johnny",
+ "▁sixties",
+ "▁yearoveryear",
+ "▁Series",
+ "▁sync",
+ "storm",
+ "▁Shop",
+ "▁retire",
+ "▁practicing",
+ "▁manipulate",
+ "Three",
+ "▁underwriting",
+ "flat",
+ "▁rag",
+ "▁shiny",
+ "▁gem",
+ "▁spinning",
+ "▁flex",
+ "escence",
+ "▁expire",
+ "▁discomfort",
+ "▁confidential",
+ "▁Sean",
+ "▁verdict",
+ "▁Standard",
+ "▁observer",
+ "▁contra",
+ "▁Stop",
+ "▁Liverpool",
+ "▁practitioner",
+ "▁variance",
+ "▁interfere",
+ "▁Carter",
+ "▁marvel",
+ "▁magnificent",
+ "▁distinctive",
+ "▁sadness",
+ "▁Drive",
+ "▁crunch",
+ "▁lounge",
+ "▁designated",
+ "Interestingly",
+ "▁spur",
+ "▁synthetic",
+ "▁Fran",
+ "▁Nice",
+ "▁Brook",
+ "▁credibility",
+ "▁jewel",
+ "▁fitted",
+ "▁dependence",
+ "▁equality",
+ "▁definitive",
+ "▁dissolve",
+ "▁irrelevant",
+ "▁embryo",
+ "▁chemotherapy",
+ "▁labour",
+ "▁leasing",
+ "suit",
+ "▁portable",
+ "Additional",
+ "▁Wolf",
+ "step",
+ "▁Creek",
+ "▁Seven",
+ "▁Bruce",
+ "▁wheat",
+ "▁bulb",
+ "Should",
+ "▁tide",
+ "develop",
+ "▁calcium",
+ "▁vivo",
+ "▁normalized",
+ "▁exempt",
+ "▁crust",
+ "▁collision",
+ "▁Eagle",
+ "▁Danny",
+ "▁Massachusetts",
+ "▁honour",
+ "▁Alaska",
+ "▁rejection",
+ "▁Lisa",
+ "▁miserable",
+ "▁bacterial",
+ "▁hydr",
+ "▁frequencies",
+ "▁digging",
+ "▁Clean",
+ "▁civilization",
+ "▁approve",
+ "▁ashamed",
+ "▁hiking",
+ "▁agricultural",
+ "▁unchanged",
+ "▁Romney",
+ "▁competitor",
+ "▁wildlife",
+ "ophil",
+ "▁repurchase",
+ "▁bruise",
+ "wide",
+ "▁wax",
+ "Read",
+ "value",
+ "▁recruitment",
+ "screen",
+ "▁qualitative",
+ "▁ballot",
+ "▁streak",
+ "▁accelerating",
+ "▁spun",
+ "ogenic",
+ "Honestly",
+ "▁posture",
+ "▁commerce",
+ "▁authorized",
+ "▁Burn",
+ "▁freight",
+ "▁activate",
+ "▁patrol",
+ "▁Championship",
+ "▁secular",
+ "▁Administration",
+ "▁deviation",
+ "▁Ruth",
+ "▁obesity",
+ "▁Flor",
+ "▁Dick",
+ "▁renovation",
+ "▁assortment",
+ "ello",
+ "▁Silver",
+ "▁exterior",
+ "▁pinch",
+ "▁scanning",
+ "▁featuring",
+ "▁relevance",
+ "Chris",
+ "▁pistol",
+ "▁Lots",
+ "▁trivial",
+ "▁Gordon",
+ "▁View",
+ "▁vitro",
+ "▁volatile",
+ "rrh",
+ "▁Listen",
+ "▁Heart",
+ "▁fastest",
+ "logical",
+ "▁revelation",
+ "▁residual",
+ "▁pork",
+ "▁estimation",
+ "▁insufficient",
+ "▁coworker",
+ "ogram",
+ "▁conjunction",
+ "▁lipid",
+ "▁bacon",
+ "▁dye",
+ "▁wrinkle",
+ "▁characterize",
+ "▁navigation",
+ "▁grape",
+ "▁bride",
+ "ieving",
+ "▁socks",
+ "▁missile",
+ "▁inquiry",
+ "▁jack",
+ "▁pseudo",
+ "▁debris",
+ "▁broaden",
+ "▁cement",
+ "▁replied",
+ "▁sensible",
+ "▁Lion",
+ "▁exert",
+ "▁Thor",
+ "▁attendance",
+ "▁bru",
+ "▁metaphor",
+ "▁mug",
+ "▁lime",
+ "▁numb",
+ "▁vegan",
+ "▁MR",
+ "wick",
+ "▁Alabama",
+ "▁relentless",
+ "▁monkey",
+ "▁driveway",
+ "▁presume",
+ "Among",
+ "▁GDP",
+ "▁singular",
+ "▁automobile",
+ "▁deferred",
+ "▁Jamie",
+ "▁Glen",
+ "▁circular",
+ "▁CPU",
+ "▁expose",
+ "▁dietary",
+ "▁gratitude",
+ "▁banana",
+ "▁extraction",
+ "▁stirring",
+ "▁benchmark",
+ "▁mitochondria",
+ "▁slammed",
+ "▁educate",
+ "▁Simply",
+ "▁unsure",
+ "▁Better",
+ "▁Oklahoma",
+ "▁Joan",
+ "▁legislative",
+ "▁sovereign",
+ "▁puff",
+ "▁Gabriel",
+ "▁physiological",
+ "▁relaxation",
+ "▁popped",
+ "▁Sara",
+ "▁Field",
+ "▁PDF",
+ "▁showcase",
+ "▁compartment",
+ "▁Wales",
+ "▁thirteenth",
+ "▁mapping",
+ "Think",
+ "▁GOP",
+ "▁Aaron",
+ "▁Penn",
+ "▁tragic",
+ "▁banner",
+ "▁claw",
+ "▁intrinsic",
+ "▁geographical",
+ "▁anticipation",
+ "▁Rule",
+ "▁semiconductor",
+ "▁swirl",
+ "▁temporarily",
+ "▁formulation",
+ "▁respectful",
+ "writer",
+ "proof",
+ "▁colorful",
+ "▁frost",
+ "▁lion",
+ "▁empire",
+ "▁Revolution",
+ "▁antioxidant",
+ "▁zombie",
+ "Find",
+ "▁Price",
+ "▁stalk",
+ "▁scandal",
+ "▁Manhattan",
+ "▁devastating",
+ "▁participant",
+ "▁validity",
+ "▁tack",
+ "▁kilometers",
+ "about",
+ "▁Denver",
+ "▁Lou",
+ "▁racism",
+ "▁threaten",
+ "▁patio",
+ "▁declining",
+ "▁tasty",
+ "hawk",
+ "▁erect",
+ "▁seizure",
+ "▁summon",
+ "cca",
+ "▁stadium",
+ "▁withdrawal",
+ "▁amplitude",
+ "▁Currently",
+ "▁drastic",
+ "Work",
+ "▁rigorous",
+ "▁conspiracy",
+ "▁derive",
+ "▁stressful",
+ "▁headquarters",
+ "▁Cooper",
+ "▁Jean",
+ "▁gossip",
+ "▁detector",
+ "▁flare",
+ "▁Berlin",
+ "▁ribbon",
+ "▁flap",
+ "▁Nathan",
+ "▁abundant",
+ "▁curated",
+ "▁subset",
+ "▁Jerry",
+ "▁Sweden",
+ "▁perceive",
+ "▁welcoming",
+ "▁Treat",
+ "▁Arabia",
+ "▁autumn",
+ "▁sprinkle",
+ "▁Pete",
+ "▁Change",
+ "▁lend",
+ "▁combining",
+ "▁tapped",
+ "▁comparative",
+ "▁amino",
+ "▁discourage",
+ "▁kidnap",
+ "▁diagnose",
+ "▁epic",
+ "▁Tennessee",
+ "pack",
+ "▁pharmaceutical",
+ "▁scramble",
+ "▁CNN",
+ "▁Certainly",
+ "▁homeowner",
+ "▁intersection",
+ "▁tropical",
+ "▁Judge",
+ "▁Depend",
+ "▁greed",
+ "bacter",
+ "▁Morris",
+ "▁seasonality",
+ "▁Syrian",
+ "▁Review",
+ "▁causal",
+ "Previous",
+ "▁arbitrary",
+ "▁tweak",
+ "▁cannabis",
+ "▁churn",
+ "▁freezing",
+ "▁shining",
+ "▁adaptation",
+ "▁ginger",
+ "▁Death",
+ "▁curriculum",
+ "▁nonsense",
+ "▁bicycle",
+ "▁Palm",
+ "▁Cloud",
+ "▁blogging",
+ "▁mercy",
+ "lving",
+ "▁frown",
+ "▁demonstrating",
+ "▁residue",
+ "▁spiral",
+ "▁pillar",
+ "▁problematic",
+ "▁habitat",
+ "▁pulmonary",
+ "▁Linux",
+ "▁agriculture",
+ "▁Whit",
+ "▁whatsoever",
+ "▁steak",
+ "▁hugged",
+ "▁revolve",
+ "▁approximation",
+ "▁rhetoric",
+ "▁mac",
+ "▁architect",
+ "▁vibration",
+ "▁sustainability",
+ "▁worm",
+ "▁parliament",
+ "▁shudder",
+ "▁literary",
+ "▁burger",
+ "▁unpleasant",
+ "▁Dream",
+ "▁relied",
+ "▁antenna",
+ "▁Hitler",
+ "▁wool",
+ "▁fireplace",
+ "▁restart",
+ "▁slap",
+ "▁Egyptian",
+ "▁Moscow",
+ "▁Manager",
+ "▁sunny",
+ "foot",
+ "▁prescribed",
+ "▁GPS",
+ "▁alliance",
+ "▁Write",
+ "▁Anthony",
+ "▁turnover",
+ "▁Development",
+ "▁cache",
+ "▁Express",
+ "▁Moore",
+ "▁unfortunate",
+ "▁inevitably",
+ "▁penetrate",
+ "Start",
+ "▁invade",
+ "▁ignoring",
+ "▁cartoon",
+ "▁hockey",
+ "▁speculation",
+ "▁recession",
+ "▁Blake",
+ "▁restoration",
+ "▁litter",
+ "▁artery",
+ "Consider",
+ "▁escort",
+ "▁vanilla",
+ "▁Pick",
+ "▁Poland",
+ "▁antigen",
+ "▁osteo",
+ "▁algebra",
+ "▁defining",
+ "▁slavery",
+ "▁dairy",
+ "▁conquer",
+ "▁governance",
+ "▁computational",
+ "▁mandatory",
+ "▁Eddie",
+ "▁Winter",
+ "▁HTML",
+ "▁Living",
+ "▁Left",
+ "▁Craig",
+ "▁nevertheless",
+ "▁Travel",
+ "▁relieve",
+ "disciplinary",
+ "▁Contact",
+ "▁oak",
+ "ancies",
+ "▁terrorism",
+ "▁Studio",
+ "▁sunset",
+ "▁yo",
+ "▁Getting",
+ "▁excluding",
+ "▁recycling",
+ "▁constructive",
+ "▁scam",
+ "▁discern",
+ "phon",
+ "▁teenage",
+ "▁informative",
+ "▁potent",
+ "▁Technology",
+ "▁potato",
+ "▁paw",
+ "▁accumulation",
+ "▁Step",
+ "▁endeavor",
+ "▁peptide",
+ "▁hatch",
+ "▁blush",
+ "▁Digital",
+ "▁passport",
+ "▁Rich",
+ "▁Uncle",
+ "▁flies",
+ "▁taxpayer",
+ "▁psychology",
+ "▁JavaScript",
+ "▁gambling",
+ "▁Steel",
+ "▁foresee",
+ "▁supervisor",
+ "▁ingredient",
+ "▁ripped",
+ "▁Clinic",
+ "▁indulge",
+ "▁Collect",
+ "▁advertisement",
+ "▁cattle",
+ "▁turkey",
+ "▁lamb",
+ "▁disposition",
+ "▁licensing",
+ "▁Larry",
+ "▁elastic",
+ "▁societies",
+ "▁visa",
+ "▁immunity",
+ "▁concession",
+ "▁Tommy",
+ "▁Similarly",
+ "▁Halloween",
+ "▁conscience",
+ "▁Smart",
+ "▁Tower",
+ "▁chasing",
+ "▁versatile",
+ "▁induction",
+ "▁Library",
+ "▁enrollment",
+ "▁Nigeria",
+ "▁yeast",
+ "▁motorcycle",
+ "▁nonetheless",
+ "▁proximity",
+ "▁Mount",
+ "▁Enjoy",
+ "▁obscure",
+ "Back",
+ "▁compose",
+ "Until",
+ "▁diligent",
+ "blast",
+ "▁isolate",
+ "▁uncommon",
+ "▁Circuit",
+ "▁rotate",
+ "▁empirical",
+ "Har",
+ "▁Claire",
+ "▁Tax",
+ "▁circulation",
+ "code",
+ "▁decorated",
+ "▁Warren",
+ "Check",
+ "▁discrete",
+ "vocation",
+ "▁accountability",
+ "▁mimic",
+ "▁elder",
+ "▁plague",
+ "function",
+ "▁browse",
+ "▁Select",
+ "▁varieties",
+ "▁Iranian",
+ "▁symmetry",
+ "▁Jeremy",
+ "▁assembled",
+ "▁pronounced",
+ "▁gradient",
+ "▁augment",
+ "▁cholesterol",
+ "▁Kennedy",
+ "▁encouragement",
+ "▁hollow",
+ "▁peek",
+ "Actually",
+ "▁controversy",
+ "▁permalink",
+ "▁Nature",
+ "▁Annie",
+ "▁supermarket",
+ "▁Victor",
+ "Third",
+ "▁tee",
+ "▁inviting",
+ "▁Model",
+ "▁dorm",
+ "▁retrospective",
+ "▁hydrogen",
+ "▁maturity",
+ "▁reconstruction",
+ "▁feasible",
+ "▁Figure",
+ "▁manifestation",
+ "▁Jerusalem",
+ "▁proprietary",
+ "▁Spec",
+ "▁asthma",
+ "▁Hannah",
+ "▁footsteps",
+ "ika",
+ "▁peanut",
+ "▁fame",
+ "▁radar",
+ "▁judicial",
+ "▁monument",
+ "▁Daily",
+ "▁shoved",
+ "▁unprecedented",
+ "▁palace",
+ "▁twenties",
+ "▁surround",
+ "▁Beijing",
+ "written",
+ "▁proving",
+ "▁Snow",
+ "▁Aunt",
+ "▁orchestra",
+ "▁leisure",
+ "▁Lock",
+ "▁inclined",
+ "▁examining",
+ "▁catalyst",
+ "▁Local",
+ "▁Alexander",
+ "▁conceive",
+ "Normally",
+ "▁adolescent",
+ "▁wolf",
+ "▁Private",
+ "▁elephant",
+ "zen",
+ "▁Conservative",
+ "▁Solutions",
+ "▁waking",
+ "▁forgiveness",
+ "▁clone",
+ "▁Wayne",
+ "▁CIA",
+ "▁roster",
+ "▁Indonesia",
+ "▁imperative",
+ "▁cardio",
+ "▁Duke",
+ "▁Staff",
+ "▁scaling",
+ "given",
+ "▁stunned",
+ "▁exotic",
+ "▁degradation",
+ "▁Missouri",
+ "▁graft",
+ "▁decreasing",
+ "▁Anything",
+ "▁spacious",
+ "▁collaborative",
+ "▁CBD",
+ "▁economies",
+ "▁Connect",
+ "ulu",
+ "▁dart",
+ "Time",
+ "▁foul",
+ "▁mourn",
+ "▁Bryan",
+ "▁editorial",
+ "▁Trade",
+ "▁airplane",
+ "▁geometry",
+ "▁prolonged",
+ "▁releasing",
+ "▁Together",
+ "▁choke",
+ "▁stool",
+ "▁spider",
+ "▁riot",
+ "▁celebrating",
+ "▁adore",
+ "▁galaxy",
+ "▁hobby",
+ "▁skate",
+ "▁operative",
+ "smith",
+ "▁backdrop",
+ "▁reimbursement",
+ "▁remedy",
+ "▁analyzing",
+ "▁predictive",
+ "▁Guide",
+ "▁Kyle",
+ "▁Hawk",
+ "▁vivid",
+ "▁Fast",
+ "▁articulate",
+ "nitially",
+ "▁pledge",
+ "▁explosive",
+ "▁dignity",
+ "▁flourish",
+ "▁foremost",
+ "▁recognizing",
+ "▁urine",
+ "▁artifact",
+ "▁statutory",
+ "▁stellar",
+ "▁albeit",
+ "▁nonlinear",
+ "▁Monte",
+ "▁communicating",
+ "▁aisle",
+ "▁Margaret",
+ "▁marble",
+ "▁envision",
+ "▁accusation",
+ "▁acquiring",
+ "▁Policy",
+ "▁Stock",
+ "▁Festival",
+ "▁vomit",
+ "shift",
+ "▁spectral",
+ "▁trademark",
+ "▁prosecution",
+ "▁Marcus",
+ "▁Must",
+ "▁conceptual",
+ "▁delegate",
+ "▁robe",
+ "▁basin",
+ "▁Deep",
+ "▁unlimited",
+ "giving",
+ "▁diversified",
+ "▁impulse",
+ "▁Finn",
+ "▁scout",
+ "▁fragile",
+ "▁terrain",
+ "▁Governor",
+ "▁lightweight",
+ "including",
+ "▁fossil",
+ "▁Basically",
+ "▁Below",
+ "▁inexpensive",
+ "▁fixture",
+ "▁Portland",
+ "▁Hindu",
+ "writing",
+ "▁firearm",
+ "▁Jonathan",
+ "▁Kentucky",
+ "▁Russell",
+ "▁ensu",
+ "▁microwave",
+ "▁exponential",
+ "▁groom",
+ "▁scanned",
+ "▁earliest",
+ "▁Search",
+ "▁gloss",
+ "▁cosmetic",
+ "▁equilibrium",
+ "▁enlighten",
+ "▁opera",
+ "▁bizarre",
+ "▁clench",
+ "▁sympathy",
+ "▁cycling",
+ "▁WordPress",
+ "▁carriage",
+ "▁cyst",
+ "▁Record",
+ "Ladies",
+ "▁invented",
+ "▁fifties",
+ "▁phenotype",
+ "▁Access",
+ "▁computation",
+ "▁Insurance",
+ "Regarding",
+ "▁initiate",
+ "▁shrug",
+ "▁metallic",
+ "▁scientist",
+ "bank",
+ "▁senator",
+ "▁Baby",
+ "▁OEM",
+ "ncluding",
+ "▁Oxford",
+ "▁assassin",
+ "▁Netflix",
+ "▁Outside",
+ "▁Maryland",
+ "▁glorious",
+ "▁Maggie",
+ "▁flipped",
+ "▁Senator",
+ "▁Remove",
+ "▁cultivate",
+ "▁optimism",
+ "▁inadequate",
+ "▁reinvest",
+ "▁Direct",
+ "▁centimeters",
+ "▁Mississippi",
+ "▁tangible",
+ "▁composite",
+ "▁Austria",
+ "▁pediatric",
+ "▁impaired",
+ "▁underestimate",
+ "▁transmitted",
+ "▁ignorance",
+ "▁Season",
+ "▁acres",
+ "▁quasi",
+ "▁competent",
+ "▁Factor",
+ "▁journalism",
+ "▁plunge",
+ "▁Heaven",
+ "▁heavier",
+ "▁Utah",
+ "▁Netherlands",
+ "▁slump",
+ "Develop",
+ "▁History",
+ "▁parade",
+ "▁advancing",
+ "▁slack",
+ "▁Industrial",
+ "▁annoyed",
+ "▁silicon",
+ "▁solicit",
+ "▁semester",
+ "▁prototype",
+ "activity",
+ "▁complementary",
+ "▁energies",
+ "frame",
+ "▁earthquake",
+ "▁verified",
+ "▁exclusion",
+ "▁balancing",
+ "▁fetch",
+ "▁stripped",
+ "▁cube",
+ "▁organizing",
+ "▁Ontario",
+ "▁ambulance",
+ "▁capturing",
+ "▁resonance",
+ "virus",
+ "About",
+ "▁Mau",
+ "▁maternal",
+ "▁Walter",
+ "▁comfortably",
+ "▁alpha",
+ "▁Taiwan",
+ "▁Orleans",
+ "▁Knight",
+ "▁vinegar",
+ "▁migrate",
+ "▁dispose",
+ "▁Ministry",
+ "▁galaxies",
+ "▁presumably",
+ "▁limp",
+ "▁clay",
+ "▁reckon",
+ "▁incurred",
+ "▁picnic",
+ "▁Jew",
+ "▁Support",
+ "▁dude",
+ "▁unreal",
+ "▁hypertension",
+ "▁paradigm",
+ "▁utilities",
+ "▁avenue",
+ "▁Cleveland",
+ "▁Nancy",
+ "▁prophet",
+ "▁messaging",
+ "▁manipulation",
+ "▁disciple",
+ "▁reopen",
+ "▁monetary",
+ "▁speculate",
+ "▁stimulus",
+ "▁whirl",
+ "▁blot",
+ "▁broth",
+ "▁energetic",
+ "▁Phoenix",
+ "quarter",
+ "▁unaware",
+ "▁chlor",
+ "▁Medi",
+ "▁kernel",
+ "▁declaration",
+ "▁integrating",
+ "▁shaft",
+ "▁Quick",
+ "▁pandemic",
+ "▁undoubtedly",
+ "▁constitution",
+ "▁lattice",
+ "Employ",
+ "motion",
+ "▁predator",
+ "▁blockchain",
+ "strict",
+ "▁revise",
+ "▁geography",
+ "scape",
+ "▁Semi",
+ "▁wagon",
+ "▁hostile",
+ "▁deficiency",
+ "▁clause",
+ "▁crouch",
+ "▁Oscar",
+ "▁impress",
+ "▁philosophical",
+ "▁Close",
+ "▁voluntary",
+ "▁situated",
+ "▁clerk",
+ "▁Oliver",
+ "▁sorrow",
+ "▁Turkish",
+ "▁salvation",
+ "▁Vancouver",
+ "▁twitch",
+ "walk",
+ "▁jazz",
+ "uzz",
+ "▁mRNA",
+ "▁occupy",
+ "▁sympathetic",
+ "▁Francis",
+ "▁encode",
+ "▁hetero",
+ "▁thirties",
+ "▁obsessed",
+ "▁damaging",
+ "▁Corporation",
+ "▁attributable",
+ "▁scalp",
+ "▁Eye",
+ "▁mutant",
+ "▁saddle",
+ "▁sank",
+ "▁seminar",
+ "▁spectra",
+ "▁funnel",
+ "▁bracket",
+ "▁revenge",
+ "▁bandwidth",
+ "▁Karen",
+ "▁termination",
+ "Otherwise",
+ "▁unwanted",
+ "▁temptation",
+ "▁Visit",
+ "▁actress",
+ "▁Consumer",
+ "▁pumpkin",
+ "▁inference",
+ "Ju",
+ "opathy",
+ "▁biopsy",
+ "▁invalid",
+ "▁Mediterranean",
+ "▁premature",
+ "▁vaccination",
+ "▁coincide",
+ "▁Switzerland",
+ "▁approximate",
+ "▁gospel",
+ "▁Jennifer",
+ "▁amenities",
+ "▁peculiar",
+ "▁wives",
+ "▁glitter",
+ "▁stole",
+ "Individual",
+ "▁biomarker",
+ "▁confined",
+ "▁Convention",
+ "Essential",
+ "▁Command",
+ "▁Tiger",
+ "▁Louisiana",
+ "▁Medicaid",
+ "▁Agency",
+ "▁tempted",
+ "▁odor",
+ "▁undermine",
+ "▁liberty",
+ "▁Nelson",
+ "▁harness",
+ "▁tasting",
+ "Eventually",
+ "▁Harvard",
+ "▁iOS",
+ "▁occupancy",
+ "▁reiterate",
+ "▁graduation",
+ "▁encompass",
+ "々",
+ "!",
+ "\"",
+ "#",
+ "$",
+ "%",
+ "&",
+ "(",
+ ")",
+ "*",
+ "+",
+ ",",
+ "-",
+ ".",
+ "/",
+ "0",
+ "1",
+ "2",
+ "3",
+ "4",
+ "5",
+ "6",
+ "7",
+ "8",
+ "9",
+ ":",
+ ";",
+ "<",
+ "=",
+ ">",
+ "?",
+ "@",
+ "[",
+ "\\",
+ "]",
+ "^",
+ "_",
+ "`",
+ "{",
+ "|",
+ "}",
+ "~",
+ "·",
+ "—",
+ "―",
+ "‘",
+ "’",
+ "“",
+ "”",
+ "…",
+ "‧",
+ "℃",
+ "○",
+ "、",
+ "。",
+ "〃",
+ "〆",
+ "〇",
+ "〈",
+ "〉",
+ "《",
+ "》",
+ "「",
+ "」",
+ "『",
+ "』",
+ "【",
+ "】",
+ "〒",
+ "〜",
+ "〝",
+ "〞",
+ "ぁ",
+ "あ",
+ "ぃ",
+ "い",
+ "ぅ",
+ "う",
+ "ぇ",
+ "え",
+ "ぉ",
+ "お",
+ "か",
+ "が",
+ "き",
+ "ぎ",
+ "く",
+ "ぐ",
+ "け",
+ "げ",
+ "こ",
+ "ご",
+ "さ",
+ "ざ",
+ "し",
+ "じ",
+ "す",
+ "ず",
+ "せ",
+ "ぜ",
+ "そ",
+ "ぞ",
+ "た",
+ "だ",
+ "ち",
+ "ぢ",
+ "っ",
+ "つ",
+ "づ",
+ "て",
+ "で",
+ "と",
+ "ど",
+ "な",
+ "に",
+ "ぬ",
+ "ね",
+ "の",
+ "は",
+ "ば",
+ "ぱ",
+ "ひ",
+ "び",
+ "ぴ",
+ "ふ",
+ "ぶ",
+ "ぷ",
+ "へ",
+ "べ",
+ "ぺ",
+ "ほ",
+ "ぼ",
+ "ぽ",
+ "ま",
+ "み",
+ "む",
+ "め",
+ "も",
+ "ゃ",
+ "や",
+ "ゅ",
+ "ゆ",
+ "ょ",
+ "よ",
+ "ら",
+ "り",
+ "る",
+ "れ",
+ "ろ",
+ "わ",
+ "ゐ",
+ "ゑ",
+ "を",
+ "ん",
+ "ゝ",
+ "ゞ",
+ "ァ",
+ "ア",
+ "ィ",
+ "イ",
+ "ゥ",
+ "ウ",
+ "ェ",
+ "エ",
+ "ォ",
+ "オ",
+ "カ",
+ "ガ",
+ "キ",
+ "ギ",
+ "ク",
+ "グ",
+ "ケ",
+ "ゲ",
+ "コ",
+ "ゴ",
+ "サ",
+ "ザ",
+ "シ",
+ "ジ",
+ "ス",
+ "ズ",
+ "セ",
+ "ゼ",
+ "ソ",
+ "ゾ",
+ "タ",
+ "ダ",
+ "チ",
+ "ヂ",
+ "ッ",
+ "ツ",
+ "ヅ",
+ "テ",
+ "デ",
+ "ト",
+ "ド",
+ "ナ",
+ "ニ",
+ "ヌ",
+ "ネ",
+ "ノ",
+ "ハ",
+ "バ",
+ "パ",
+ "ヒ",
+ "ビ",
+ "ピ",
+ "フ",
+ "ブ",
+ "プ",
+ "ヘ",
+ "ベ",
+ "ペ",
+ "ホ",
+ "ボ",
+ "ポ",
+ "マ",
+ "ミ",
+ "ム",
+ "メ",
+ "モ",
+ "ャ",
+ "ヤ",
+ "ュ",
+ "ユ",
+ "ョ",
+ "ヨ",
+ "ラ",
+ "リ",
+ "ル",
+ "レ",
+ "ロ",
+ "ヮ",
+ "ワ",
+ "ヰ",
+ "ヱ",
+ "ヲ",
+ "ン",
+ "ヴ",
+ "ヵ",
+ "ヶ",
+ "・",
+ "ー",
+ "ヾ",
+ "㖭",
+ "㗎",
+ "㩒",
+ "㩧",
+ "䁯",
+ "一",
+ "丁",
+ "七",
+ "万",
+ "丈",
+ "三",
+ "上",
+ "下",
+ "不",
+ "与",
+ "丐",
+ "丑",
+ "专",
+ "且",
+ "丕",
+ "世",
+ "丗",
+ "丘",
+ "丙",
+ "业",
+ "丛",
+ "东",
+ "丝",
+ "丞",
+ "丟",
+ "両",
+ "丢",
+ "两",
+ "严",
+ "並",
+ "丧",
+ "丨",
+ "个",
+ "丫",
+ "中",
+ "丰",
+ "串",
+ "临",
+ "丶",
+ "丸",
+ "丹",
+ "为",
+ "主",
+ "丼",
+ "丽",
+ "举",
+ "乂",
+ "乃",
+ "久",
+ "乇",
+ "么",
+ "义",
+ "之",
+ "乌",
+ "乍",
+ "乎",
+ "乏",
+ "乐",
+ "乒",
+ "乓",
+ "乔",
+ "乖",
+ "乗",
+ "乘",
+ "乙",
+ "乜",
+ "九",
+ "乞",
+ "也",
+ "习",
+ "乡",
+ "乢",
+ "书",
+ "乩",
+ "乪",
+ "买",
+ "乱",
+ "乳",
+ "乸",
+ "乾",
+ "亀",
+ "亁",
+ "亂",
+ "了",
+ "予",
+ "争",
+ "事",
+ "二",
+ "亍",
+ "于",
+ "亏",
+ "云",
+ "互",
+ "亓",
+ "五",
+ "井",
+ "亘",
+ "亙",
+ "亚",
+ "些",
+ "亜",
+ "亞",
+ "亟",
+ "亡",
+ "亢",
+ "交",
+ "亥",
+ "亦",
+ "产",
+ "亨",
+ "亩",
+ "享",
+ "京",
+ "亭",
+ "亮",
+ "亰",
+ "亲",
+ "亳",
+ "亵",
+ "亶",
+ "亹",
+ "人",
+ "亿",
+ "什",
+ "仁",
+ "仂",
+ "仃",
+ "仄",
+ "仅",
+ "仆",
+ "仇",
+ "仉",
+ "今",
+ "介",
+ "仍",
+ "从",
+ "仏",
+ "仑",
+ "仓",
+ "仔",
+ "仕",
+ "他",
+ "仗",
+ "付",
+ "仙",
+ "仝",
+ "仞",
+ "仟",
+ "仡",
+ "代",
+ "令",
+ "以",
+ "仨",
+ "仪",
+ "仫",
+ "们",
+ "仭",
+ "仮",
+ "仰",
+ "仲",
+ "仳",
+ "仵",
+ "件",
+ "价",
+ "任",
+ "份",
+ "仿",
+ "企",
+ "伃",
+ "伄",
+ "伉",
+ "伊",
+ "伋",
+ "伍",
+ "伎",
+ "伏",
+ "伐",
+ "休",
+ "众",
+ "优",
+ "伙",
+ "会",
+ "伛",
+ "伜",
+ "伝",
+ "伞",
+ "伟",
+ "传",
+ "伢",
+ "伤",
+ "伥",
+ "伦",
+ "伧",
+ "伪",
+ "伫",
+ "伯",
+ "估",
+ "伱",
+ "伲",
+ "伴",
+ "伶",
+ "伷",
+ "伸",
+ "伺",
+ "似",
+ "伽",
+ "佃",
+ "但",
+ "佇",
+ "佈",
+ "佉",
+ "位",
+ "低",
+ "住",
+ "佐",
+ "佑",
+ "体",
+ "佔",
+ "何",
+ "佗",
+ "佘",
+ "余",
+ "佚",
+ "佛",
+ "作",
+ "佝",
+ "佞",
+ "佟",
+ "你",
+ "佢",
+ "佣",
+ "佤",
+ "佥",
+ "佩",
+ "佬",
+ "佯",
+ "佰",
+ "佳",
+ "併",
+ "佶",
+ "佷",
+ "佺",
+ "佻",
+ "佼",
+ "佾",
+ "使",
+ "侂",
+ "侃",
+ "侄",
+ "來",
+ "侈",
+ "侉",
+ "例",
+ "侍",
+ "侏",
+ "侑",
+ "侓",
+ "侔",
+ "侗",
+ "侘",
+ "供",
+ "依",
+ "侠",
+ "価",
+ "侣",
+ "侥",
+ "侦",
+ "侧",
+ "侨",
+ "侩",
+ "侪",
+ "侬",
+ "侭",
+ "侮",
+ "侯",
+ "侵",
+ "侶",
+ "侷",
+ "便",
+ "係",
+ "促",
+ "俄",
+ "俅",
+ "俊",
+ "俎",
+ "俏",
+ "俐",
+ "俑",
+ "俔",
+ "俗",
+ "俘",
+ "俚",
+ "俛",
+ "俜",
+ "保",
+ "俞",
+ "俟",
+ "俠",
+ "信",
+ "俢",
+ "俣",
+ "俤",
+ "俦",
+ "俨",
+ "俩",
+ "俪",
+ "俬",
+ "俭",
+ "修",
+ "俯",
+ "俱",
+ "俳",
+ "俵",
+ "俶",
+ "俸",
+ "俺",
+ "俾",
+ "倅",
+ "倆",
+ "倉",
+ "個",
+ "倌",
+ "倍",
+ "倏",
+ "們",
+ "倒",
+ "倓",
+ "倔",
+ "倖",
+ "倘",
+ "候",
+ "倚",
+ "倜",
+ "借",
+ "倡",
+ "倢",
+ "倣",
+ "値",
+ "倥",
+ "倦",
+ "倧",
+ "倨",
+ "倩",
+ "倪",
+ "倫",
+ "倬",
+ "倭",
+ "倮",
+ "倶",
+ "倹",
+ "债",
+ "值",
+ "倾",
+ "偁",
+ "偃",
+ "假",
+ "偈",
+ "偉",
+ "偌",
+ "偎",
+ "偏",
+ "偓",
+ "偕",
+ "偖",
+ "做",
+ "停",
+ "健",
+ "偬",
+ "偭",
+ "偱",
+ "偲",
+ "側",
+ "偵",
+ "偶",
+ "偷",
+ "偸",
+ "偻",
+ "偽",
+ "偾",
+ "偿",
+ "傀",
+ "傅",
+ "傈",
+ "傍",
+ "傑",
+ "傕",
+ "傘",
+ "備",
+ "傜",
+ "傢",
+ "傣",
+ "傥",
+ "傧",
+ "储",
+ "傩",
+ "傫",
+ "催",
+ "傭",
+ "傲",
+ "傳",
+ "傴",
+ "債",
+ "傷",
+ "傺",
+ "傻",
+ "傾",
+ "僂",
+ "僅",
+ "僆",
+ "僉",
+ "僊",
+ "働",
+ "像",
+ "僑",
+ "僔",
+ "僕",
+ "僖",
+ "僚",
+ "僞",
+ "僣",
+ "僥",
+ "僦",
+ "僧",
+ "僬",
+ "僭",
+ "僮",
+ "僱",
+ "僳",
+ "僵",
+ "價",
+ "僻",
+ "儀",
+ "儁",
+ "儂",
+ "億",
+ "儆",
+ "儈",
+ "儉",
+ "儋",
+ "儒",
+ "儔",
+ "儕",
+ "儘",
+ "儚",
+ "償",
+ "儡",
+ "優",
+ "儲",
+ "儷",
+ "儺",
+ "儼",
+ "儿",
+ "兀",
+ "允",
+ "元",
+ "兄",
+ "充",
+ "兆",
+ "兇",
+ "先",
+ "光",
+ "兊",
+ "克",
+ "兌",
+ "免",
+ "兎",
+ "児",
+ "兑",
+ "兒",
+ "兔",
+ "兕",
+ "兖",
+ "党",
+ "兜",
+ "兢",
+ "入",
+ "內",
+ "全",
+ "兩",
+ "兪",
+ "八",
+ "公",
+ "六",
+ "兮",
+ "兰",
+ "共",
+ "关",
+ "兴",
+ "兵",
+ "其",
+ "具",
+ "典",
+ "兹",
+ "养",
+ "兼",
+ "兽",
+ "冀",
+ "冂",
+ "内",
+ "円",
+ "冇",
+ "冈",
+ "冉",
+ "冊",
+ "册",
+ "再",
+ "冏",
+ "冑",
+ "冒",
+ "冕",
+ "冖",
+ "冗",
+ "写",
+ "冚",
+ "军",
+ "农",
+ "冠",
+ "冢",
+ "冤",
+ "冥",
+ "冦",
+ "冧",
+ "冨",
+ "冩",
+ "冪",
+ "冫",
+ "冬",
+ "冮",
+ "冯",
+ "冰",
+ "冱",
+ "冲",
+ "决",
+ "冴",
+ "况",
+ "冶",
+ "冷",
+ "冻",
+ "冼",
+ "冽",
+ "冿",
+ "净",
+ "凄",
+ "准",
+ "凇",
+ "凈",
+ "凉",
+ "凊",
+ "凋",
+ "凌",
+ "凍",
+ "减",
+ "凑",
+ "凖",
+ "凛",
+ "凜",
+ "凝",
+ "几",
+ "凡",
+ "凢",
+ "凤",
+ "処",
+ "凧",
+ "凩",
+ "凪",
+ "凫",
+ "凭",
+ "凯",
+ "凰",
+ "凱",
+ "凳",
+ "凵",
+ "凶",
+ "凸",
+ "凹",
+ "出",
+ "击",
+ "凼",
+ "函",
+ "凿",
+ "刀",
+ "刁",
+ "刃",
+ "分",
+ "切",
+ "刈",
+ "刊",
+ "刍",
+ "刎",
+ "刑",
+ "划",
+ "刔",
+ "列",
+ "刘",
+ "则",
+ "刚",
+ "创",
+ "初",
+ "删",
+ "判",
+ "別",
+ "刨",
+ "利",
+ "刪",
+ "别",
+ "刬",
+ "刭",
+ "刮",
+ "到",
+ "刳",
+ "制",
+ "刷",
+ "券",
+ "刹",
+ "刺",
+ "刻",
+ "刼",
+ "刽",
+ "刿",
+ "剀",
+ "剁",
+ "剂",
+ "剃",
+ "剅",
+ "則",
+ "削",
+ "剋",
+ "剌",
+ "前",
+ "剎",
+ "剐",
+ "剑",
+ "剔",
+ "剕",
+ "剖",
+ "剛",
+ "剜",
+ "剝",
+ "剞",
+ "剟",
+ "剡",
+ "剣",
+ "剤",
+ "剥",
+ "剧",
+ "剩",
+ "剪",
+ "副",
+ "剰",
+ "剱",
+ "割",
+ "剴",
+ "創",
+ "剽",
+ "剿",
+ "劂",
+ "劃",
+ "劇",
+ "劈",
+ "劉",
+ "劍",
+ "劏",
+ "劑",
+ "劒",
+ "劓",
+ "劔",
+ "力",
+ "劝",
+ "办",
+ "功",
+ "加",
+ "务",
+ "劢",
+ "劣",
+ "动",
+ "助",
+ "努",
+ "劫",
+ "劬",
+ "劭",
+ "励",
+ "劲",
+ "劳",
+ "労",
+ "劵",
+ "効",
+ "劼",
+ "劾",
+ "势",
+ "勁",
+ "勃",
+ "勅",
+ "勇",
+ "勉",
+ "勋",
+ "勍",
+ "勐",
+ "勒",
+ "動",
+ "勖",
+ "勗",
+ "勘",
+ "務",
+ "勛",
+ "勝",
+ "勞",
+ "募",
+ "勠",
+ "勢",
+ "勣",
+ "勤",
+ "勦",
+ "勧",
+ "勮",
+ "勰",
+ "勲",
+ "勳",
+ "勵",
+ "勸",
+ "勹",
+ "勺",
+ "勻",
+ "勾",
+ "勿",
+ "匀",
+ "匁",
+ "匂",
+ "包",
+ "匆",
+ "匈",
+ "匍",
+ "匏",
+ "匐",
+ "匕",
+ "化",
+ "北",
+ "匙",
+ "匚",
+ "匜",
+ "匝",
+ "匠",
+ "匡",
+ "匣",
+ "匪",
+ "匮",
+ "匯",
+ "匱",
+ "匸",
+ "匹",
+ "区",
+ "医",
+ "匼",
+ "匽",
+ "匾",
+ "匿",
+ "區",
+ "十",
+ "千",
+ "卅",
+ "卆",
+ "升",
+ "午",
+ "卉",
+ "半",
+ "卍",
+ "华",
+ "协",
+ "卑",
+ "卒",
+ "卓",
+ "協",
+ "单",
+ "卖",
+ "南",
+ "単",
+ "博",
+ "卜",
+ "卞",
+ "卟",
+ "占",
+ "卡",
+ "卢",
+ "卣",
+ "卤",
+ "卦",
+ "卧",
+ "卫",
+ "卬",
+ "卮",
+ "卯",
+ "印",
+ "危",
+ "卲",
+ "即",
+ "却",
+ "卵",
+ "卷",
+ "卸",
+ "卺",
+ "卻",
+ "卿",
+ "厂",
+ "厄",
+ "厅",
+ "历",
+ "厉",
+ "压",
+ "厌",
+ "厍",
+ "厐",
+ "厓",
+ "厔",
+ "厕",
+ "厖",
+ "厘",
+ "厚",
+ "厝",
+ "原",
+ "厠",
+ "厢",
+ "厣",
+ "厥",
+ "厦",
+ "厨",
+ "厩",
+ "厭",
+ "厮",
+ "厰",
+ "厲",
+ "厳",
+ "厶",
+ "去",
+ "县",
+ "叁",
+ "参",
+ "參",
+ "叆",
+ "又",
+ "叉",
+ "及",
+ "友",
+ "双",
+ "反",
+ "収",
+ "发",
+ "叔",
+ "取",
+ "受",
+ "变",
+ "叙",
+ "叛",
+ "叟",
+ "叠",
+ "叡",
+ "叢",
+ "口",
+ "古",
+ "句",
+ "另",
+ "叨",
+ "叩",
+ "只",
+ "叫",
+ "召",
+ "叭",
+ "叮",
+ "可",
+ "台",
+ "叱",
+ "史",
+ "右",
+ "叵",
+ "叶",
+ "号",
+ "司",
+ "叹",
+ "叺",
+ "叻",
+ "叼",
+ "叽",
+ "吁",
+ "吃",
+ "各",
+ "吅",
+ "吆",
+ "吇",
+ "合",
+ "吉",
+ "吊",
+ "吋",
+ "同",
+ "名",
+ "后",
+ "吏",
+ "吐",
+ "向",
+ "吒",
+ "吓",
+ "吔",
+ "吕",
+ "吖",
+ "吗",
+ "吙",
+ "君",
+ "吝",
+ "吞",
+ "吟",
+ "吠",
+ "吡",
+ "吣",
+ "吥",
+ "否",
+ "吧",
+ "吨",
+ "吩",
+ "含",
+ "听",
+ "吭",
+ "吮",
+ "启",
+ "吱",
+ "吲",
+ "吳",
+ "吴",
+ "吵",
+ "吶",
+ "吸",
+ "吹",
+ "吻",
+ "吼",
+ "吽",
+ "吾",
+ "吿",
+ "呀",
+ "呂",
+ "呃",
+ "呆",
+ "呈",
+ "呉",
+ "告",
+ "呋",
+ "呎",
+ "呐",
+ "呑",
+ "呒",
+ "呓",
+ "呔",
+ "呕",
+ "呖",
+ "呗",
+ "员",
+ "呙",
+ "呛",
+ "呜",
+ "呟",
+ "呢",
+ "呣",
+ "呤",
+ "呦",
+ "周",
+ "呪",
+ "呫",
+ "呯",
+ "呰",
+ "呱",
+ "呲",
+ "味",
+ "呵",
+ "呶",
+ "呷",
+ "呸",
+ "呻",
+ "呼",
+ "命",
+ "咀",
+ "咁",
+ "咂",
+ "咄",
+ "咆",
+ "咉",
+ "咋",
+ "和",
+ "咎",
+ "咏",
+ "咐",
+ "咒",
+ "咔",
+ "咕",
+ "咖",
+ "咗",
+ "咘",
+ "咙",
+ "咚",
+ "咛",
+ "咝",
+ "咣",
+ "咤",
+ "咦",
+ "咧",
+ "咨",
+ "咩",
+ "咪",
+ "咫",
+ "咬",
+ "咭",
+ "咯",
+ "咱",
+ "咲",
+ "咳",
+ "咴",
+ "咵",
+ "咶",
+ "咷",
+ "咸",
+ "咹",
+ "咻",
+ "咽",
+ "咾",
+ "咿",
+ "哀",
+ "品",
+ "哂",
+ "哃",
+ "哄",
+ "哆",
+ "哇",
+ "哈",
+ "哉",
+ "哋",
+ "哌",
+ "响",
+ "哎",
+ "哏",
+ "哐",
+ "哑",
+ "哒",
+ "哓",
+ "哔",
+ "哕",
+ "哖",
+ "哗",
+ "哘",
+ "哙",
+ "哚",
+ "哜",
+ "哝",
+ "哞",
+ "哟",
+ "哠",
+ "員",
+ "哥",
+ "哦",
+ "哧",
+ "哨",
+ "哩",
+ "哪",
+ "哭",
+ "哮",
+ "哲",
+ "哺",
+ "哼",
+ "哽",
+ "唁",
+ "唄",
+ "唆",
+ "唇",
+ "唉",
+ "唏",
+ "唐",
+ "唑",
+ "唔",
+ "唖",
+ "唛",
+ "唞",
+ "唠",
+ "唢",
+ "唣",
+ "唤",
+ "唧",
+ "唪",
+ "唬",
+ "售",
+ "唯",
+ "唰",
+ "唱",
+ "唳",
+ "唵",
+ "唷",
+ "唸",
+ "唻",
+ "唼",
+ "唾",
+ "唿",
+ "啀",
+ "啁",
+ "啂",
+ "啃",
+ "啄",
+ "商",
+ "啉",
+ "啊",
+ "啋",
+ "問",
+ "啐",
+ "啓",
+ "啕",
+ "啖",
+ "啜",
+ "啞",
+ "啟",
+ "啡",
+ "啤",
+ "啥",
+ "啦",
+ "啧",
+ "啩",
+ "啪",
+ "啫",
+ "啬",
+ "啭",
+ "啮",
+ "啯",
+ "啰",
+ "啱",
+ "啲",
+ "啵",
+ "啶",
+ "啷",
+ "啸",
+ "啻",
+ "啼",
+ "啾",
+ "喀",
+ "喁",
+ "喂",
+ "喃",
+ "善",
+ "喆",
+ "喇",
+ "喈",
+ "喉",
+ "喊",
+ "喋",
+ "喎",
+ "喏",
+ "喐",
+ "喑",
+ "喒",
+ "喓",
+ "喔",
+ "喘",
+ "喙",
+ "喚",
+ "喛",
+ "喜",
+ "喝",
+ "喟",
+ "喤",
+ "喧",
+ "喨",
+ "喩",
+ "喪",
+ "喫",
+ "喬",
+ "單",
+ "喰",
+ "喱",
+ "喲",
+ "喳",
+ "喵",
+ "営",
+ "喷",
+ "喹",
+ "喺",
+ "喻",
+ "喽",
+ "喾",
+ "嗄",
+ "嗅",
+ "嗆",
+ "嗇",
+ "嗉",
+ "嗌",
+ "嗍",
+ "嗎",
+ "嗐",
+ "嗑",
+ "嗒",
+ "嗓",
+ "嗔",
+ "嗖",
+ "嗙",
+ "嗚",
+ "嗛",
+ "嗜",
+ "嗝",
+ "嗞",
+ "嗟",
+ "嗡",
+ "嗣",
+ "嗤",
+ "嗥",
+ "嗦",
+ "嗨",
+ "嗪",
+ "嗫",
+ "嗬",
+ "嗮",
+ "嗯",
+ "嗰",
+ "嗱",
+ "嗲",
+ "嗳",
+ "嗵",
+ "嗶",
+ "嗷",
+ "嗻",
+ "嗽",
+ "嗾",
+ "嘀",
+ "嘁",
+ "嘅",
+ "嘆",
+ "嘈",
+ "嘉",
+ "嘌",
+ "嘎",
+ "嘏",
+ "嘔",
+ "嘖",
+ "嘗",
+ "嘘",
+ "嘚",
+ "嘛",
+ "嘞",
+ "嘟",
+ "嘡",
+ "嘢",
+ "嘣",
+ "嘤",
+ "嘥",
+ "嘧",
+ "嘩",
+ "嘬",
+ "嘭",
+ "嘯",
+ "嘰",
+ "嘱",
+ "嘲",
+ "嘴",
+ "嘶",
+ "嘸",
+ "嘹",
+ "嘻",
+ "嘿",
+ "噂",
+ "噃",
+ "噌",
+ "噍",
+ "噎",
+ "噓",
+ "噔",
+ "噗",
+ "噘",
+ "噙",
+ "噛",
+ "噜",
+ "噠",
+ "噢",
+ "噤",
+ "器",
+ "噩",
+ "噪",
+ "噫",
+ "噬",
+ "噱",
+ "噴",
+ "噶",
+ "噸",
+ "噹",
+ "噺",
+ "噻",
+ "噼",
+ "嚀",
+ "嚅",
+ "嚆",
+ "嚇",
+ "嚊",
+ "嚎",
+ "嚏",
+ "嚐",
+ "嚒",
+ "嚓",
+ "嚔",
+ "嚕",
+ "嚗",
+ "嚜",
+ "嚟",
+ "嚠",
+ "嚢",
+ "嚣",
+ "嚥",
+ "嚨",
+ "嚩",
+ "嚭",
+ "嚮",
+ "嚯",
+ "嚴",
+ "嚶",
+ "嚷",
+ "嚼",
+ "囀",
+ "囁",
+ "囂",
+ "囃",
+ "囈",
+ "囉",
+ "囊",
+ "囍",
+ "囎",
+ "囑",
+ "囔",
+ "囖",
+ "囗",
+ "囚",
+ "四",
+ "囝",
+ "回",
+ "囟",
+ "因",
+ "囡",
+ "团",
+ "団",
+ "囤",
+ "囧",
+ "囨",
+ "囫",
+ "园",
+ "囮",
+ "囯",
+ "困",
+ "囱",
+ "囲",
+ "図",
+ "围",
+ "囵",
+ "囷",
+ "囹",
+ "固",
+ "国",
+ "图",
+ "囿",
+ "圀",
+ "圃",
+ "圄",
+ "圆",
+ "圈",
+ "圉",
+ "圊",
+ "國",
+ "圍",
+ "圏",
+ "園",
+ "圓",
+ "圖",
+ "團",
+ "圜",
+ "土",
+ "圣",
+ "圦",
+ "圧",
+ "在",
+ "圩",
+ "圪",
+ "圬",
+ "圭",
+ "圮",
+ "圯",
+ "地",
+ "圳",
+ "圷",
+ "圹",
+ "场",
+ "圻",
+ "圾",
+ "址",
+ "坂",
+ "均",
+ "坊",
+ "坍",
+ "坎",
+ "坏",
+ "坐",
+ "坑",
+ "坒",
+ "块",
+ "坚",
+ "坛",
+ "坜",
+ "坝",
+ "坞",
+ "坟",
+ "坠",
+ "坡",
+ "坤",
+ "坦",
+ "坨",
+ "坩",
+ "坪",
+ "坭",
+ "坮",
+ "坯",
+ "坳",
+ "坷",
+ "坻",
+ "坼",
+ "垂",
+ "垃",
+ "垄",
+ "垅",
+ "垆",
+ "垇",
+ "垈",
+ "型",
+ "垌",
+ "垍",
+ "垒",
+ "垓",
+ "垕",
+ "垗",
+ "垚",
+ "垛",
+ "垝",
+ "垠",
+ "垡",
+ "垢",
+ "垣",
+ "垤",
+ "垦",
+ "垧",
+ "垩",
+ "垪",
+ "垫",
+ "垭",
+ "垮",
+ "垯",
+ "垰",
+ "垱",
+ "垳",
+ "垴",
+ "垵",
+ "垸",
+ "埀",
+ "埂",
+ "埃",
+ "埆",
+ "埇",
+ "埋",
+ "埌",
+ "城",
+ "埏",
+ "埒",
+ "埓",
+ "埔",
+ "埕",
+ "埖",
+ "埗",
+ "埙",
+ "埚",
+ "埜",
+ "埝",
+ "域",
+ "埠",
+ "埣",
+ "埤",
+ "埪",
+ "埭",
+ "埲",
+ "埴",
+ "埵",
+ "執",
+ "埸",
+ "培",
+ "基",
+ "埼",
+ "埽",
+ "堀",
+ "堂",
+ "堃",
+ "堅",
+ "堆",
+ "堇",
+ "堊",
+ "堋",
+ "堌",
+ "堍",
+ "堎",
+ "堐",
+ "堑",
+ "堕",
+ "堙",
+ "堝",
+ "堞",
+ "堠",
+ "堡",
+ "堢",
+ "堤",
+ "堨",
+ "堪",
+ "堯",
+ "堰",
+ "報",
+ "場",
+ "堵",
+ "堺",
+ "堼",
+ "塀",
+ "塁",
+ "塄",
+ "塊",
+ "塋",
+ "塌",
+ "塍",
+ "塑",
+ "塒",
+ "塔",
+ "塗",
+ "塘",
+ "塙",
+ "塚",
+ "塞",
+ "塢",
+ "塩",
+ "填",
+ "塬",
+ "塲",
+ "塵",
+ "塹",
+ "塽",
+ "塾",
+ "墀",
+ "墁",
+ "境",
+ "墅",
+ "墉",
+ "墊",
+ "墎",
+ "墒",
+ "墓",
+ "墕",
+ "増",
+ "墙",
+ "墚",
+ "墜",
+ "增",
+ "墟",
+ "墡",
+ "墨",
+ "墩",
+ "墫",
+ "墮",
+ "墳",
+ "墹",
+ "墺",
+ "墻",
+ "墼",
+ "墾",
+ "壁",
+ "壅",
+ "壇",
+ "壊",
+ "壌",
+ "壑",
+ "壓",
+ "壕",
+ "壗",
+ "壘",
+ "壜",
+ "壞",
+ "壟",
+ "壤",
+ "壩",
+ "士",
+ "壬",
+ "壮",
+ "壯",
+ "声",
+ "壱",
+ "売",
+ "壳",
+ "壶",
+ "壷",
+ "壸",
+ "壹",
+ "壺",
+ "壻",
+ "壽",
+ "处",
+ "备",
+ "変",
+ "夊",
+ "夌",
+ "复",
+ "夏",
+ "夐",
+ "夔",
+ "夕",
+ "外",
+ "夙",
+ "多",
+ "夛",
+ "夜",
+ "够",
+ "夠",
+ "夢",
+ "夤",
+ "夥",
+ "大",
+ "天",
+ "太",
+ "夫",
+ "夬",
+ "夭",
+ "央",
+ "夯",
+ "失",
+ "头",
+ "夷",
+ "夸",
+ "夹",
+ "夺",
+ "夼",
+ "夾",
+ "奁",
+ "奂",
+ "奄",
+ "奇",
+ "奈",
+ "奉",
+ "奋",
+ "奌",
+ "奎",
+ "奏",
+ "奐",
+ "契",
+ "奔",
+ "奕",
+ "奖",
+ "套",
+ "奘",
+ "奚",
+ "奠",
+ "奢",
+ "奥",
+ "奧",
+ "奨",
+ "奪",
+ "奬",
+ "奭",
+ "奮",
+ "女",
+ "奴",
+ "奶",
+ "奸",
+ "她",
+ "好",
+ "妁",
+ "如",
+ "妃",
+ "妄",
+ "妆",
+ "妇",
+ "妈",
+ "妊",
+ "妍",
+ "妒",
+ "妓",
+ "妖",
+ "妗",
+ "妙",
+ "妝",
+ "妞",
+ "妣",
+ "妤",
+ "妥",
+ "妧",
+ "妨",
+ "妩",
+ "妪",
+ "妫",
+ "妬",
+ "妮",
+ "妯",
+ "妱",
+ "妲",
+ "妹",
+ "妺",
+ "妻",
+ "妽",
+ "妾",
+ "姆",
+ "姉",
+ "姊",
+ "始",
+ "姍",
+ "姐",
+ "姑",
+ "姒",
+ "姓",
+ "委",
+ "姗",
+ "姘",
+ "姚",
+ "姜",
+ "姝",
+ "姣",
+ "姤",
+ "姥",
+ "姦",
+ "姨",
+ "姩",
+ "姪",
+ "姫",
+ "姬",
+ "姮",
+ "姶",
+ "姸",
+ "姹",
+ "姺",
+ "姻",
+ "姿",
+ "威",
+ "娃",
+ "娄",
+ "娅",
+ "娆",
+ "娇",
+ "娈",
+ "娉",
+ "娌",
+ "娑",
+ "娓",
+ "娘",
+ "娚",
+ "娛",
+ "娜",
+ "娟",
+ "娠",
+ "娡",
+ "娣",
+ "娥",
+ "娩",
+ "娯",
+ "娱",
+ "娲",
+ "娴",
+ "娶",
+ "娼",
+ "娿",
+ "婀",
+ "婁",
+ "婄",
+ "婆",
+ "婉",
+ "婊",
+ "婌",
+ "婕",
+ "婚",
+ "婢",
+ "婦",
+ "婧",
+ "婪",
+ "婬",
+ "婴",
+ "婵",
+ "婶",
+ "婷",
+ "婺",
+ "婿",
+ "媒",
+ "媖",
+ "媚",
+ "媛",
+ "媜",
+ "媞",
+ "媪",
+ "媱",
+ "媲",
+ "媳",
+ "媵",
+ "媼",
+ "媽",
+ "媾",
+ "嫁",
+ "嫂",
+ "嫄",
+ "嫉",
+ "嫋",
+ "嫌",
+ "嫒",
+ "嫔",
+ "嫖",
+ "嫗",
+ "嫘",
+ "嫚",
+ "嫡",
+ "嫣",
+ "嫤",
+ "嫦",
+ "嫩",
+ "嫪",
+ "嫫",
+ "嫰",
+ "嫱",
+ "嫲",
+ "嫵",
+ "嫻",
+ "嬅",
+ "嬉",
+ "嬋",
+ "嬌",
+ "嬖",
+ "嬗",
+ "嬛",
+ "嬢",
+ "嬥",
+ "嬪",
+ "嬬",
+ "嬰",
+ "嬲",
+ "嬴",
+ "嬶",
+ "嬷",
+ "嬸",
+ "孀",
+ "孃",
+ "子",
+ "孑",
+ "孓",
+ "孔",
+ "孕",
+ "孖",
+ "字",
+ "存",
+ "孙",
+ "孚",
+ "孛",
+ "孜",
+ "孝",
+ "孟",
+ "孢",
+ "季",
+ "孤",
+ "孥",
+ "学",
+ "孩",
+ "孪",
+ "孫",
+ "孬",
+ "孭",
+ "孰",
+ "孱",
+ "孳",
+ "孵",
+ "學",
+ "孺",
+ "孽",
+ "宁",
+ "它",
+ "宄",
+ "宅",
+ "宇",
+ "守",
+ "安",
+ "宋",
+ "完",
+ "宍",
+ "宏",
+ "宓",
+ "宕",
+ "宗",
+ "官",
+ "宙",
+ "定",
+ "宛",
+ "宜",
+ "宝",
+ "实",
+ "実",
+ "宠",
+ "审",
+ "客",
+ "宣",
+ "室",
+ "宥",
+ "宦",
+ "宪",
+ "宫",
+ "宮",
+ "宰",
+ "害",
+ "宴",
+ "宵",
+ "家",
+ "宸",
+ "容",
+ "宽",
+ "宾",
+ "宿",
+ "寂",
+ "寄",
+ "寅",
+ "密",
+ "寇",
+ "富",
+ "寐",
+ "寒",
+ "寓",
+ "寔",
+ "寕",
+ "寖",
+ "寛",
+ "寝",
+ "寞",
+ "察",
+ "寠",
+ "寡",
+ "寢",
+ "寤",
+ "寥",
+ "實",
+ "寧",
+ "寨",
+ "審",
+ "寫",
+ "寬",
+ "寮",
+ "寰",
+ "寳",
+ "寵",
+ "寶",
+ "寸",
+ "对",
+ "寺",
+ "寻",
+ "导",
+ "対",
+ "寿",
+ "封",
+ "専",
+ "射",
+ "尅",
+ "将",
+ "將",
+ "專",
+ "尉",
+ "尊",
+ "尋",
+ "對",
+ "導",
+ "小",
+ "少",
+ "尓",
+ "尔",
+ "尕",
+ "尖",
+ "尘",
+ "尙",
+ "尚",
+ "尝",
+ "尞",
+ "尠",
+ "尡",
+ "尢",
+ "尤",
+ "尥",
+ "尧",
+ "尨",
+ "尪",
+ "尬",
+ "尭",
+ "尰",
+ "就",
+ "尴",
+ "尷",
+ "尸",
+ "尹",
+ "尺",
+ "尻",
+ "尼",
+ "尽",
+ "尾",
+ "尿",
+ "局",
+ "屁",
+ "层",
+ "屄",
+ "居",
+ "屆",
+ "屈",
+ "屉",
+ "届",
+ "屋",
+ "屌",
+ "屍",
+ "屎",
+ "屏",
+ "屐",
+ "屑",
+ "屓",
+ "展",
+ "屘",
+ "屙",
+ "屜",
+ "属",
+ "屠",
+ "屡",
+ "屢",
+ "屣",
+ "層",
+ "履",
+ "屦",
+ "屬",
+ "屯",
+ "山",
+ "屹",
+ "屺",
+ "屿",
+ "岀",
+ "岁",
+ "岂",
+ "岈",
+ "岌",
+ "岍",
+ "岐",
+ "岑",
+ "岔",
+ "岕",
+ "岖",
+ "岗",
+ "岘",
+ "岙",
+ "岚",
+ "岛",
+ "岜",
+ "岞",
+ "岡",
+ "岢",
+ "岨",
+ "岩",
+ "岫",
+ "岬",
+ "岭",
+ "岱",
+ "岳",
+ "岵",
+ "岷",
+ "岸",
+ "岻",
+ "岼",
+ "岽",
+ "岿",
+ "峁",
+ "峄",
+ "峅",
+ "峇",
+ "峋",
+ "峒",
+ "峙",
+ "峠",
+ "峡",
+ "峣",
+ "峤",
+ "峥",
+ "峦",
+ "峨",
+ "峪",
+ "峭",
+ "峯",
+ "峰",
+ "島",
+ "峻",
+ "峽",
+ "崂",
+ "崃",
+ "崆",
+ "崇",
+ "崋",
+ "崎",
+ "崐",
+ "崑",
+ "崒",
+ "崔",
+ "崕",
+ "崖",
+ "崗",
+ "崙",
+ "崚",
+ "崛",
+ "崞",
+ "崟",
+ "崢",
+ "崤",
+ "崦",
+ "崧",
+ "崩",
+ "崭",
+ "崮",
+ "崴",
+ "崽",
+ "崾",
+ "嵂",
+ "嵇",
+ "嵊",
+ "嵋",
+ "嵌",
+ "嵎",
+ "嵐",
+ "嵒",
+ "嵖",
+ "嵘",
+ "嵛",
+ "嵜",
+ "嵨",
+ "嵩",
+ "嵪",
+ "嵫",
+ "嵬",
+ "嵯",
+ "嵴",
+ "嶂",
+ "嶃",
+ "嶄",
+ "嶇",
+ "嶋",
+ "嶌",
+ "嶓",
+ "嶖",
+ "嶙",
+ "嶝",
+ "嶬",
+ "嶮",
+ "嶷",
+ "嶺",
+ "嶼",
+ "嶽",
+ "巂",
+ "巅",
+ "巇",
+ "巉",
+ "巌",
+ "巍",
+ "巒",
+ "巓",
+ "巖",
+ "川",
+ "州",
+ "巡",
+ "巢",
+ "巣",
+ "工",
+ "左",
+ "巧",
+ "巨",
+ "巩",
+ "巫",
+ "差",
+ "巯",
+ "己",
+ "已",
+ "巳",
+ "巴",
+ "巵",
+ "巷",
+ "巺",
+ "巻",
+ "巽",
+ "巾",
+ "巿",
+ "帀",
+ "币",
+ "市",
+ "布",
+ "帅",
+ "帆",
+ "师",
+ "希",
+ "帏",
+ "帐",
+ "帑",
+ "帔",
+ "帕",
+ "帖",
+ "帘",
+ "帙",
+ "帚",
+ "帛",
+ "帜",
+ "帝",
+ "帥",
+ "带",
+ "帧",
+ "師",
+ "席",
+ "帮",
+ "帯",
+ "帰",
+ "帳",
+ "帶",
+ "帷",
+ "常",
+ "帻",
+ "帼",
+ "帽",
+ "幀",
+ "幂",
+ "幄",
+ "幅",
+ "幇",
+ "幌",
+ "幔",
+ "幕",
+ "幗",
+ "幛",
+ "幟",
+ "幡",
+ "幢",
+ "幣",
+ "幫",
+ "干",
+ "平",
+ "年",
+ "并",
+ "幷",
+ "幸",
+ "幹",
+ "幺",
+ "幻",
+ "幼",
+ "幽",
+ "幾",
+ "广",
+ "庁",
+ "広",
+ "庄",
+ "庅",
+ "庆",
+ "庇",
+ "床",
+ "序",
+ "庐",
+ "庑",
+ "库",
+ "应",
+ "底",
+ "庖",
+ "店",
+ "庙",
+ "庚",
+ "府",
+ "庞",
+ "废",
+ "庠",
+ "度",
+ "座",
+ "庫",
+ "庭",
+ "庵",
+ "庶",
+ "康",
+ "庸",
+ "庹",
+ "庾",
+ "廁",
+ "廂",
+ "廃",
+ "廆",
+ "廈",
+ "廉",
+ "廊",
+ "廋",
+ "廑",
+ "廓",
+ "廖",
+ "廚",
+ "廛",
+ "廝",
+ "廟",
+ "廠",
+ "廢",
+ "廣",
+ "廨",
+ "廪",
+ "廬",
+ "廳",
+ "廴",
+ "延",
+ "廷",
+ "建",
+ "廻",
+ "廼",
+ "廿",
+ "开",
+ "弁",
+ "异",
+ "弃",
+ "弄",
+ "弇",
+ "弈",
+ "弉",
+ "弊",
+ "弋",
+ "式",
+ "弐",
+ "弑",
+ "弓",
+ "弔",
+ "引",
+ "弖",
+ "弗",
+ "弘",
+ "弛",
+ "弟",
+ "张",
+ "弢",
+ "弥",
+ "弦",
+ "弧",
+ "弨",
+ "弩",
+ "弭",
+ "弯",
+ "弱",
+ "張",
+ "強",
+ "弹",
+ "强",
+ "弼",
+ "弾",
+ "彀",
+ "彅",
+ "彆",
+ "彈",
+ "彊",
+ "彌",
+ "彎",
+ "彑",
+ "归",
+ "当",
+ "录",
+ "彖",
+ "彗",
+ "彘",
+ "彙",
+ "彝",
+ "彟",
+ "彡",
+ "形",
+ "彤",
+ "彥",
+ "彦",
+ "彧",
+ "彩",
+ "彪",
+ "彫",
+ "彬",
+ "彭",
+ "彰",
+ "影",
+ "彳",
+ "彷",
+ "役",
+ "彺",
+ "彻",
+ "彼",
+ "彿",
+ "往",
+ "征",
+ "徂",
+ "徃",
+ "径",
+ "待",
+ "徇",
+ "很",
+ "徉",
+ "徊",
+ "律",
+ "後",
+ "徍",
+ "徐",
+ "徑",
+ "徒",
+ "従",
+ "徕",
+ "得",
+ "徘",
+ "徙",
+ "徜",
+ "從",
+ "徠",
+ "御",
+ "徨",
+ "復",
+ "循",
+ "徬",
+ "徭",
+ "微",
+ "徳",
+ "徴",
+ "徵",
+ "德",
+ "徹",
+ "徼",
+ "徽",
+ "心",
+ "忄",
+ "必",
+ "忆",
+ "忋",
+ "忌",
+ "忍",
+ "忏",
+ "忐",
+ "忑",
+ "忒",
+ "忖",
+ "志",
+ "忘",
+ "忙",
+ "応",
+ "忝",
+ "忠",
+ "忡",
+ "忤",
+ "忧",
+ "忪",
+ "快",
+ "忰",
+ "忱",
+ "念",
+ "忸",
+ "忻",
+ "忽",
+ "忾",
+ "忿",
+ "怀",
+ "态",
+ "怂",
+ "怃",
+ "怄",
+ "怅",
+ "怆",
+ "怍",
+ "怎",
+ "怏",
+ "怒",
+ "怔",
+ "怕",
+ "怖",
+ "怗",
+ "怙",
+ "怛",
+ "怜",
+ "思",
+ "怠",
+ "怡",
+ "急",
+ "怦",
+ "性",
+ "怨",
+ "怩",
+ "怪",
+ "怫",
+ "怯",
+ "怱",
+ "怵",
+ "怹",
+ "总",
+ "怼",
+ "怿",
+ "恁",
+ "恂",
+ "恃",
+ "恆",
+ "恋",
+ "恍",
+ "恐",
+ "恒",
+ "恓",
+ "恕",
+ "恙",
+ "恚",
+ "恟",
+ "恢",
+ "恣",
+ "恤",
+ "恥",
+ "恨",
+ "恩",
+ "恪",
+ "恫",
+ "恬",
+ "恭",
+ "息",
+ "恰",
+ "恳",
+ "恵",
+ "恶",
+ "恸",
+ "恹",
+ "恺",
+ "恻",
+ "恼",
+ "恽",
+ "恿",
+ "悃",
+ "悄",
+ "悅",
+ "悆",
+ "悉",
+ "悋",
+ "悌",
+ "悍",
+ "悒",
+ "悔",
+ "悕",
+ "悖",
+ "悚",
+ "悛",
+ "悝",
+ "悟",
+ "悠",
+ "患",
+ "悦",
+ "悧",
+ "您",
+ "悩",
+ "悪",
+ "悫",
+ "悬",
+ "悭",
+ "悯",
+ "悱",
+ "悲",
+ "悳",
+ "悴",
+ "悵",
+ "悶",
+ "悸",
+ "悻",
+ "悼",
+ "悽",
+ "情",
+ "惆",
+ "惇",
+ "惊",
+ "惋",
+ "惎",
+ "惑",
+ "惕",
+ "惘",
+ "惙",
+ "惚",
+ "惜",
+ "惟",
+ "惠",
+ "惡",
+ "惣",
+ "惦",
+ "惧",
+ "惨",
+ "惩",
+ "惫",
+ "惬",
+ "惭",
+ "惮",
+ "惯",
+ "惰",
+ "惱",
+ "想",
+ "惴",
+ "惶",
+ "惹",
+ "惺",
+ "惻",
+ "愀",
+ "愁",
+ "愆",
+ "愇",
+ "愈",
+ "愉",
+ "愊",
+ "愍",
+ "愎",
+ "意",
+ "愔",
+ "愕",
+ "愚",
+ "愛",
+ "感",
+ "愠",
+ "愣",
+ "愤",
+ "愦",
+ "愧",
+ "愫",
+ "愬",
+ "愴",
+ "愷",
+ "愼",
+ "愾",
+ "愿",
+ "慂",
+ "慄",
+ "慆",
+ "慇",
+ "慈",
+ "慊",
+ "態",
+ "慌",
+ "慎",
+ "慑",
+ "慓",
+ "慕",
+ "慘",
+ "慙",
+ "慚",
+ "慜",
+ "慝",
+ "慟",
+ "慢",
+ "慣",
+ "慥",
+ "慧",
+ "慨",
+ "慫",
+ "慮",
+ "慰",
+ "慳",
+ "慴",
+ "慵",
+ "慶",
+ "慷",
+ "慾",
+ "憂",
+ "憊",
+ "憋",
+ "憍",
+ "憎",
+ "憐",
+ "憑",
+ "憔",
+ "憖",
+ "憙",
+ "憚",
+ "憤",
+ "憧",
+ "憨",
+ "憩",
+ "憫",
+ "憬",
+ "憮",
+ "憲",
+ "憶",
+ "憷",
+ "憺",
+ "憾",
+ "懂",
+ "懃",
+ "懆",
+ "懇",
+ "懈",
+ "應",
+ "懊",
+ "懋",
+ "懐",
+ "懑",
+ "懒",
+ "懣",
+ "懦",
+ "懲",
+ "懵",
+ "懶",
+ "懷",
+ "懸",
+ "懺",
+ "懼",
+ "懾",
+ "懿",
+ "戀",
+ "戆",
+ "戇",
+ "戈",
+ "戊",
+ "戌",
+ "戍",
+ "戎",
+ "戏",
+ "成",
+ "我",
+ "戒",
+ "戔",
+ "戕",
+ "或",
+ "戗",
+ "战",
+ "戚",
+ "戛",
+ "戞",
+ "戟",
+ "戡",
+ "戢",
+ "戥",
+ "戦",
+ "截",
+ "戬",
+ "戮",
+ "戯",
+ "戰",
+ "戲",
+ "戳",
+ "戴",
+ "戶",
+ "户",
+ "戸",
+ "戻",
+ "戽",
+ "戾",
+ "房",
+ "所",
+ "扁",
+ "扃",
+ "扆",
+ "扇",
+ "扈",
+ "扉",
+ "手",
+ "才",
+ "扎",
+ "扐",
+ "扑",
+ "扒",
+ "打",
+ "扔",
+ "払",
+ "托",
+ "扛",
+ "扞",
+ "扠",
+ "扣",
+ "扤",
+ "扥",
+ "扦",
+ "执",
+ "扨",
+ "扩",
+ "扪",
+ "扫",
+ "扬",
+ "扭",
+ "扮",
+ "扯",
+ "扰",
+ "扱",
+ "扳",
+ "扶",
+ "批",
+ "扼",
+ "找",
+ "承",
+ "技",
+ "抃",
+ "抄",
+ "抅",
+ "抉",
+ "把",
+ "抌",
+ "抑",
+ "抒",
+ "抓",
+ "抔",
+ "投",
+ "抖",
+ "抗",
+ "折",
+ "抚",
+ "抛",
+ "抜",
+ "択",
+ "抟",
+ "抠",
+ "抡",
+ "抢",
+ "护",
+ "报",
+ "抨",
+ "披",
+ "抬",
+ "抱",
+ "抵",
+ "抹",
+ "抻",
+ "押",
+ "抽",
+ "抾",
+ "抿",
+ "拂",
+ "拃",
+ "拄",
+ "担",
+ "拆",
+ "拇",
+ "拈",
+ "拉",
+ "拊",
+ "拋",
+ "拌",
+ "拍",
+ "拎",
+ "拐",
+ "拒",
+ "拓",
+ "拔",
+ "拖",
+ "拗",
+ "拘",
+ "拙",
+ "拚",
+ "招",
+ "拜",
+ "拝",
+ "拟",
+ "拠",
+ "拡",
+ "拢",
+ "拣",
+ "拤",
+ "拥",
+ "拦",
+ "拧",
+ "拨",
+ "择",
+ "括",
+ "拭",
+ "拮",
+ "拯",
+ "拱",
+ "拳",
+ "拴",
+ "拵",
+ "拶",
+ "拷",
+ "拼",
+ "拽",
+ "拾",
+ "拿",
+ "持",
+ "挂",
+ "指",
+ "挈",
+ "按",
+ "挌",
+ "挎",
+ "挑",
+ "挒",
+ "挖",
+ "挙",
+ "挚",
+ "挛",
+ "挝",
+ "挞",
+ "挟",
+ "挠",
+ "挡",
+ "挢",
+ "挣",
+ "挤",
+ "挥",
+ "挨",
+ "挪",
+ "挫",
+ "振",
+ "挲",
+ "挹",
+ "挺",
+ "挼",
+ "挽",
+ "挾",
+ "挿",
+ "捂",
+ "捅",
+ "捆",
+ "捉",
+ "捊",
+ "捋",
+ "捌",
+ "捍",
+ "捎",
+ "捏",
+ "捐",
+ "捕",
+ "捗",
+ "捜",
+ "捞",
+ "损",
+ "捡",
+ "换",
+ "捣",
+ "捧",
+ "捨",
+ "捩",
+ "捫",
+ "捭",
+ "据",
+ "捯",
+ "捱",
+ "捲",
+ "捶",
+ "捷",
+ "捺",
+ "捻",
+ "掀",
+ "掂",
+ "掃",
+ "掇",
+ "授",
+ "掉",
+ "掊",
+ "掌",
+ "掎",
+ "掏",
+ "掐",
+ "排",
+ "掕",
+ "掖",
+ "掘",
+ "掙",
+ "掛",
+ "掞",
+ "掟",
+ "掠",
+ "採",
+ "探",
+ "掣",
+ "接",
+ "控",
+ "推",
+ "掩",
+ "措",
+ "掬",
+ "掮",
+ "掰",
+ "掲",
+ "掳",
+ "掴",
+ "掷",
+ "掸",
+ "掹",
+ "掺",
+ "掻",
+ "掼",
+ "掾",
+ "揀",
+ "揃",
+ "揄",
+ "揆",
+ "揈",
+ "揉",
+ "揍",
+ "揎",
+ "描",
+ "提",
+ "插",
+ "揖",
+ "揚",
+ "換",
+ "揞",
+ "揠",
+ "握",
+ "揣",
+ "揩",
+ "揪",
+ "揭",
+ "揮",
+ "揲",
+ "援",
+ "揵",
+ "揶",
+ "揸",
+ "揺",
+ "揼",
+ "揽",
+ "揿",
+ "搀",
+ "搁",
+ "搂",
+ "搅",
+ "搆",
+ "搋",
+ "搌",
+ "損",
+ "搏",
+ "搐",
+ "搓",
+ "搔",
+ "搖",
+ "搗",
+ "搛",
+ "搜",
+ "搞",
+ "搠",
+ "搡",
+ "搢",
+ "搣",
+ "搦",
+ "搧",
+ "搨",
+ "搪",
+ "搬",
+ "搭",
+ "搴",
+ "搵",
+ "搶",
+ "搹",
+ "携",
+ "搽",
+ "搾",
+ "摁",
+ "摂",
+ "摄",
+ "摅",
+ "摆",
+ "摇",
+ "摈",
+ "摊",
+ "摐",
+ "摒",
+ "摔",
+ "摘",
+ "摛",
+ "摞",
+ "摟",
+ "摧",
+ "摩",
+ "摭",
+ "摯",
+ "摵",
+ "摸",
+ "摹",
+ "摺",
+ "摽",
+ "撂",
+ "撃",
+ "撄",
+ "撅",
+ "撇",
+ "撈",
+ "撐",
+ "撑",
+ "撒",
+ "撓",
+ "撕",
+ "撖",
+ "撙",
+ "撚",
+ "撞",
+ "撤",
+ "撥",
+ "撩",
+ "撫",
+ "撬",
+ "播",
+ "撮",
+ "撰",
+ "撲",
+ "撳",
+ "撴",
+ "撵",
+ "撷",
+ "撸",
+ "撹",
+ "撺",
+ "撻",
+ "撼",
+ "撿",
+ "擀",
+ "擁",
+ "擂",
+ "擅",
+ "擇",
+ "擊",
+ "擋",
+ "操",
+ "擎",
+ "擐",
+ "擒",
+ "擔",
+ "擗",
+ "擘",
+ "據",
+ "擞",
+ "擠",
+ "擡",
+ "擢",
+ "擣",
+ "擤",
+ "擦",
+ "擧",
+ "擬",
+ "擯",
+ "擰",
+ "擱",
+ "擲",
+ "擳",
+ "擴",
+ "擶",
+ "擺",
+ "擻",
+ "擽",
+ "擾",
+ "攀",
+ "攆",
+ "攉",
+ "攏",
+ "攒",
+ "攔",
+ "攘",
+ "攙",
+ "攜",
+ "攝",
+ "攞",
+ "攣",
+ "攤",
+ "攥",
+ "攪",
+ "攫",
+ "攬",
+ "攮",
+ "支",
+ "攰",
+ "攴",
+ "攵",
+ "收",
+ "攷",
+ "攸",
+ "改",
+ "攻",
+ "放",
+ "政",
+ "故",
+ "效",
+ "敉",
+ "敌",
+ "敍",
+ "敏",
+ "救",
+ "敕",
+ "敖",
+ "敗",
+ "敘",
+ "教",
+ "敛",
+ "敝",
+ "敞",
+ "敢",
+ "散",
+ "敦",
+ "敫",
+ "敬",
+ "数",
+ "敲",
+ "整",
+ "敵",
+ "敷",
+ "數",
+ "斁",
+ "斂",
+ "斃",
+ "文",
+ "斉",
+ "斋",
+ "斌",
+ "斎",
+ "斐",
+ "斑",
+ "斓",
+ "斕",
+ "斗",
+ "料",
+ "斛",
+ "斜",
+ "斝",
+ "斟",
+ "斡",
+ "斤",
+ "斥",
+ "斧",
+ "斩",
+ "斫",
+ "斬",
+ "断",
+ "斯",
+ "新",
+ "斷",
+ "方",
+ "於",
+ "施",
+ "斿",
+ "旁",
+ "旃",
+ "旄",
+ "旅",
+ "旆",
+ "旉",
+ "旋",
+ "旌",
+ "旎",
+ "族",
+ "旒",
+ "旖",
+ "旗",
+ "旛",
+ "无",
+ "既",
+ "日",
+ "旦",
+ "旧",
+ "旨",
+ "早",
+ "旬",
+ "旭",
+ "旮",
+ "旯",
+ "旰",
+ "旱",
+ "旳",
+ "时",
+ "旷",
+ "旸",
+ "旺",
+ "旻",
+ "旼",
+ "昀",
+ "昂",
+ "昃",
+ "昆",
+ "昇",
+ "昉",
+ "昊",
+ "昌",
+ "明",
+ "昏",
+ "易",
+ "昔",
+ "昕",
+ "昙",
+ "昚",
+ "昝",
+ "昞",
+ "星",
+ "映",
+ "春",
+ "昧",
+ "昨",
+ "昭",
+ "是",
+ "昱",
+ "昴",
+ "昵",
+ "昶",
+ "昺",
+ "昼",
+ "显",
+ "晁",
+ "時",
+ "晃",
+ "晄",
+ "晉",
+ "晋",
+ "晌",
+ "晏",
+ "晒",
+ "晓",
+ "晔",
+ "晕",
+ "晖",
+ "晗",
+ "晚",
+ "晝",
+ "晞",
+ "晟",
+ "晡",
+ "晢",
+ "晤",
+ "晥",
+ "晦",
+ "晧",
+ "晨",
+ "晩",
+ "晬",
+ "普",
+ "景",
+ "晰",
+ "晳",
+ "晴",
+ "晶",
+ "晷",
+ "智",
+ "晻",
+ "晾",
+ "暁",
+ "暂",
+ "暄",
+ "暇",
+ "暈",
+ "暉",
+ "暌",
+ "暍",
+ "暎",
+ "暑",
+ "暖",
+ "暗",
+ "暘",
+ "暝",
+ "暢",
+ "暦",
+ "暧",
+ "暨",
+ "暫",
+ "暮",
+ "暲",
+ "暴",
+ "暹",
+ "暻",
+ "暼",
+ "暾",
+ "曄",
+ "曆",
+ "曇",
+ "曈",
+ "曉",
+ "曌",
+ "曖",
+ "曙",
+ "曚",
+ "曛",
+ "曜",
+ "曝",
+ "曠",
+ "曡",
+ "曦",
+ "曩",
+ "曬",
+ "曰",
+ "曱",
+ "曲",
+ "曳",
+ "更",
+ "曵",
+ "曷",
+ "書",
+ "曹",
+ "曺",
+ "曼",
+ "曽",
+ "曾",
+ "替",
+ "最",
+ "會",
+ "月",
+ "有",
+ "朊",
+ "朋",
+ "服",
+ "朏",
+ "朐",
+ "朓",
+ "朔",
+ "朕",
+ "朗",
+ "望",
+ "朝",
+ "期",
+ "朦",
+ "朧",
+ "木",
+ "未",
+ "末",
+ "本",
+ "札",
+ "朮",
+ "术",
+ "朱",
+ "朴",
+ "朵",
+ "朶",
+ "朸",
+ "机",
+ "朽",
+ "朾",
+ "杀",
+ "杁",
+ "杂",
+ "权",
+ "杆",
+ "杈",
+ "杉",
+ "杌",
+ "李",
+ "杏",
+ "材",
+ "村",
+ "杓",
+ "杖",
+ "杙",
+ "杜",
+ "杞",
+ "束",
+ "杠",
+ "条",
+ "杢",
+ "杣",
+ "杤",
+ "来",
+ "杨",
+ "杩",
+ "杪",
+ "杬",
+ "杭",
+ "杮",
+ "杯",
+ "杰",
+ "東",
+ "杲",
+ "杳",
+ "杵",
+ "杷",
+ "杻",
+ "杼",
+ "松",
+ "板",
+ "极",
+ "构",
+ "枅",
+ "枇",
+ "枉",
+ "枋",
+ "枌",
+ "枎",
+ "析",
+ "枓",
+ "枕",
+ "林",
+ "枘",
+ "枚",
+ "果",
+ "枝",
+ "枞",
+ "枠",
+ "枡",
+ "枢",
+ "枣",
+ "枥",
+ "枦",
+ "枧",
+ "枨",
+ "枪",
+ "枫",
+ "枭",
+ "枯",
+ "枰",
+ "枱",
+ "枲",
+ "枳",
+ "枴",
+ "架",
+ "枷",
+ "枸",
+ "枹",
+ "柀",
+ "柁",
+ "柃",
+ "柄",
+ "柇",
+ "柊",
+ "柏",
+ "某",
+ "柑",
+ "柒",
+ "染",
+ "柔",
+ "柘",
+ "柚",
+ "柜",
+ "柝",
+ "柞",
+ "柠",
+ "柢",
+ "柤",
+ "查",
+ "柧",
+ "柩",
+ "柬",
+ "柯",
+ "柰",
+ "柱",
+ "柳",
+ "柴",
+ "柵",
+ "柷",
+ "柸",
+ "柹",
+ "査",
+ "柽",
+ "柾",
+ "柿",
+ "栀",
+ "栂",
+ "栃",
+ "栄",
+ "栅",
+ "标",
+ "栈",
+ "栉",
+ "栊",
+ "栋",
+ "栌",
+ "栎",
+ "栏",
+ "树",
+ "栓",
+ "栖",
+ "栗",
+ "栘",
+ "栝",
+ "栞",
+ "栟",
+ "校",
+ "栢",
+ "栧",
+ "栩",
+ "株",
+ "栫",
+ "栬",
+ "栱",
+ "栲",
+ "栳",
+ "栴",
+ "样",
+ "核",
+ "根",
+ "栻",
+ "格",
+ "栽",
+ "栾",
+ "桀",
+ "桁",
+ "桂",
+ "桃",
+ "桄",
+ "桅",
+ "框",
+ "案",
+ "桉",
+ "桌",
+ "桎",
+ "桐",
+ "桑",
+ "桓",
+ "桔",
+ "桕",
+ "桖",
+ "桙",
+ "桜",
+ "桝",
+ "桟",
+ "桠",
+ "桡",
+ "桢",
+ "档",
+ "桤",
+ "桥",
+ "桦",
+ "桧",
+ "桨",
+ "桩",
+ "桫",
+ "桯",
+ "桴",
+ "桶",
+ "桷",
+ "桼",
+ "桾",
+ "桿",
+ "梁",
+ "梃",
+ "梅",
+ "梆",
+ "梈",
+ "梏",
+ "梓",
+ "梔",
+ "梗",
+ "梛",
+ "條",
+ "梟",
+ "梠",
+ "梡",
+ "梢",
+ "梣",
+ "梦",
+ "梧",
+ "梨",
+ "梪",
+ "梫",
+ "梭",
+ "梯",
+ "械",
+ "梱",
+ "梳",
+ "梵",
+ "梶",
+ "梹",
+ "梺",
+ "梻",
+ "梼",
+ "梿",
+ "检",
+ "棂",
+ "棄",
+ "棅",
+ "棈",
+ "棉",
+ "棊",
+ "棋",
+ "棍",
+ "棒",
+ "棔",
+ "棕",
+ "棗",
+ "棘",
+ "棚",
+ "棟",
+ "棠",
+ "棡",
+ "棣",
+ "棧",
+ "棨",
+ "棬",
+ "森",
+ "棯",
+ "棰",
+ "棱",
+ "棲",
+ "棵",
+ "棶",
+ "棷",
+ "棹",
+ "棺",
+ "棻",
+ "棼",
+ "椀",
+ "椁",
+ "椅",
+ "椈",
+ "椊",
+ "椋",
+ "椌",
+ "植",
+ "椎",
+ "椏",
+ "椐",
+ "椒",
+ "椙",
+ "椚",
+ "椛",
+ "検",
+ "椟",
+ "椡",
+ "椣",
+ "椤",
+ "椥",
+ "椨",
+ "椪",
+ "椭",
+ "椰",
+ "椴",
+ "椹",
+ "椽",
+ "椿",
+ "楀",
+ "楂",
+ "楉",
+ "楊",
+ "楓",
+ "楔",
+ "楕",
+ "楗",
+ "楙",
+ "楚",
+ "楜",
+ "楝",
+ "楞",
+ "楠",
+ "楡",
+ "楢",
+ "楣",
+ "楦",
+ "楪",
+ "楫",
+ "業",
+ "楮",
+ "楯",
+ "楱",
+ "楳",
+ "極",
+ "楷",
+ "楸",
+ "楹",
+ "楼",
+ "楽",
+ "楾",
+ "榁",
+ "概",
+ "榄",
+ "榆",
+ "榇",
+ "榈",
+ "榉",
+ "榊",
+ "榎",
+ "榑",
+ "榔",
+ "榕",
+ "榖",
+ "榘",
+ "榛",
+ "榜",
+ "榧",
+ "榨",
+ "榫",
+ "榭",
+ "榮",
+ "榲",
+ "榴",
+ "榷",
+ "榻",
+ "榼",
+ "榾",
+ "榿",
+ "槁",
+ "槃",
+ "槅",
+ "槇",
+ "槊",
+ "構",
+ "槌",
+ "槍",
+ "槎",
+ "槐",
+ "槓",
+ "槖",
+ "様",
+ "槙",
+ "槛",
+ "槟",
+ "槧",
+ "槨",
+ "槩",
+ "槫",
+ "槭",
+ "槲",
+ "槳",
+ "槻",
+ "槽",
+ "槿",
+ "樀",
+ "樁",
+ "樂",
+ "樅",
+ "樉",
+ "樊",
+ "樋",
+ "樑",
+ "樒",
+ "樓",
+ "樖",
+ "樗",
+ "樘",
+ "標",
+ "樛",
+ "樞",
+ "樟",
+ "模",
+ "樣",
+ "樨",
+ "権",
+ "横",
+ "樫",
+ "樮",
+ "樯",
+ "樱",
+ "樵",
+ "樸",
+ "樹",
+ "樺",
+ "樽",
+ "樾",
+ "橄",
+ "橅",
+ "橇",
+ "橈",
+ "橋",
+ "橐",
+ "橘",
+ "橙",
+ "橛",
+ "橞",
+ "機",
+ "橡",
+ "橢",
+ "橥",
+ "橦",
+ "橫",
+ "橱",
+ "橲",
+ "橹",
+ "橼",
+ "橿",
+ "檀",
+ "檄",
+ "檉",
+ "檍",
+ "檎",
+ "檐",
+ "檔",
+ "檗",
+ "檜",
+ "檞",
+ "檠",
+ "檢",
+ "檣",
+ "檩",
+ "檪",
+ "檫",
+ "檬",
+ "檮",
+ "檯",
+ "檳",
+ "檸",
+ "檻",
+ "檿",
+ "櫁",
+ "櫂",
+ "櫃",
+ "櫈",
+ "櫓",
+ "櫚",
+ "櫛",
+ "櫞",
+ "櫟",
+ "櫧",
+ "櫨",
+ "櫪",
+ "櫺",
+ "櫻",
+ "欄",
+ "欅",
+ "權",
+ "欒",
+ "欖",
+ "欝",
+ "欞",
+ "欠",
+ "次",
+ "欢",
+ "欣",
+ "欤",
+ "欧",
+ "欲",
+ "欷",
+ "欸",
+ "欹",
+ "欺",
+ "欻",
+ "欽",
+ "款",
+ "歀",
+ "歃",
+ "歆",
+ "歇",
+ "歉",
+ "歌",
+ "歎",
+ "歐",
+ "歓",
+ "歔",
+ "歘",
+ "歙",
+ "歡",
+ "止",
+ "正",
+ "此",
+ "步",
+ "武",
+ "歧",
+ "歩",
+ "歪",
+ "歭",
+ "歯",
+ "歲",
+ "歳",
+ "歴",
+ "歷",
+ "歸",
+ "歹",
+ "死",
+ "歼",
+ "歿",
+ "殁",
+ "殂",
+ "殃",
+ "殄",
+ "殆",
+ "殇",
+ "殉",
+ "殊",
+ "残",
+ "殍",
+ "殒",
+ "殓",
+ "殖",
+ "殘",
+ "殚",
+ "殛",
+ "殡",
+ "殪",
+ "殭",
+ "殮",
+ "殯",
+ "殲",
+ "殳",
+ "殴",
+ "段",
+ "殷",
+ "殺",
+ "殻",
+ "殼",
+ "殽",
+ "殿",
+ "毀",
+ "毁",
+ "毂",
+ "毅",
+ "毆",
+ "毋",
+ "母",
+ "毎",
+ "每",
+ "毐",
+ "毒",
+ "毓",
+ "比",
+ "毕",
+ "毖",
+ "毗",
+ "毘",
+ "毙",
+ "毛",
+ "毟",
+ "毡",
+ "毫",
+ "毬",
+ "毯",
+ "毳",
+ "毹",
+ "毽",
+ "氅",
+ "氆",
+ "氇",
+ "氈",
+ "氍",
+ "氏",
+ "氐",
+ "民",
+ "氓",
+ "气",
+ "氕",
+ "氖",
+ "気",
+ "氘",
+ "氙",
+ "氚",
+ "氛",
+ "氟",
+ "氡",
+ "氢",
+ "氣",
+ "氤",
+ "氦",
+ "氧",
+ "氨",
+ "氩",
+ "氪",
+ "氮",
+ "氯",
+ "氰",
+ "氲",
+ "水",
+ "氷",
+ "永",
+ "氹",
+ "氽",
+ "氾",
+ "汀",
+ "汁",
+ "求",
+ "汆",
+ "汇",
+ "汈",
+ "汉",
+ "汊",
+ "汎",
+ "汐",
+ "汔",
+ "汕",
+ "汗",
+ "汚",
+ "汛",
+ "汜",
+ "汝",
+ "汞",
+ "江",
+ "池",
+ "污",
+ "汤",
+ "汨",
+ "汩",
+ "汪",
+ "汭",
+ "汰",
+ "汲",
+ "汴",
+ "汵",
+ "汶",
+ "汹",
+ "決",
+ "汽",
+ "汾",
+ "沁",
+ "沂",
+ "沃",
+ "沄",
+ "沅",
+ "沆",
+ "沈",
+ "沉",
+ "沌",
+ "沏",
+ "沐",
+ "沒",
+ "沓",
+ "沔",
+ "沖",
+ "沙",
+ "沚",
+ "沛",
+ "沟",
+ "没",
+ "沢",
+ "沣",
+ "沤",
+ "沥",
+ "沦",
+ "沧",
+ "沨",
+ "沩",
+ "沪",
+ "沫",
+ "沭",
+ "沮",
+ "沱",
+ "河",
+ "沸",
+ "油",
+ "治",
+ "沼",
+ "沽",
+ "沾",
+ "沿",
+ "況",
+ "泃",
+ "泄",
+ "泅",
+ "泆",
+ "泉",
+ "泊",
+ "泌",
+ "泐",
+ "泒",
+ "泓",
+ "泔",
+ "法",
+ "泖",
+ "泗",
+ "泙",
+ "泚",
+ "泛",
+ "泞",
+ "泠",
+ "泡",
+ "波",
+ "泣",
+ "泥",
+ "注",
+ "泪",
+ "泫",
+ "泬",
+ "泮",
+ "泯",
+ "泰",
+ "泱",
+ "泳",
+ "泵",
+ "泷",
+ "泸",
+ "泺",
+ "泻",
+ "泼",
+ "泽",
+ "泾",
+ "洁",
+ "洄",
+ "洇",
+ "洋",
+ "洌",
+ "洎",
+ "洏",
+ "洑",
+ "洒",
+ "洗",
+ "洙",
+ "洛",
+ "洞",
+ "洟",
+ "洣",
+ "津",
+ "洧",
+ "洩",
+ "洪",
+ "洮",
+ "洱",
+ "洲",
+ "洳",
+ "洵",
+ "洶",
+ "洸",
+ "洹",
+ "洺",
+ "活",
+ "洼",
+ "洽",
+ "派",
+ "洿",
+ "流",
+ "浃",
+ "浄",
+ "浅",
+ "浆",
+ "浇",
+ "浈",
+ "浉",
+ "浊",
+ "测",
+ "浍",
+ "济",
+ "浏",
+ "浐",
+ "浑",
+ "浒",
+ "浓",
+ "浔",
+ "浙",
+ "浚",
+ "浛",
+ "浜",
+ "浞",
+ "浠",
+ "浣",
+ "浥",
+ "浦",
+ "浩",
+ "浪",
+ "浬",
+ "浮",
+ "浯",
+ "浴",
+ "海",
+ "浸",
+ "浹",
+ "涂",
+ "涅",
+ "消",
+ "涉",
+ "涌",
+ "涎",
+ "涑",
+ "涓",
+ "涔",
+ "涕",
+ "涖",
+ "涘",
+ "涙",
+ "涛",
+ "涜",
+ "涝",
+ "涞",
+ "涟",
+ "涠",
+ "涡",
+ "涣",
+ "涤",
+ "润",
+ "涧",
+ "涨",
+ "涩",
+ "涪",
+ "涮",
+ "涯",
+ "液",
+ "涵",
+ "涸",
+ "涼",
+ "涿",
+ "淀",
+ "淄",
+ "淅",
+ "淆",
+ "淇",
+ "淋",
+ "淌",
+ "淏",
+ "淑",
+ "淒",
+ "淖",
+ "淘",
+ "淙",
+ "淚",
+ "淜",
+ "淝",
+ "淞",
+ "淠",
+ "淡",
+ "淤",
+ "淦",
+ "淨",
+ "淪",
+ "淫",
+ "淬",
+ "淮",
+ "淯",
+ "深",
+ "淳",
+ "淵",
+ "混",
+ "淸",
+ "淹",
+ "淺",
+ "添",
+ "淼",
+ "渀",
+ "清",
+ "渇",
+ "済",
+ "渉",
+ "渊",
+ "渋",
+ "渌",
+ "渍",
+ "渎",
+ "渐",
+ "渑",
+ "渓",
+ "渔",
+ "渕",
+ "渗",
+ "渙",
+ "渚",
+ "減",
+ "渝",
+ "渟",
+ "渠",
+ "渡",
+ "渣",
+ "渤",
+ "渥",
+ "渦",
+ "温",
+ "渫",
+ "測",
+ "渭",
+ "港",
+ "渲",
+ "渴",
+ "游",
+ "渺",
+ "渾",
+ "湃",
+ "湄",
+ "湉",
+ "湊",
+ "湍",
+ "湎",
+ "湓",
+ "湔",
+ "湖",
+ "湘",
+ "湛",
+ "湜",
+ "湝",
+ "湟",
+ "湣",
+ "湧",
+ "湫",
+ "湮",
+ "湯",
+ "湲",
+ "湴",
+ "湶",
+ "湾",
+ "湿",
+ "満",
+ "溂",
+ "溃",
+ "溅",
+ "溆",
+ "溇",
+ "溉",
+ "溌",
+ "溍",
+ "溏",
+ "源",
+ "準",
+ "溘",
+ "溜",
+ "溝",
+ "溟",
+ "溢",
+ "溥",
+ "溧",
+ "溪",
+ "溫",
+ "溯",
+ "溱",
+ "溲",
+ "溴",
+ "溶",
+ "溷",
+ "溺",
+ "溽",
+ "滁",
+ "滂",
+ "滄",
+ "滅",
+ "滇",
+ "滈",
+ "滉",
+ "滋",
+ "滌",
+ "滏",
+ "滑",
+ "滓",
+ "滔",
+ "滕",
+ "滗",
+ "滘",
+ "滚",
+ "滝",
+ "滞",
+ "滟",
+ "滠",
+ "满",
+ "滢",
+ "滤",
+ "滥",
+ "滦",
+ "滨",
+ "滩",
+ "滬",
+ "滯",
+ "滲",
+ "滴",
+ "滸",
+ "滹",
+ "滾",
+ "滿",
+ "漁",
+ "漂",
+ "漆",
+ "漈",
+ "漉",
+ "漏",
+ "漑",
+ "漓",
+ "演",
+ "漕",
+ "漠",
+ "漢",
+ "漣",
+ "漩",
+ "漪",
+ "漫",
+ "漬",
+ "漭",
+ "漯",
+ "漱",
+ "漲",
+ "漳",
+ "漴",
+ "漶",
+ "漷",
+ "漸",
+ "漼",
+ "漾",
+ "漿",
+ "潅",
+ "潆",
+ "潇",
+ "潋",
+ "潍",
+ "潎",
+ "潏",
+ "潑",
+ "潔",
+ "潘",
+ "潛",
+ "潜",
+ "潞",
+ "潟",
+ "潡",
+ "潢",
+ "潤",
+ "潥",
+ "潦",
+ "潩",
+ "潬",
+ "潭",
+ "潮",
+ "潰",
+ "潲",
+ "潴",
+ "潵",
+ "潸",
+ "潺",
+ "潼",
+ "澀",
+ "澁",
+ "澄",
+ "澆",
+ "澈",
+ "澌",
+ "澍",
+ "澎",
+ "澗",
+ "澜",
+ "澡",
+ "澣",
+ "澤",
+ "澧",
+ "澪",
+ "澱",
+ "澳",
+ "澴",
+ "澶",
+ "澹",
+ "激",
+ "濁",
+ "濂",
+ "濃",
+ "濆",
+ "濉",
+ "濑",
+ "濒",
+ "濕",
+ "濘",
+ "濛",
+ "濞",
+ "濟",
+ "濠",
+ "濡",
+ "濤",
+ "濩",
+ "濫",
+ "濬",
+ "濮",
+ "濯",
+ "濱",
+ "濶",
+ "濺",
+ "濾",
+ "瀉",
+ "瀋",
+ "瀍",
+ "瀏",
+ "瀑",
+ "瀕",
+ "瀚",
+ "瀛",
+ "瀝",
+ "瀞",
+ "瀟",
+ "瀣",
+ "瀦",
+ "瀧",
+ "瀬",
+ "瀰",
+ "瀲",
+ "瀹",
+ "瀾",
+ "灌",
+ "灏",
+ "灑",
+ "灘",
+ "灞",
+ "灣",
+ "火",
+ "灭",
+ "灯",
+ "灰",
+ "灵",
+ "灶",
+ "灸",
+ "灼",
+ "災",
+ "灾",
+ "灿",
+ "炀",
+ "炁",
+ "炅",
+ "炆",
+ "炉",
+ "炊",
+ "炎",
+ "炒",
+ "炔",
+ "炕",
+ "炖",
+ "炙",
+ "炜",
+ "炝",
+ "炟",
+ "炤",
+ "炪",
+ "炫",
+ "炬",
+ "炭",
+ "炮",
+ "炯",
+ "炳",
+ "炴",
+ "炷",
+ "炸",
+ "点",
+ "為",
+ "炼",
+ "炽",
+ "烀",
+ "烁",
+ "烂",
+ "烃",
+ "烈",
+ "烊",
+ "烏",
+ "烖",
+ "烘",
+ "烙",
+ "烛",
+ "烜",
+ "烟",
+ "烤",
+ "烦",
+ "烧",
+ "烨",
+ "烩",
+ "烫",
+ "烬",
+ "热",
+ "烯",
+ "烱",
+ "烷",
+ "烹",
+ "烽",
+ "焉",
+ "焊",
+ "焐",
+ "焓",
+ "焔",
+ "焕",
+ "焖",
+ "焗",
+ "焘",
+ "焙",
+ "焚",
+ "焜",
+ "無",
+ "焦",
+ "焯",
+ "焰",
+ "焱",
+ "然",
+ "焼",
+ "煅",
+ "煉",
+ "煊",
+ "煋",
+ "煌",
+ "煎",
+ "煕",
+ "煖",
+ "煙",
+ "煜",
+ "煞",
+ "煟",
+ "煢",
+ "煤",
+ "煥",
+ "煦",
+ "照",
+ "煨",
+ "煩",
+ "煬",
+ "煮",
+ "煲",
+ "煳",
+ "煸",
+ "煺",
+ "煽",
+ "煿",
+ "熄",
+ "熊",
+ "熏",
+ "熔",
+ "熘",
+ "熙",
+ "熜",
+ "熟",
+ "熠",
+ "熨",
+ "熬",
+ "熱",
+ "熳",
+ "熵",
+ "熹",
+ "熾",
+ "燃",
+ "燄",
+ "燈",
+ "燉",
+ "燊",
+ "燋",
+ "燎",
+ "燐",
+ "燒",
+ "燔",
+ "燕",
+ "燗",
+ "燙",
+ "燚",
+ "營",
+ "燠",
+ "燥",
+ "燦",
+ "燧",
+ "燭",
+ "燮",
+ "燵",
+ "燹",
+ "燻",
+ "燼",
+ "燿",
+ "爆",
+ "爍",
+ "爐",
+ "爛",
+ "爨",
+ "爪",
+ "爬",
+ "爭",
+ "爰",
+ "爱",
+ "爲",
+ "爵",
+ "父",
+ "爷",
+ "爸",
+ "爹",
+ "爺",
+ "爻",
+ "爼",
+ "爽",
+ "爾",
+ "爿",
+ "牀",
+ "牁",
+ "牂",
+ "牆",
+ "片",
+ "版",
+ "牌",
+ "牍",
+ "牒",
+ "牕",
+ "牖",
+ "牘",
+ "牙",
+ "牛",
+ "牝",
+ "牟",
+ "牠",
+ "牡",
+ "牢",
+ "牤",
+ "牦",
+ "牧",
+ "物",
+ "牮",
+ "牯",
+ "牲",
+ "牴",
+ "牵",
+ "牸",
+ "特",
+ "牺",
+ "牽",
+ "牾",
+ "犀",
+ "犁",
+ "犂",
+ "犄",
+ "犇",
+ "犊",
+ "犋",
+ "犍",
+ "犒",
+ "犖",
+ "犟",
+ "犠",
+ "犢",
+ "犧",
+ "犬",
+ "犯",
+ "犰",
+ "犳",
+ "犴",
+ "状",
+ "犷",
+ "犸",
+ "犹",
+ "犼",
+ "狀",
+ "狂",
+ "狄",
+ "狆",
+ "狈",
+ "狌",
+ "狍",
+ "狎",
+ "狐",
+ "狒",
+ "狗",
+ "狙",
+ "狛",
+ "狝",
+ "狞",
+ "狠",
+ "狡",
+ "狢",
+ "狨",
+ "狩",
+ "独",
+ "狭",
+ "狮",
+ "狰",
+ "狱",
+ "狲",
+ "狴",
+ "狷",
+ "狸",
+ "狹",
+ "狻",
+ "狼",
+ "狽",
+ "猁",
+ "猇",
+ "猊",
+ "猎",
+ "猕",
+ "猖",
+ "猗",
+ "猙",
+ "猛",
+ "猜",
+ "猝",
+ "猞",
+ "猟",
+ "猡",
+ "猢",
+ "猥",
+ "猨",
+ "猩",
+ "猪",
+ "猫",
+ "猬",
+ "献",
+ "猯",
+ "猱",
+ "猲",
+ "猴",
+ "猶",
+ "猷",
+ "猹",
+ "猾",
+ "猿",
+ "獄",
+ "獅",
+ "獎",
+ "獏",
+ "獐",
+ "獒",
+ "獗",
+ "獠",
+ "獣",
+ "獨",
+ "獪",
+ "獬",
+ "獭",
+ "獰",
+ "獲",
+ "獵",
+ "獸",
+ "獺",
+ "獻",
+ "獾",
+ "玄",
+ "率",
+ "玉",
+ "王",
+ "玎",
+ "玑",
+ "玕",
+ "玖",
+ "玘",
+ "玙",
+ "玚",
+ "玛",
+ "玟",
+ "玠",
+ "玢",
+ "玥",
+ "玦",
+ "玩",
+ "玫",
+ "玮",
+ "环",
+ "现",
+ "玲",
+ "玳",
+ "玷",
+ "玹",
+ "玺",
+ "玻",
+ "珀",
+ "珂",
+ "珅",
+ "珈",
+ "珉",
+ "珊",
+ "珍",
+ "珎",
+ "珏",
+ "珐",
+ "珑",
+ "珙",
+ "珜",
+ "珞",
+ "珠",
+ "珣",
+ "珥",
+ "珦",
+ "珧",
+ "珩",
+ "珪",
+ "珫",
+ "班",
+ "珮",
+ "珰",
+ "珲",
+ "珸",
+ "珺",
+ "珽",
+ "現",
+ "球",
+ "琅",
+ "理",
+ "琇",
+ "琉",
+ "琊",
+ "琍",
+ "琎",
+ "琏",
+ "琐",
+ "琚",
+ "琛",
+ "琢",
+ "琤",
+ "琥",
+ "琦",
+ "琨",
+ "琪",
+ "琬",
+ "琮",
+ "琯",
+ "琰",
+ "琲",
+ "琳",
+ "琴",
+ "琵",
+ "琶",
+ "琺",
+ "琼",
+ "瑀",
+ "瑁",
+ "瑄",
+ "瑕",
+ "瑗",
+ "瑙",
+ "瑚",
+ "瑛",
+ "瑜",
+ "瑞",
+ "瑟",
+ "瑠",
+ "瑣",
+ "瑤",
+ "瑩",
+ "瑪",
+ "瑭",
+ "瑮",
+ "瑯",
+ "瑰",
+ "瑱",
+ "瑳",
+ "瑴",
+ "瑶",
+ "瑷",
+ "瑾",
+ "璀",
+ "璁",
+ "璃",
+ "璇",
+ "璈",
+ "璋",
+ "璎",
+ "璐",
+ "璘",
+ "璜",
+ "璝",
+ "璞",
+ "璟",
+ "璠",
+ "璣",
+ "璧",
+ "璨",
+ "璩",
+ "環",
+ "璺",
+ "璽",
+ "瓊",
+ "瓏",
+ "瓒",
+ "瓔",
+ "瓘",
+ "瓜",
+ "瓠",
+ "瓢",
+ "瓣",
+ "瓤",
+ "瓦",
+ "瓫",
+ "瓮",
+ "瓯",
+ "瓴",
+ "瓶",
+ "瓷",
+ "瓿",
+ "甃",
+ "甄",
+ "甌",
+ "甍",
+ "甎",
+ "甏",
+ "甑",
+ "甓",
+ "甕",
+ "甘",
+ "甙",
+ "甚",
+ "甜",
+ "生",
+ "產",
+ "産",
+ "甥",
+ "甦",
+ "用",
+ "甩",
+ "甪",
+ "甫",
+ "甬",
+ "甭",
+ "甯",
+ "田",
+ "由",
+ "甲",
+ "申",
+ "甴",
+ "电",
+ "男",
+ "甸",
+ "町",
+ "画",
+ "甾",
+ "畀",
+ "畅",
+ "畈",
+ "畉",
+ "畊",
+ "畋",
+ "界",
+ "畎",
+ "畏",
+ "畑",
+ "畔",
+ "留",
+ "畚",
+ "畛",
+ "畜",
+ "畝",
+ "畠",
+ "畢",
+ "畤",
+ "略",
+ "畦",
+ "番",
+ "畫",
+ "畬",
+ "畭",
+ "畯",
+ "異",
+ "畲",
+ "畳",
+ "畴",
+ "畵",
+ "當",
+ "畷",
+ "畸",
+ "畹",
+ "畿",
+ "疃",
+ "疆",
+ "疇",
+ "疊",
+ "疋",
+ "疍",
+ "疎",
+ "疏",
+ "疑",
+ "疔",
+ "疖",
+ "疗",
+ "疙",
+ "疚",
+ "疝",
+ "疟",
+ "疠",
+ "疡",
+ "疣",
+ "疤",
+ "疥",
+ "疫",
+ "疬",
+ "疭",
+ "疮",
+ "疯",
+ "疰",
+ "疱",
+ "疲",
+ "疳",
+ "疴",
+ "疵",
+ "疸",
+ "疹",
+ "疼",
+ "疽",
+ "疾",
+ "痂",
+ "痃",
+ "痄",
+ "病",
+ "症",
+ "痈",
+ "痉",
+ "痊",
+ "痍",
+ "痒",
+ "痔",
+ "痕",
+ "痘",
+ "痙",
+ "痛",
+ "痞",
+ "痢",
+ "痣",
+ "痤",
+ "痦",
+ "痧",
+ "痨",
+ "痩",
+ "痪",
+ "痫",
+ "痰",
+ "痱",
+ "痲",
+ "痳",
+ "痴",
+ "痹",
+ "痺",
+ "痼",
+ "痾",
+ "痿",
+ "瘀",
+ "瘁",
+ "瘅",
+ "瘆",
+ "瘊",
+ "瘋",
+ "瘌",
+ "瘍",
+ "瘓",
+ "瘕",
+ "瘗",
+ "瘘",
+ "瘙",
+ "瘝",
+ "瘟",
+ "瘠",
+ "瘡",
+ "瘢",
+ "瘤",
+ "瘦",
+ "瘧",
+ "瘩",
+ "瘪",
+ "瘫",
+ "瘰",
+ "瘳",
+ "瘴",
+ "瘵",
+ "瘸",
+ "瘻",
+ "瘼",
+ "瘾",
+ "瘿",
+ "癀",
+ "療",
+ "癃",
+ "癆",
+ "癇",
+ "癈",
+ "癌",
+ "癍",
+ "癎",
+ "癒",
+ "癔",
+ "癖",
+ "癘",
+ "癜",
+ "癞",
+ "癡",
+ "癢",
+ "癣",
+ "癥",
+ "癧",
+ "癩",
+ "癪",
+ "癫",
+ "癬",
+ "癮",
+ "癯",
+ "癰",
+ "癱",
+ "癲",
+ "癸",
+ "発",
+ "登",
+ "發",
+ "白",
+ "百",
+ "皀",
+ "皂",
+ "的",
+ "皆",
+ "皇",
+ "皈",
+ "皋",
+ "皌",
+ "皎",
+ "皐",
+ "皑",
+ "皓",
+ "皕",
+ "皖",
+ "皙",
+ "皚",
+ "皝",
+ "皞",
+ "皤",
+ "皦",
+ "皮",
+ "皯",
+ "皰",
+ "皱",
+ "皲",
+ "皴",
+ "皷",
+ "皸",
+ "皹",
+ "皺",
+ "皿",
+ "盂",
+ "盃",
+ "盅",
+ "盆",
+ "盈",
+ "盉",
+ "益",
+ "盍",
+ "盎",
+ "盏",
+ "盐",
+ "监",
+ "盒",
+ "盔",
+ "盖",
+ "盗",
+ "盘",
+ "盛",
+ "盜",
+ "盞",
+ "盟",
+ "盡",
+ "監",
+ "盤",
+ "盥",
+ "盧",
+ "盩",
+ "盪",
+ "目",
+ "盯",
+ "盱",
+ "盲",
+ "直",
+ "相",
+ "盹",
+ "盻",
+ "盼",
+ "盾",
+ "眀",
+ "省",
+ "眄",
+ "眇",
+ "眈",
+ "眉",
+ "看",
+ "県",
+ "眍",
+ "眙",
+ "眚",
+ "眛",
+ "眜",
+ "眞",
+ "真",
+ "眠",
+ "眥",
+ "眦",
+ "眨",
+ "眩",
+ "眬",
+ "眭",
+ "眯",
+ "眵",
+ "眶",
+ "眷",
+ "眸",
+ "眺",
+ "眼",
+ "眾",
+ "着",
+ "睁",
+ "睃",
+ "睆",
+ "睇",
+ "睐",
+ "睑",
+ "睚",
+ "睛",
+ "睜",
+ "睞",
+ "睟",
+ "睡",
+ "睢",
+ "督",
+ "睥",
+ "睦",
+ "睨",
+ "睫",
+ "睬",
+ "睱",
+ "睹",
+ "睺",
+ "睽",
+ "睾",
+ "睿",
+ "瞀",
+ "瞄",
+ "瞅",
+ "瞆",
+ "瞇",
+ "瞋",
+ "瞌",
+ "瞎",
+ "瞑",
+ "瞒",
+ "瞓",
+ "瞞",
+ "瞟",
+ "瞠",
+ "瞢",
+ "瞥",
+ "瞧",
+ "瞩",
+ "瞪",
+ "瞬",
+ "瞭",
+ "瞰",
+ "瞳",
+ "瞵",
+ "瞻",
+ "瞼",
+ "瞽",
+ "瞾",
+ "瞿",
+ "矇",
+ "矍",
+ "矓",
+ "矗",
+ "矚",
+ "矛",
+ "矜",
+ "矢",
+ "矣",
+ "知",
+ "矧",
+ "矩",
+ "矫",
+ "矬",
+ "短",
+ "矮",
+ "矯",
+ "矱",
+ "石",
+ "矶",
+ "矸",
+ "矼",
+ "矽",
+ "矾",
+ "矿",
+ "砀",
+ "码",
+ "砂",
+ "砊",
+ "砌",
+ "砍",
+ "砒",
+ "研",
+ "砕",
+ "砖",
+ "砗",
+ "砘",
+ "砚",
+ "砜",
+ "砝",
+ "砟",
+ "砠",
+ "砣",
+ "砥",
+ "砦",
+ "砧",
+ "砩",
+ "砫",
+ "砬",
+ "砭",
+ "砰",
+ "砲",
+ "破",
+ "砵",
+ "砷",
+ "砸",
+ "砺",
+ "砻",
+ "砼",
+ "砾",
+ "砿",
+ "础",
+ "硁",
+ "硅",
+ "硌",
+ "硐",
+ "硒",
+ "硕",
+ "硖",
+ "硗",
+ "硚",
+ "硝",
+ "硞",
+ "硪",
+ "硫",
+ "硬",
+ "硭",
+ "确",
+ "硯",
+ "硲",
+ "硴",
+ "硷",
+ "硼",
+ "硿",
+ "碁",
+ "碆",
+ "碇",
+ "碉",
+ "碌",
+ "碍",
+ "碎",
+ "碑",
+ "碓",
+ "碕",
+ "碗",
+ "碘",
+ "碚",
+ "碛",
+ "碜",
+ "碟",
+ "碡",
+ "碣",
+ "碧",
+ "碩",
+ "碪",
+ "碰",
+ "碱",
+ "碲",
+ "碳",
+ "碴",
+ "確",
+ "碼",
+ "碾",
+ "磁",
+ "磅",
+ "磆",
+ "磉",
+ "磊",
+ "磋",
+ "磐",
+ "磑",
+ "磒",
+ "磔",
+ "磕",
+ "磙",
+ "磚",
+ "磡",
+ "磧",
+ "磨",
+ "磬",
+ "磯",
+ "磲",
+ "磴",
+ "磷",
+ "磺",
+ "磻",
+ "磾",
+ "礁",
+ "礅",
+ "礌",
+ "礎",
+ "礒",
+ "礓",
+ "礙",
+ "礞",
+ "礦",
+ "礪",
+ "礫",
+ "礬",
+ "礴",
+ "示",
+ "礻",
+ "礼",
+ "礽",
+ "社",
+ "祀",
+ "祁",
+ "祆",
+ "祇",
+ "祈",
+ "祉",
+ "祎",
+ "祏",
+ "祐",
+ "祓",
+ "祖",
+ "祗",
+ "祚",
+ "祛",
+ "祜",
+ "祝",
+ "神",
+ "祟",
+ "祠",
+ "祢",
+ "祥",
+ "祧",
+ "票",
+ "祭",
+ "祯",
+ "祷",
+ "祸",
+ "祺",
+ "祼",
+ "祿",
+ "禀",
+ "禁",
+ "禄",
+ "禅",
+ "禊",
+ "禍",
+ "禎",
+ "福",
+ "禛",
+ "禥",
+ "禦",
+ "禧",
+ "禨",
+ "禩",
+ "禪",
+ "禮",
+ "禰",
+ "禱",
+ "禳",
+ "禹",
+ "禺",
+ "离",
+ "禽",
+ "禾",
+ "禿",
+ "秀",
+ "私",
+ "秂",
+ "秃",
+ "秆",
+ "秉",
+ "秋",
+ "种",
+ "秏",
+ "科",
+ "秒",
+ "秕",
+ "秘",
+ "租",
+ "秡",
+ "秣",
+ "秤",
+ "秦",
+ "秧",
+ "秩",
+ "秫",
+ "秬",
+ "秭",
+ "积",
+ "称",
+ "秸",
+ "移",
+ "秽",
+ "秾",
+ "稀",
+ "稂",
+ "稅",
+ "稈",
+ "稊",
+ "程",
+ "稍",
+ "税",
+ "稔",
+ "稗",
+ "稙",
+ "稚",
+ "稜",
+ "稞",
+ "稟",
+ "稠",
+ "稣",
+ "種",
+ "稱",
+ "稲",
+ "稳",
+ "稷",
+ "稹",
+ "稻",
+ "稼",
+ "稽",
+ "稿",
+ "穀",
+ "穂",
+ "穆",
+ "穇",
+ "穌",
+ "積",
+ "穎",
+ "穏",
+ "穐",
+ "穑",
+ "穗",
+ "穡",
+ "穢",
+ "穣",
+ "穩",
+ "穫",
+ "穰",
+ "穴",
+ "究",
+ "穷",
+ "穸",
+ "穹",
+ "空",
+ "穽",
+ "穿",
+ "窀",
+ "突",
+ "窃",
+ "窄",
+ "窈",
+ "窍",
+ "窎",
+ "窑",
+ "窒",
+ "窓",
+ "窕",
+ "窖",
+ "窗",
+ "窘",
+ "窜",
+ "窝",
+ "窟",
+ "窠",
+ "窡",
+ "窣",
+ "窥",
+ "窦",
+ "窨",
+ "窩",
+ "窪",
+ "窭",
+ "窮",
+ "窯",
+ "窳",
+ "窶",
+ "窸",
+ "窺",
+ "窾",
+ "窿",
+ "竃",
+ "竄",
+ "竅",
+ "竇",
+ "竈",
+ "竊",
+ "立",
+ "竑",
+ "竖",
+ "站",
+ "竜",
+ "竝",
+ "竞",
+ "竟",
+ "章",
+ "竢",
+ "竣",
+ "童",
+ "竦",
+ "竪",
+ "竭",
+ "端",
+ "竲",
+ "競",
+ "竹",
+ "竺",
+ "竽",
+ "竿",
+ "笂",
+ "笃",
+ "笄",
+ "笆",
+ "笈",
+ "笊",
+ "笋",
+ "笏",
+ "笑",
+ "笔",
+ "笕",
+ "笖",
+ "笘",
+ "笙",
+ "笛",
+ "笞",
+ "笠",
+ "笤",
+ "笥",
+ "符",
+ "笨",
+ "笩",
+ "笪",
+ "笫",
+ "第",
+ "笳",
+ "笵",
+ "笸",
+ "笹",
+ "笺",
+ "笼",
+ "笾",
+ "筅",
+ "筆",
+ "筇",
+ "筈",
+ "等",
+ "筊",
+ "筋",
+ "筌",
+ "筍",
+ "筏",
+ "筐",
+ "筑",
+ "筒",
+ "答",
+ "策",
+ "筘",
+ "筚",
+ "筛",
+ "筜",
+ "筝",
+ "筠",
+ "筢",
+ "筥",
+ "筧",
+ "筬",
+ "筮",
+ "筰",
+ "筱",
+ "筲",
+ "筵",
+ "筷",
+ "筹",
+ "筺",
+ "筻",
+ "筼",
+ "签",
+ "简",
+ "箅",
+ "箆",
+ "箇",
+ "箋",
+ "箍",
+ "箏",
+ "箐",
+ "箒",
+ "箓",
+ "箔",
+ "箕",
+ "算",
+ "箙",
+ "箚",
+ "箜",
+ "箝",
+ "箟",
+ "管",
+ "箢",
+ "箥",
+ "箦",
+ "箧",
+ "箨",
+ "箩",
+ "箪",
+ "箫",
+ "箬",
+ "箭",
+ "箱",
+ "箴",
+ "箸",
+ "箻",
+ "箼",
+ "箾",
+ "節",
+ "篁",
+ "範",
+ "篆",
+ "篇",
+ "築",
+ "篋",
+ "篌",
+ "篑",
+ "篓",
+ "篙",
+ "篚",
+ "篝",
+ "篠",
+ "篡",
+ "篤",
+ "篥",
+ "篦",
+ "篩",
+ "篪",
+ "篭",
+ "篮",
+ "篱",
+ "篳",
+ "篶",
+ "篷",
+ "篼",
+ "篾",
+ "簀",
+ "簃",
+ "簇",
+ "簋",
+ "簌",
+ "簍",
+ "簏",
+ "簑",
+ "簒",
+ "簓",
+ "簔",
+ "簖",
+ "簗",
+ "簟",
+ "簡",
+ "簣",
+ "簦",
+ "簧",
+ "簪",
+ "簫",
+ "簰",
+ "簷",
+ "簸",
+ "簺",
+ "簽",
+ "簾",
+ "簿",
+ "籀",
+ "籁",
+ "籃",
+ "籇",
+ "籌",
+ "籍",
+ "籏",
+ "籐",
+ "籓",
+ "籔",
+ "籖",
+ "籟",
+ "籠",
+ "籣",
+ "籤",
+ "籬",
+ "籮",
+ "籲",
+ "米",
+ "类",
+ "籼",
+ "籽",
+ "籾",
+ "粁",
+ "粂",
+ "粃",
+ "粉",
+ "粋",
+ "粍",
+ "粑",
+ "粒",
+ "粕",
+ "粗",
+ "粘",
+ "粛",
+ "粝",
+ "粟",
+ "粢",
+ "粤",
+ "粥",
+ "粦",
+ "粧",
+ "粪",
+ "粭",
+ "粮",
+ "粱",
+ "粲",
+ "粳",
+ "粵",
+ "粹",
+ "粼",
+ "粽",
+ "精",
+ "糀",
+ "糁",
+ "糅",
+ "糊",
+ "糌",
+ "糍",
+ "糎",
+ "糒",
+ "糕",
+ "糖",
+ "糗",
+ "糘",
+ "糙",
+ "糜",
+ "糞",
+ "糟",
+ "糠",
+ "糢",
+ "糧",
+ "糨",
+ "糯",
+ "糲",
+ "糶",
+ "糸",
+ "糺",
+ "系",
+ "糾",
+ "紀",
+ "紂",
+ "約",
+ "紅",
+ "紆",
+ "紉",
+ "紊",
+ "紋",
+ "納",
+ "紐",
+ "純",
+ "紗",
+ "紘",
+ "紙",
+ "級",
+ "紛",
+ "紜",
+ "素",
+ "紡",
+ "索",
+ "紧",
+ "紫",
+ "紬",
+ "紮",
+ "累",
+ "細",
+ "紲",
+ "紳",
+ "紵",
+ "紹",
+ "紺",
+ "絀",
+ "終",
+ "絃",
+ "組",
+ "絅",
+ "絆",
+ "絋",
+ "経",
+ "絎",
+ "絏",
+ "結",
+ "絕",
+ "絖",
+ "絛",
+ "絜",
+ "絞",
+ "絡",
+ "絢",
+ "絣",
+ "給",
+ "絨",
+ "絮",
+ "絯",
+ "統",
+ "絲",
+ "絳",
+ "絵",
+ "絶",
+ "絹",
+ "絺",
+ "絽",
+ "綁",
+ "綉",
+ "綏",
+ "經",
+ "継",
+ "続",
+ "綛",
+ "綜",
+ "綟",
+ "綠",
+ "綢",
+ "綣",
+ "綦",
+ "綬",
+ "維",
+ "綮",
+ "綯",
+ "綰",
+ "綱",
+ "網",
+ "綴",
+ "綵",
+ "綶",
+ "綸",
+ "綺",
+ "綻",
+ "綽",
+ "綾",
+ "綿",
+ "緇",
+ "緊",
+ "緋",
+ "総",
+ "緑",
+ "緒",
+ "緘",
+ "線",
+ "緛",
+ "緝",
+ "緞",
+ "締",
+ "緡",
+ "緣",
+ "緤",
+ "編",
+ "緩",
+ "緬",
+ "緯",
+ "緲",
+ "練",
+ "緻",
+ "縁",
+ "縄",
+ "縅",
+ "縈",
+ "縉",
+ "縊",
+ "縋",
+ "縒",
+ "縛",
+ "縞",
+ "縟",
+ "縠",
+ "縢",
+ "縣",
+ "縦",
+ "縫",
+ "縮",
+ "縱",
+ "縲",
+ "縴",
+ "縵",
+ "縷",
+ "縹",
+ "縺",
+ "縻",
+ "總",
+ "績",
+ "繁",
+ "繃",
+ "繆",
+ "繇",
+ "繊",
+ "繋",
+ "繍",
+ "繑",
+ "織",
+ "繕",
+ "繖",
+ "繙",
+ "繚",
+ "繝",
+ "繞",
+ "繡",
+ "繧",
+ "繩",
+ "繪",
+ "繫",
+ "繭",
+ "繰",
+ "繳",
+ "繹",
+ "繻",
+ "繼",
+ "繽",
+ "纂",
+ "纇",
+ "纈",
+ "續",
+ "纍",
+ "纏",
+ "纐",
+ "纒",
+ "纓",
+ "纔",
+ "纖",
+ "纛",
+ "纜",
+ "纠",
+ "纡",
+ "红",
+ "纣",
+ "纤",
+ "纥",
+ "约",
+ "级",
+ "纨",
+ "纩",
+ "纪",
+ "纫",
+ "纬",
+ "纭",
+ "纮",
+ "纯",
+ "纰",
+ "纱",
+ "纲",
+ "纳",
+ "纵",
+ "纶",
+ "纷",
+ "纸",
+ "纹",
+ "纺",
+ "纻",
+ "纽",
+ "纾",
+ "线",
+ "绀",
+ "绁",
+ "绂",
+ "练",
+ "组",
+ "绅",
+ "细",
+ "织",
+ "终",
+ "绉",
+ "绊",
+ "绋",
+ "绌",
+ "绍",
+ "绎",
+ "经",
+ "绐",
+ "绑",
+ "绒",
+ "结",
+ "绔",
+ "绕",
+ "绗",
+ "绘",
+ "给",
+ "绚",
+ "绛",
+ "络",
+ "绝",
+ "绞",
+ "统",
+ "绡",
+ "绢",
+ "绣",
+ "绤",
+ "绥",
+ "绦",
+ "继",
+ "绨",
+ "绩",
+ "绪",
+ "绫",
+ "续",
+ "绮",
+ "绯",
+ "绰",
+ "绱",
+ "绲",
+ "绳",
+ "维",
+ "绵",
+ "绶",
+ "绷",
+ "绸",
+ "绺",
+ "绻",
+ "综",
+ "绽",
+ "绾",
+ "绿",
+ "缀",
+ "缁",
+ "缂",
+ "缃",
+ "缄",
+ "缅",
+ "缆",
+ "缇",
+ "缈",
+ "缉",
+ "缊",
+ "缋",
+ "缌",
+ "缎",
+ "缑",
+ "缒",
+ "缓",
+ "缔",
+ "缕",
+ "编",
+ "缗",
+ "缘",
+ "缙",
+ "缚",
+ "缛",
+ "缜",
+ "缝",
+ "缟",
+ "缠",
+ "缢",
+ "缣",
+ "缤",
+ "缥",
+ "缦",
+ "缧",
+ "缨",
+ "缩",
+ "缪",
+ "缫",
+ "缬",
+ "缭",
+ "缮",
+ "缯",
+ "缰",
+ "缱",
+ "缳",
+ "缴",
+ "缵",
+ "缶",
+ "缸",
+ "缺",
+ "罂",
+ "罄",
+ "罅",
+ "罇",
+ "罌",
+ "罍",
+ "罐",
+ "网",
+ "罔",
+ "罕",
+ "罗",
+ "罘",
+ "罚",
+ "罟",
+ "罠",
+ "罡",
+ "罢",
+ "罧",
+ "罨",
+ "罩",
+ "罪",
+ "罫",
+ "置",
+ "罰",
+ "署",
+ "罴",
+ "罵",
+ "罷",
+ "罹",
+ "罾",
+ "羁",
+ "羂",
+ "羃",
+ "羅",
+ "羆",
+ "羇",
+ "羈",
+ "羊",
+ "羌",
+ "美",
+ "羑",
+ "羔",
+ "羖",
+ "羗",
+ "羚",
+ "羝",
+ "羞",
+ "羟",
+ "羡",
+ "羣",
+ "群",
+ "羧",
+ "羨",
+ "義",
+ "羯",
+ "羰",
+ "羲",
+ "羶",
+ "羸",
+ "羹",
+ "羽",
+ "羿",
+ "翀",
+ "翁",
+ "翃",
+ "翅",
+ "翆",
+ "翊",
+ "翌",
+ "翎",
+ "習",
+ "翔",
+ "翕",
+ "翘",
+ "翚",
+ "翛",
+ "翟",
+ "翠",
+ "翡",
+ "翥",
+ "翦",
+ "翩",
+ "翫",
+ "翮",
+ "翰",
+ "翱",
+ "翳",
+ "翹",
+ "翻",
+ "翼",
+ "耀",
+ "老",
+ "考",
+ "耄",
+ "者",
+ "耆",
+ "耋",
+ "而",
+ "耍",
+ "耐",
+ "耒",
+ "耕",
+ "耗",
+ "耘",
+ "耙",
+ "耜",
+ "耦",
+ "耧",
+ "耨",
+ "耪",
+ "耱",
+ "耳",
+ "耵",
+ "耶",
+ "耷",
+ "耸",
+ "耻",
+ "耽",
+ "耿",
+ "聂",
+ "聃",
+ "聆",
+ "聊",
+ "聋",
+ "职",
+ "聍",
+ "聒",
+ "联",
+ "聖",
+ "聘",
+ "聚",
+ "聞",
+ "聟",
+ "聡",
+ "聢",
+ "聨",
+ "聩",
+ "聪",
+ "聯",
+ "聰",
+ "聲",
+ "聳",
+ "聴",
+ "聵",
+ "聶",
+ "職",
+ "聽",
+ "聾",
+ "聿",
+ "肃",
+ "肄",
+ "肅",
+ "肆",
+ "肇",
+ "肉",
+ "肋",
+ "肌",
+ "肏",
+ "肓",
+ "肖",
+ "肘",
+ "肚",
+ "肛",
+ "肝",
+ "肟",
+ "肠",
+ "股",
+ "肢",
+ "肤",
+ "肥",
+ "肩",
+ "肪",
+ "肫",
+ "肬",
+ "肭",
+ "肮",
+ "肯",
+ "肱",
+ "育",
+ "肴",
+ "肷",
+ "肸",
+ "肺",
+ "肼",
+ "肽",
+ "肾",
+ "肿",
+ "胀",
+ "胁",
+ "胃",
+ "胄",
+ "胆",
+ "背",
+ "胍",
+ "胎",
+ "胖",
+ "胗",
+ "胙",
+ "胚",
+ "胛",
+ "胜",
+ "胝",
+ "胞",
+ "胡",
+ "胤",
+ "胥",
+ "胧",
+ "胪",
+ "胫",
+ "胬",
+ "胭",
+ "胯",
+ "胰",
+ "胱",
+ "胳",
+ "胴",
+ "胶",
+ "胸",
+ "胺",
+ "胼",
+ "能",
+ "脁",
+ "脂",
+ "脅",
+ "脆",
+ "脇",
+ "脈",
+ "脉",
+ "脊",
+ "脍",
+ "脏",
+ "脐",
+ "脑",
+ "脒",
+ "脓",
+ "脔",
+ "脖",
+ "脘",
+ "脚",
+ "脛",
+ "脣",
+ "脩",
+ "脫",
+ "脬",
+ "脯",
+ "脰",
+ "脱",
+ "脲",
+ "脳",
+ "脷",
+ "脸",
+ "脹",
+ "脾",
+ "腆",
+ "腈",
+ "腊",
+ "腋",
+ "腌",
+ "腎",
+ "腐",
+ "腑",
+ "腓",
+ "腔",
+ "腕",
+ "腘",
+ "腙",
+ "腚",
+ "腟",
+ "腠",
+ "腥",
+ "腦",
+ "腧",
+ "腩",
+ "腫",
+ "腭",
+ "腮",
+ "腰",
+ "腱",
+ "腳",
+ "腴",
+ "腸",
+ "腹",
+ "腺",
+ "腻",
+ "腼",
+ "腾",
+ "腿",
+ "膀",
+ "膂",
+ "膃",
+ "膈",
+ "膊",
+ "膏",
+ "膑",
+ "膕",
+ "膘",
+ "膚",
+ "膛",
+ "膜",
+ "膝",
+ "膠",
+ "膣",
+ "膦",
+ "膨",
+ "膩",
+ "膳",
+ "膴",
+ "膵",
+ "膺",
+ "膻",
+ "膽",
+ "膾",
+ "膿",
+ "臀",
+ "臂",
+ "臃",
+ "臆",
+ "臇",
+ "臈",
+ "臉",
+ "臊",
+ "臌",
+ "臍",
+ "臑",
+ "臓",
+ "臘",
+ "臙",
+ "臚",
+ "臜",
+ "臟",
+ "臣",
+ "臥",
+ "臧",
+ "臨",
+ "自",
+ "臬",
+ "臭",
+ "至",
+ "致",
+ "臺",
+ "臻",
+ "臼",
+ "臾",
+ "舀",
+ "舁",
+ "舂",
+ "舅",
+ "舆",
+ "與",
+ "興",
+ "舉",
+ "舊",
+ "舌",
+ "舍",
+ "舎",
+ "舐",
+ "舒",
+ "舔",
+ "舖",
+ "舗",
+ "舘",
+ "舛",
+ "舜",
+ "舞",
+ "舟",
+ "舢",
+ "舣",
+ "舩",
+ "航",
+ "舫",
+ "般",
+ "舮",
+ "舯",
+ "舰",
+ "舱",
+ "舲",
+ "舳",
+ "舵",
+ "舶",
+ "舷",
+ "舸",
+ "船",
+ "舾",
+ "艀",
+ "艄",
+ "艇",
+ "艉",
+ "艋",
+ "艏",
+ "艘",
+ "艙",
+ "艟",
+ "艤",
+ "艦",
+ "艨",
+ "艪",
+ "艫",
+ "艮",
+ "良",
+ "艰",
+ "艱",
+ "色",
+ "艳",
+ "艶",
+ "艷",
+ "艸",
+ "艹",
+ "艺",
+ "艽",
+ "艾",
+ "艿",
+ "节",
+ "芃",
+ "芈",
+ "芊",
+ "芋",
+ "芍",
+ "芎",
+ "芑",
+ "芒",
+ "芗",
+ "芘",
+ "芙",
+ "芜",
+ "芝",
+ "芟",
+ "芡",
+ "芣",
+ "芤",
+ "芥",
+ "芦",
+ "芨",
+ "芩",
+ "芪",
+ "芫",
+ "芬",
+ "芭",
+ "芮",
+ "芯",
+ "芰",
+ "花",
+ "芳",
+ "芷",
+ "芸",
+ "芹",
+ "芻",
+ "芽",
+ "芾",
+ "苁",
+ "苄",
+ "苅",
+ "苇",
+ "苈",
+ "苊",
+ "苋",
+ "苌",
+ "苍",
+ "苎",
+ "苏",
+ "苑",
+ "苒",
+ "苓",
+ "苔",
+ "苕",
+ "苗",
+ "苘",
+ "苙",
+ "苛",
+ "苜",
+ "苞",
+ "苟",
+ "苡",
+ "苢",
+ "苣",
+ "苤",
+ "若",
+ "苦",
+ "苧",
+ "苫",
+ "苯",
+ "英",
+ "苳",
+ "苴",
+ "苷",
+ "苹",
+ "苺",
+ "苻",
+ "苼",
+ "苾",
+ "茁",
+ "茂",
+ "范",
+ "茄",
+ "茅",
+ "茆",
+ "茈",
+ "茉",
+ "茌",
+ "茎",
+ "茏",
+ "茑",
+ "茔",
+ "茕",
+ "茗",
+ "茘",
+ "茚",
+ "茛",
+ "茜",
+ "茣",
+ "茧",
+ "茨",
+ "茫",
+ "茬",
+ "茭",
+ "茯",
+ "茱",
+ "茲",
+ "茳",
+ "茴",
+ "茵",
+ "茶",
+ "茸",
+ "茹",
+ "茺",
+ "茼",
+ "荀",
+ "荃",
+ "荅",
+ "荆",
+ "荇",
+ "草",
+ "荊",
+ "荏",
+ "荐",
+ "荑",
+ "荒",
+ "荔",
+ "荘",
+ "荙",
+ "荚",
+ "荛",
+ "荜",
+ "荞",
+ "荟",
+ "荠",
+ "荡",
+ "荣",
+ "荤",
+ "荥",
+ "荦",
+ "荧",
+ "荨",
+ "荩",
+ "荪",
+ "荫",
+ "荬",
+ "药",
+ "荳",
+ "荷",
+ "荸",
+ "荻",
+ "荼",
+ "荽",
+ "莅",
+ "莆",
+ "莇",
+ "莉",
+ "莊",
+ "莎",
+ "莒",
+ "莓",
+ "莕",
+ "莖",
+ "莘",
+ "莙",
+ "莚",
+ "莜",
+ "莞",
+ "莟",
+ "莠",
+ "莢",
+ "莧",
+ "莨",
+ "莩",
+ "莪",
+ "莫",
+ "莱",
+ "莲",
+ "莳",
+ "莴",
+ "莵",
+ "莶",
+ "获",
+ "莸",
+ "莹",
+ "莺",
+ "莼",
+ "莽",
+ "菀",
+ "菁",
+ "菅",
+ "菇",
+ "菉",
+ "菊",
+ "菌",
+ "菎",
+ "菏",
+ "菓",
+ "菔",
+ "菖",
+ "菘",
+ "菜",
+ "菟",
+ "菠",
+ "菡",
+ "菥",
+ "菨",
+ "菩",
+ "菪",
+ "菫",
+ "華",
+ "菰",
+ "菱",
+ "菲",
+ "菴",
+ "菸",
+ "菹",
+ "菽",
+ "萁",
+ "萃",
+ "萄",
+ "萆",
+ "萊",
+ "萋",
+ "萌",
+ "萍",
+ "萎",
+ "萏",
+ "萓",
+ "萘",
+ "萜",
+ "萝",
+ "萠",
+ "萢",
+ "萤",
+ "营",
+ "萦",
+ "萧",
+ "萨",
+ "萩",
+ "萬",
+ "萱",
+ "萵",
+ "萸",
+ "萹",
+ "萼",
+ "落",
+ "葆",
+ "葈",
+ "葉",
+ "葎",
+ "葑",
+ "著",
+ "葙",
+ "葚",
+ "葛",
+ "葡",
+ "董",
+ "葦",
+ "葩",
+ "葫",
+ "葬",
+ "葭",
+ "葯",
+ "葱",
+ "葳",
+ "葵",
+ "葶",
+ "葷",
+ "葸",
+ "葹",
+ "葺",
+ "蒂",
+ "蒄",
+ "蒋",
+ "蒌",
+ "蒎",
+ "蒐",
+ "蒔",
+ "蒗",
+ "蒙",
+ "蒜",
+ "蒟",
+ "蒡",
+ "蒯",
+ "蒲",
+ "蒴",
+ "蒸",
+ "蒹",
+ "蒺",
+ "蒻",
+ "蒼",
+ "蒽",
+ "蒿",
+ "蓀",
+ "蓁",
+ "蓂",
+ "蓄",
+ "蓆",
+ "蓉",
+ "蓊",
+ "蓋",
+ "蓍",
+ "蓐",
+ "蓑",
+ "蓓",
+ "蓖",
+ "蓙",
+ "蓚",
+ "蓝",
+ "蓟",
+ "蓠",
+ "蓣",
+ "蓥",
+ "蓦",
+ "蓬",
+ "蓮",
+ "蓴",
+ "蓼",
+ "蓿",
+ "蔀",
+ "蔌",
+ "蔑",
+ "蔓",
+ "蔔",
+ "蔕",
+ "蔗",
+ "蔚",
+ "蔟",
+ "蔡",
+ "蔣",
+ "蔤",
+ "蔥",
+ "蔦",
+ "蔫",
+ "蔬",
+ "蔭",
+ "蔵",
+ "蔷",
+ "蔸",
+ "蔹",
+ "蔺",
+ "蔻",
+ "蔼",
+ "蔽",
+ "蕁",
+ "蕃",
+ "蕈",
+ "蕉",
+ "蕊",
+ "蕋",
+ "蕎",
+ "蕖",
+ "蕗",
+ "蕙",
+ "蕚",
+ "蕞",
+ "蕣",
+ "蕤",
+ "蕨",
+ "蕩",
+ "蕪",
+ "蕫",
+ "蕭",
+ "蕲",
+ "蕴",
+ "蕷",
+ "蕺",
+ "蕻",
+ "蕾",
+ "薀",
+ "薁",
+ "薄",
+ "薅",
+ "薇",
+ "薈",
+ "薊",
+ "薏",
+ "薐",
+ "薑",
+ "薔",
+ "薗",
+ "薙",
+ "薛",
+ "薜",
+ "薢",
+ "薤",
+ "薦",
+ "薨",
+ "薩",
+ "薪",
+ "薫",
+ "薬",
+ "薭",
+ "薮",
+ "薯",
+ "薰",
+ "薳",
+ "薷",
+ "薹",
+ "薺",
+ "藁",
+ "藉",
+ "藍",
+ "藏",
+ "藐",
+ "藓",
+ "藕",
+ "藜",
+ "藝",
+ "藠",
+ "藤",
+ "藥",
+ "藦",
+ "藩",
+ "藪",
+ "藷",
+ "藹",
+ "藺",
+ "藻",
+ "藿",
+ "蘂",
+ "蘅",
+ "蘆",
+ "蘇",
+ "蘊",
+ "蘋",
+ "蘑",
+ "蘓",
+ "蘖",
+ "蘗",
+ "蘘",
+ "蘚",
+ "蘧",
+ "蘭",
+ "蘰",
+ "蘸",
+ "蘼",
+ "蘿",
+ "虎",
+ "虏",
+ "虐",
+ "虑",
+ "虓",
+ "虔",
+ "處",
+ "虚",
+ "虛",
+ "虜",
+ "虞",
+ "號",
+ "虢",
+ "虧",
+ "虫",
+ "虬",
+ "虮",
+ "虱",
+ "虵",
+ "虹",
+ "虺",
+ "虻",
+ "虽",
+ "虾",
+ "虿",
+ "蚀",
+ "蚁",
+ "蚂",
+ "蚊",
+ "蚋",
+ "蚌",
+ "蚍",
+ "蚓",
+ "蚕",
+ "蚜",
+ "蚝",
+ "蚡",
+ "蚣",
+ "蚤",
+ "蚧",
+ "蚨",
+ "蚩",
+ "蚪",
+ "蚫",
+ "蚬",
+ "蚯",
+ "蚰",
+ "蚱",
+ "蚳",
+ "蚴",
+ "蚵",
+ "蚶",
+ "蛀",
+ "蛄",
+ "蛆",
+ "蛇",
+ "蛉",
+ "蛊",
+ "蛋",
+ "蛍",
+ "蛎",
+ "蛏",
+ "蛐",
+ "蛑",
+ "蛔",
+ "蛘",
+ "蛙",
+ "蛛",
+ "蛞",
+ "蛟",
+ "蛤",
+ "蛩",
+ "蛬",
+ "蛭",
+ "蛮",
+ "蛯",
+ "蛰",
+ "蛱",
+ "蛲",
+ "蛳",
+ "蛴",
+ "蛸",
+ "蛹",
+ "蛻",
+ "蛼",
+ "蛽",
+ "蛾",
+ "蜀",
+ "蜂",
+ "蜃",
+ "蜆",
+ "蜇",
+ "蜈",
+ "蜉",
+ "蜊",
+ "蜍",
+ "蜎",
+ "蜑",
+ "蜒",
+ "蜓",
+ "蜕",
+ "蜗",
+ "蜘",
+ "蜚",
+ "蜛",
+ "蜜",
+ "蜞",
+ "蜡",
+ "蜢",
+ "蜣",
+ "蜥",
+ "蜩",
+ "蜮",
+ "蜱",
+ "蜴",
+ "蜷",
+ "蜻",
+ "蜾",
+ "蜿",
+ "蝇",
+ "蝈",
+ "蝉",
+ "蝋",
+ "蝌",
+ "蝎",
+ "蝓",
+ "蝕",
+ "蝗",
+ "蝘",
+ "蝙",
+ "蝟",
+ "蝠",
+ "蝣",
+ "蝥",
+ "蝦",
+ "蝨",
+ "蝮",
+ "蝰",
+ "蝲",
+ "蝴",
+ "蝶",
+ "蝸",
+ "蝻",
+ "蝼",
+ "蝽",
+ "蝾",
+ "蝿",
+ "螂",
+ "螃",
+ "螅",
+ "螈",
+ "螋",
+ "融",
+ "螞",
+ "螟",
+ "螠",
+ "螢",
+ "螨",
+ "螫",
+ "螬",
+ "螭",
+ "螯",
+ "螳",
+ "螵",
+ "螺",
+ "螻",
+ "螽",
+ "蟀",
+ "蟄",
+ "蟆",
+ "蟇",
+ "蟊",
+ "蟋",
+ "蟐",
+ "蟑",
+ "蟒",
+ "蟛",
+ "蟜",
+ "蟟",
+ "蟠",
+ "蟥",
+ "蟪",
+ "蟬",
+ "蟭",
+ "蟮",
+ "蟯",
+ "蟲",
+ "蟶",
+ "蟷",
+ "蟹",
+ "蟻",
+ "蟾",
+ "蠃",
+ "蠅",
+ "蠊",
+ "蠋",
+ "蠍",
+ "蠎",
+ "蠏",
+ "蠑",
+ "蠓",
+ "蠕",
+ "蠖",
+ "蠛",
+ "蠜",
+ "蠟",
+ "蠡",
+ "蠢",
+ "蠣",
+ "蠧",
+ "蠱",
+ "蠲",
+ "蠶",
+ "蠹",
+ "蠻",
+ "蠼",
+ "血",
+ "衄",
+ "衅",
+ "衆",
+ "行",
+ "衍",
+ "衎",
+ "衒",
+ "術",
+ "衔",
+ "街",
+ "衙",
+ "衛",
+ "衝",
+ "衞",
+ "衡",
+ "衢",
+ "衣",
+ "补",
+ "表",
+ "衩",
+ "衫",
+ "衬",
+ "衮",
+ "衯",
+ "衰",
+ "衲",
+ "衵",
+ "衷",
+ "衽",
+ "衾",
+ "衿",
+ "袁",
+ "袂",
+ "袄",
+ "袅",
+ "袆",
+ "袈",
+ "袋",
+ "袍",
+ "袒",
+ "袓",
+ "袖",
+ "袗",
+ "袙",
+ "袜",
+ "袝",
+ "袞",
+ "袢",
+ "袤",
+ "袪",
+ "被",
+ "袭",
+ "袰",
+ "袱",
+ "袴",
+ "袵",
+ "袷",
+ "袼",
+ "袿",
+ "裁",
+ "裂",
+ "裃",
+ "裄",
+ "装",
+ "裆",
+ "裇",
+ "裉",
+ "裊",
+ "裎",
+ "裏",
+ "裒",
+ "裔",
+ "裕",
+ "裘",
+ "裙",
+ "裛",
+ "補",
+ "裝",
+ "裟",
+ "裡",
+ "裢",
+ "裤",
+ "裥",
+ "裨",
+ "裰",
+ "裱",
+ "裲",
+ "裳",
+ "裴",
+ "裸",
+ "裹",
+ "製",
+ "裾",
+ "褀",
+ "褂",
+ "褄",
+ "複",
+ "褊",
+ "褌",
+ "褐",
+ "褒",
+ "褓",
+ "褔",
+ "褙",
+ "褚",
+ "褛",
+ "褞",
+ "褡",
+ "褥",
+ "褪",
+ "褫",
+ "褭",
+ "褰",
+ "褲",
+ "褴",
+ "褶",
+ "褸",
+ "褻",
+ "襀",
+ "襁",
+ "襄",
+ "襖",
+ "襜",
+ "襞",
+ "襟",
+ "襠",
+ "襤",
+ "襦",
+ "襪",
+ "襯",
+ "襲",
+ "襴",
+ "襷",
+ "襻",
+ "西",
+ "要",
+ "覃",
+ "覆",
+ "覇",
+ "見",
+ "規",
+ "覓",
+ "視",
+ "覗",
+ "覘",
+ "覚",
+ "覡",
+ "覧",
+ "覩",
+ "親",
+ "覯",
+ "覲",
+ "観",
+ "覷",
+ "覺",
+ "覽",
+ "覿",
+ "觀",
+ "见",
+ "观",
+ "规",
+ "觅",
+ "视",
+ "觇",
+ "览",
+ "觉",
+ "觊",
+ "觌",
+ "觎",
+ "觏",
+ "觐",
+ "觑",
+ "角",
+ "觚",
+ "觜",
+ "觝",
+ "觞",
+ "解",
+ "觥",
+ "触",
+ "觫",
+ "觯",
+ "觱",
+ "觳",
+ "觴",
+ "觸",
+ "言",
+ "訂",
+ "訃",
+ "訇",
+ "計",
+ "訊",
+ "訌",
+ "討",
+ "訓",
+ "訕",
+ "託",
+ "記",
+ "訚",
+ "訛",
+ "訝",
+ "訟",
+ "訢",
+ "訣",
+ "訥",
+ "訪",
+ "設",
+ "許",
+ "訳",
+ "訴",
+ "訶",
+ "診",
+ "註",
+ "証",
+ "訾",
+ "詁",
+ "詈",
+ "詐",
+ "詒",
+ "詔",
+ "評",
+ "詛",
+ "詝",
+ "詞",
+ "詠",
+ "詢",
+ "詣",
+ "試",
+ "詩",
+ "詫",
+ "詬",
+ "詭",
+ "詮",
+ "詰",
+ "話",
+ "該",
+ "詳",
+ "詹",
+ "誂",
+ "誄",
+ "誅",
+ "誇",
+ "誉",
+ "誊",
+ "誌",
+ "認",
+ "誑",
+ "誒",
+ "誓",
+ "誕",
+ "誘",
+ "語",
+ "誠",
+ "誡",
+ "誣",
+ "誤",
+ "誥",
+ "誦",
+ "誨",
+ "說",
+ "説",
+ "読",
+ "誰",
+ "課",
+ "誹",
+ "誼",
+ "調",
+ "諂",
+ "諄",
+ "談",
+ "請",
+ "諌",
+ "諍",
+ "諏",
+ "諒",
+ "論",
+ "諗",
+ "諚",
+ "諛",
+ "諜",
+ "諡",
+ "諢",
+ "諤",
+ "諦",
+ "諧",
+ "諫",
+ "諭",
+ "諮",
+ "諱",
+ "諳",
+ "諷",
+ "諸",
+ "諺",
+ "諼",
+ "諾",
+ "謀",
+ "謁",
+ "謂",
+ "謄",
+ "謇",
+ "謊",
+ "謎",
+ "謐",
+ "謔",
+ "謖",
+ "謗",
+ "謙",
+ "謚",
+ "講",
+ "謝",
+ "謠",
+ "謡",
+ "謦",
+ "謨",
+ "謩",
+ "謫",
+ "謬",
+ "謳",
+ "謷",
+ "謹",
+ "譁",
+ "證",
+ "譎",
+ "譏",
+ "譖",
+ "識",
+ "譚",
+ "譜",
+ "譞",
+ "譟",
+ "警",
+ "譫",
+ "譬",
+ "譯",
+ "議",
+ "譲",
+ "譴",
+ "護",
+ "譽",
+ "讀",
+ "讃",
+ "變",
+ "讌",
+ "讎",
+ "讐",
+ "讒",
+ "讓",
+ "讖",
+ "讚",
+ "讠",
+ "计",
+ "订",
+ "讣",
+ "认",
+ "讥",
+ "讦",
+ "讧",
+ "讨",
+ "让",
+ "讪",
+ "讫",
+ "训",
+ "议",
+ "讯",
+ "记",
+ "讲",
+ "讳",
+ "讴",
+ "讵",
+ "讶",
+ "讷",
+ "许",
+ "讹",
+ "论",
+ "讼",
+ "讽",
+ "设",
+ "访",
+ "诀",
+ "证",
+ "诂",
+ "诃",
+ "评",
+ "诅",
+ "识",
+ "诈",
+ "诉",
+ "诊",
+ "诋",
+ "诌",
+ "词",
+ "诎",
+ "诏",
+ "诐",
+ "译",
+ "诒",
+ "诓",
+ "诔",
+ "试",
+ "诖",
+ "诗",
+ "诘",
+ "诙",
+ "诚",
+ "诛",
+ "诜",
+ "话",
+ "诞",
+ "诟",
+ "诠",
+ "诡",
+ "询",
+ "诣",
+ "诤",
+ "该",
+ "详",
+ "诧",
+ "诨",
+ "诩",
+ "诫",
+ "诬",
+ "语",
+ "诮",
+ "误",
+ "诰",
+ "诱",
+ "诲",
+ "诳",
+ "说",
+ "诵",
+ "诶",
+ "请",
+ "诸",
+ "诹",
+ "诺",
+ "读",
+ "诼",
+ "诽",
+ "课",
+ "诿",
+ "谀",
+ "谁",
+ "谂",
+ "调",
+ "谄",
+ "谅",
+ "谆",
+ "谈",
+ "谊",
+ "谋",
+ "谌",
+ "谍",
+ "谎",
+ "谏",
+ "谐",
+ "谑",
+ "谒",
+ "谓",
+ "谔",
+ "谕",
+ "谖",
+ "谗",
+ "谘",
+ "谙",
+ "谚",
+ "谛",
+ "谜",
+ "谝",
+ "谞",
+ "谟",
+ "谠",
+ "谡",
+ "谢",
+ "谣",
+ "谤",
+ "谥",
+ "谦",
+ "谧",
+ "谨",
+ "谩",
+ "谪",
+ "谬",
+ "谭",
+ "谮",
+ "谯",
+ "谰",
+ "谱",
+ "谲",
+ "谳",
+ "谴",
+ "谵",
+ "谶",
+ "谷",
+ "谺",
+ "谿",
+ "豁",
+ "豅",
+ "豆",
+ "豇",
+ "豈",
+ "豉",
+ "豊",
+ "豌",
+ "豎",
+ "豐",
+ "豔",
+ "豕",
+ "豚",
+ "豛",
+ "豝",
+ "象",
+ "豢",
+ "豨",
+ "豪",
+ "豫",
+ "豬",
+ "豳",
+ "豸",
+ "豹",
+ "豺",
+ "貂",
+ "貅",
+ "貉",
+ "貊",
+ "貌",
+ "貓",
+ "貔",
+ "貘",
+ "貝",
+ "貞",
+ "負",
+ "財",
+ "貢",
+ "貧",
+ "貨",
+ "販",
+ "貪",
+ "貫",
+ "責",
+ "貯",
+ "貰",
+ "貲",
+ "貳",
+ "貴",
+ "貶",
+ "買",
+ "貸",
+ "費",
+ "貼",
+ "貽",
+ "貿",
+ "賀",
+ "賁",
+ "賂",
+ "賃",
+ "賄",
+ "資",
+ "賈",
+ "賊",
+ "賎",
+ "賑",
+ "賒",
+ "賓",
+ "賚",
+ "賛",
+ "賜",
+ "賞",
+ "賠",
+ "賢",
+ "賣",
+ "賤",
+ "賦",
+ "質",
+ "賬",
+ "賭",
+ "賴",
+ "賺",
+ "購",
+ "賽",
+ "贄",
+ "贅",
+ "贇",
+ "贈",
+ "贊",
+ "贋",
+ "贏",
+ "贐",
+ "贓",
+ "贔",
+ "贖",
+ "贝",
+ "贞",
+ "负",
+ "贡",
+ "财",
+ "责",
+ "贤",
+ "败",
+ "账",
+ "货",
+ "质",
+ "贩",
+ "贪",
+ "贫",
+ "贬",
+ "购",
+ "贮",
+ "贯",
+ "贰",
+ "贱",
+ "贲",
+ "贴",
+ "贵",
+ "贶",
+ "贷",
+ "贸",
+ "费",
+ "贺",
+ "贻",
+ "贼",
+ "贽",
+ "贾",
+ "贿",
+ "赁",
+ "赂",
+ "赃",
+ "资",
+ "赅",
+ "赈",
+ "赉",
+ "赊",
+ "赋",
+ "赌",
+ "赍",
+ "赎",
+ "赏",
+ "赐",
+ "赓",
+ "赔",
+ "赕",
+ "赖",
+ "赘",
+ "赙",
+ "赚",
+ "赛",
+ "赜",
+ "赝",
+ "赞",
+ "赟",
+ "赠",
+ "赡",
+ "赢",
+ "赣",
+ "赤",
+ "赦",
+ "赧",
+ "赪",
+ "赫",
+ "赬",
+ "赭",
+ "走",
+ "赳",
+ "赴",
+ "赵",
+ "赶",
+ "起",
+ "趁",
+ "趄",
+ "超",
+ "越",
+ "趋",
+ "趔",
+ "趕",
+ "趙",
+ "趟",
+ "趣",
+ "趨",
+ "足",
+ "趴",
+ "趵",
+ "趸",
+ "趺",
+ "趾",
+ "趿",
+ "跂",
+ "跃",
+ "跄",
+ "跆",
+ "跋",
+ "跌",
+ "跎",
+ "跏",
+ "跑",
+ "跖",
+ "跗",
+ "跚",
+ "跛",
+ "距",
+ "跞",
+ "跟",
+ "跡",
+ "跣",
+ "跤",
+ "跨",
+ "跩",
+ "跪",
+ "跫",
+ "跬",
+ "路",
+ "跱",
+ "跳",
+ "践",
+ "跶",
+ "跷",
+ "跸",
+ "跹",
+ "跺",
+ "跻",
+ "跼",
+ "跽",
+ "跿",
+ "踅",
+ "踉",
+ "踊",
+ "踌",
+ "踎",
+ "踏",
+ "踐",
+ "踔",
+ "踖",
+ "踝",
+ "踞",
+ "踟",
+ "踡",
+ "踢",
+ "踣",
+ "踦",
+ "踧",
+ "踩",
+ "踪",
+ "踬",
+ "踭",
+ "踮",
+ "踯",
+ "踰",
+ "踱",
+ "踴",
+ "踵",
+ "踹",
+ "踺",
+ "踽",
+ "蹀",
+ "蹁",
+ "蹂",
+ "蹄",
+ "蹇",
+ "蹈",
+ "蹉",
+ "蹊",
+ "蹋",
+ "蹌",
+ "蹐",
+ "蹑",
+ "蹒",
+ "蹕",
+ "蹙",
+ "蹚",
+ "蹟",
+ "蹠",
+ "蹡",
+ "蹣",
+ "蹤",
+ "蹦",
+ "蹩",
+ "蹬",
+ "蹭",
+ "蹯",
+ "蹰",
+ "蹲",
+ "蹴",
+ "蹶",
+ "蹼",
+ "蹽",
+ "蹿",
+ "躁",
+ "躄",
+ "躅",
+ "躇",
+ "躊",
+ "躍",
+ "躏",
+ "躐",
+ "躑",
+ "躓",
+ "躔",
+ "躙",
+ "躜",
+ "躡",
+ "躪",
+ "身",
+ "躬",
+ "躯",
+ "躰",
+ "躱",
+ "躲",
+ "躺",
+ "躾",
+ "軀",
+ "軈",
+ "車",
+ "軋",
+ "軌",
+ "軍",
+ "軎",
+ "軒",
+ "軛",
+ "軟",
+ "転",
+ "軣",
+ "軫",
+ "軸",
+ "軻",
+ "軼",
+ "軽",
+ "較",
+ "載",
+ "輊",
+ "輌",
+ "輒",
+ "輓",
+ "輔",
+ "輕",
+ "輛",
+ "輜",
+ "輝",
+ "輦",
+ "輩",
+ "輪",
+ "輯",
+ "輳",
+ "輶",
+ "輸",
+ "輻",
+ "輾",
+ "輿",
+ "轂",
+ "轄",
+ "轅",
+ "轆",
+ "轉",
+ "轌",
+ "轍",
+ "轎",
+ "轗",
+ "轟",
+ "轡",
+ "轢",
+ "轣",
+ "轤",
+ "车",
+ "轧",
+ "轨",
+ "轩",
+ "轫",
+ "转",
+ "轭",
+ "轮",
+ "软",
+ "轰",
+ "轱",
+ "轲",
+ "轳",
+ "轴",
+ "轵",
+ "轶",
+ "轸",
+ "轹",
+ "轺",
+ "轻",
+ "轼",
+ "载",
+ "轾",
+ "轿",
+ "辂",
+ "较",
+ "辄",
+ "辅",
+ "辆",
+ "辇",
+ "辈",
+ "辉",
+ "辊",
+ "辋",
+ "辍",
+ "辎",
+ "辏",
+ "辐",
+ "辑",
+ "输",
+ "辔",
+ "辕",
+ "辖",
+ "辗",
+ "辘",
+ "辙",
+ "辚",
+ "辛",
+ "辜",
+ "辞",
+ "辟",
+ "辣",
+ "辦",
+ "辨",
+ "辩",
+ "辫",
+ "辭",
+ "辮",
+ "辯",
+ "辰",
+ "辱",
+ "農",
+ "辷",
+ "边",
+ "辺",
+ "辻",
+ "込",
+ "辽",
+ "达",
+ "辿",
+ "迁",
+ "迂",
+ "迄",
+ "迅",
+ "过",
+ "迈",
+ "迎",
+ "运",
+ "近",
+ "迓",
+ "返",
+ "迕",
+ "还",
+ "这",
+ "迚",
+ "进",
+ "远",
+ "违",
+ "连",
+ "迟",
+ "迠",
+ "迢",
+ "迤",
+ "迥",
+ "迦",
+ "迨",
+ "迩",
+ "迪",
+ "迫",
+ "迭",
+ "迮",
+ "述",
+ "迳",
+ "迴",
+ "迷",
+ "迸",
+ "迹",
+ "追",
+ "退",
+ "送",
+ "适",
+ "逃",
+ "逄",
+ "逅",
+ "逆",
+ "选",
+ "逊",
+ "逋",
+ "逍",
+ "透",
+ "逐",
+ "逑",
+ "递",
+ "逓",
+ "途",
+ "逕",
+ "逖",
+ "逗",
+ "這",
+ "通",
+ "逛",
+ "逝",
+ "逞",
+ "速",
+ "造",
+ "逡",
+ "逢",
+ "連",
+ "逦",
+ "逮",
+ "逯",
+ "週",
+ "進",
+ "逵",
+ "逶",
+ "逸",
+ "逻",
+ "逼",
+ "逾",
+ "遁",
+ "遂",
+ "遄",
+ "遅",
+ "遇",
+ "遉",
+ "遊",
+ "運",
+ "遍",
+ "過",
+ "遏",
+ "遐",
+ "遑",
+ "遒",
+ "道",
+ "達",
+ "違",
+ "遖",
+ "遗",
+ "遘",
+ "遙",
+ "遛",
+ "遜",
+ "遞",
+ "遠",
+ "遡",
+ "遢",
+ "遣",
+ "遥",
+ "遨",
+ "適",
+ "遭",
+ "遮",
+ "遯",
+ "遲",
+ "遴",
+ "遵",
+ "遷",
+ "選",
+ "遹",
+ "遺",
+ "遼",
+ "遽",
+ "避",
+ "邀",
+ "邁",
+ "邂",
+ "邃",
+ "還",
+ "邅",
+ "邇",
+ "邈",
+ "邉",
+ "邊",
+ "邋",
+ "邏",
+ "邑",
+ "邓",
+ "邕",
+ "邗",
+ "邘",
+ "邙",
+ "邛",
+ "邝",
+ "邠",
+ "邡",
+ "邢",
+ "那",
+ "邦",
+ "邨",
+ "邪",
+ "邬",
+ "邮",
+ "邯",
+ "邰",
+ "邱",
+ "邳",
+ "邴",
+ "邵",
+ "邶",
+ "邸",
+ "邹",
+ "邺",
+ "邻",
+ "邽",
+ "邾",
+ "郁",
+ "郃",
+ "郄",
+ "郅",
+ "郇",
+ "郊",
+ "郎",
+ "郏",
+ "郐",
+ "郑",
+ "郓",
+ "郕",
+ "郛",
+ "郜",
+ "郝",
+ "郞",
+ "郡",
+ "郢",
+ "郤",
+ "郦",
+ "郧",
+ "部",
+ "郫",
+ "郭",
+ "郯",
+ "郴",
+ "郵",
+ "郷",
+ "郸",
+ "都",
+ "郾",
+ "郿",
+ "鄂",
+ "鄄",
+ "鄅",
+ "鄉",
+ "鄏",
+ "鄒",
+ "鄘",
+ "鄙",
+ "鄚",
+ "鄜",
+ "鄞",
+ "鄠",
+ "鄢",
+ "鄣",
+ "鄧",
+ "鄩",
+ "鄫",
+ "鄭",
+ "鄮",
+ "鄯",
+ "鄰",
+ "鄱",
+ "鄲",
+ "鄺",
+ "酆",
+ "酉",
+ "酊",
+ "酋",
+ "酌",
+ "配",
+ "酎",
+ "酐",
+ "酒",
+ "酔",
+ "酗",
+ "酘",
+ "酚",
+ "酝",
+ "酞",
+ "酡",
+ "酢",
+ "酣",
+ "酤",
+ "酥",
+ "酩",
+ "酪",
+ "酫",
+ "酬",
+ "酮",
+ "酯",
+ "酰",
+ "酱",
+ "酵",
+ "酶",
+ "酷",
+ "酸",
+ "酹",
+ "酺",
+ "酽",
+ "酿",
+ "醂",
+ "醅",
+ "醇",
+ "醉",
+ "醋",
+ "醌",
+ "醍",
+ "醐",
+ "醒",
+ "醗",
+ "醚",
+ "醛",
+ "醜",
+ "醞",
+ "醢",
+ "醣",
+ "醤",
+ "醪",
+ "醫",
+ "醬",
+ "醭",
+ "醮",
+ "醯",
+ "醲",
+ "醴",
+ "醵",
+ "醸",
+ "醺",
+ "釀",
+ "釁",
+ "釆",
+ "采",
+ "釈",
+ "釉",
+ "释",
+ "釋",
+ "里",
+ "重",
+ "野",
+ "量",
+ "釐",
+ "金",
+ "釘",
+ "釛",
+ "釜",
+ "針",
+ "釡",
+ "釣",
+ "釦",
+ "釧",
+ "釭",
+ "釵",
+ "釶",
+ "釼",
+ "釿",
+ "鈇",
+ "鈍",
+ "鈎",
+ "鈑",
+ "鈔",
+ "鈕",
+ "鈞",
+ "鈩",
+ "鈪",
+ "鈳",
+ "鈴",
+ "鈷",
+ "鈿",
+ "鉄",
+ "鉈",
+ "鉉",
+ "鉋",
+ "鉏",
+ "鉗",
+ "鉛",
+ "鉞",
+ "鉢",
+ "鉤",
+ "鉦",
+ "鉱",
+ "鉴",
+ "鉾",
+ "銀",
+ "銃",
+ "銅",
+ "銑",
+ "銓",
+ "銕",
+ "銖",
+ "銘",
+ "銚",
+ "銛",
+ "銜",
+ "銭",
+ "銮",
+ "銳",
+ "銶",
+ "銷",
+ "銹",
+ "鋆",
+ "鋈",
+ "鋏",
+ "鋐",
+ "鋒",
+ "鋤",
+ "鋩",
+ "鋪",
+ "鋭",
+ "鋲",
+ "鋳",
+ "鋸",
+ "鋹",
+ "鋺",
+ "鋼",
+ "錄",
+ "錆",
+ "錏",
+ "錐",
+ "錘",
+ "錙",
+ "錚",
+ "錞",
+ "錠",
+ "錢",
+ "錣",
+ "錦",
+ "錨",
+ "錫",
+ "錬",
+ "錮",
+ "錯",
+ "録",
+ "錵",
+ "錶",
+ "錺",
+ "錾",
+ "鍉",
+ "鍊",
+ "鍋",
+ "鍍",
+ "鍒",
+ "鍔",
+ "鍛",
+ "鍜",
+ "鍥",
+ "鍪",
+ "鍬",
+ "鍮",
+ "鍵",
+ "鍼",
+ "鍾",
+ "鎉",
+ "鎊",
+ "鎌",
+ "鎏",
+ "鎔",
+ "鎖",
+ "鎗",
+ "鎚",
+ "鎛",
+ "鎧",
+ "鎬",
+ "鎭",
+ "鎮",
+ "鎰",
+ "鎸",
+ "鎹",
+ "鏃",
+ "鏈",
+ "鏊",
+ "鏐",
+ "鏑",
+ "鏖",
+ "鏗",
+ "鏘",
+ "鏝",
+ "鏟",
+ "鏡",
+ "鏤",
+ "鏥",
+ "鏨",
+ "鐃",
+ "鐇",
+ "鐎",
+ "鐐",
+ "鐔",
+ "鐘",
+ "鐙",
+ "鐚",
+ "鐡",
+ "鐧",
+ "鐮",
+ "鐲",
+ "鐵",
+ "鐶",
+ "鐸",
+ "鐺",
+ "鑁",
+ "鑄",
+ "鑊",
+ "鑑",
+ "鑒",
+ "鑓",
+ "鑛",
+ "鑞",
+ "鑠",
+ "鑢",
+ "鑪",
+ "鑫",
+ "鑰",
+ "鑱",
+ "鑲",
+ "鑵",
+ "鑷",
+ "鑹",
+ "鑼",
+ "鑽",
+ "鑿",
+ "钇",
+ "针",
+ "钉",
+ "钊",
+ "钋",
+ "钌",
+ "钍",
+ "钎",
+ "钏",
+ "钐",
+ "钒",
+ "钓",
+ "钔",
+ "钕",
+ "钗",
+ "钘",
+ "钙",
+ "钚",
+ "钛",
+ "钜",
+ "钝",
+ "钞",
+ "钟",
+ "钠",
+ "钡",
+ "钢",
+ "钣",
+ "钤",
+ "钥",
+ "钦",
+ "钧",
+ "钨",
+ "钩",
+ "钪",
+ "钫",
+ "钬",
+ "钮",
+ "钯",
+ "钰",
+ "钱",
+ "钲",
+ "钳",
+ "钴",
+ "钵",
+ "钹",
+ "钺",
+ "钻",
+ "钼",
+ "钽",
+ "钾",
+ "钿",
+ "铀",
+ "铁",
+ "铂",
+ "铃",
+ "铄",
+ "铅",
+ "铆",
+ "铈",
+ "铉",
+ "铊",
+ "铋",
+ "铌",
+ "铍",
+ "铎",
+ "铐",
+ "铑",
+ "铒",
+ "铓",
+ "铖",
+ "铗",
+ "铙",
+ "铚",
+ "铛",
+ "铜",
+ "铝",
+ "铞",
+ "铟",
+ "铠",
+ "铡",
+ "铢",
+ "铣",
+ "铤",
+ "铥",
+ "铦",
+ "铧",
+ "铨",
+ "铩",
+ "铪",
+ "铫",
+ "铬",
+ "铭",
+ "铮",
+ "铯",
+ "铰",
+ "铱",
+ "铲",
+ "铳",
+ "铵",
+ "银",
+ "铷",
+ "铸",
+ "铺",
+ "铼",
+ "链",
+ "铿",
+ "销",
+ "锁",
+ "锂",
+ "锃",
+ "锄",
+ "锅",
+ "锆",
+ "锇",
+ "锈",
+ "锉",
+ "锊",
+ "锋",
+ "锌",
+ "锍",
+ "锏",
+ "锐",
+ "锑",
+ "锒",
+ "锔",
+ "锕",
+ "锖",
+ "锗",
+ "锘",
+ "错",
+ "锚",
+ "锛",
+ "锜",
+ "锝",
+ "锞",
+ "锟",
+ "锡",
+ "锢",
+ "锣",
+ "锤",
+ "锥",
+ "锦",
+ "锨",
+ "锩",
+ "锫",
+ "锬",
+ "锭",
+ "键",
+ "锯",
+ "锰",
+ "锱",
+ "锲",
+ "锴",
+ "锵",
+ "锶",
+ "锷",
+ "锸",
+ "锹",
+ "锺",
+ "锻",
+ "镀",
+ "镁",
+ "镂",
+ "镅",
+ "镆",
+ "镇",
+ "镉",
+ "镊",
+ "镋",
+ "镌",
+ "镍",
+ "镏",
+ "镐",
+ "镑",
+ "镒",
+ "镔",
+ "镕",
+ "镖",
+ "镗",
+ "镘",
+ "镛",
+ "镜",
+ "镝",
+ "镞",
+ "镟",
+ "镠",
+ "镡",
+ "镢",
+ "镣",
+ "镥",
+ "镧",
+ "镩",
+ "镪",
+ "镫",
+ "镬",
+ "镭",
+ "镯",
+ "镰",
+ "镱",
+ "镲",
+ "镳",
+ "镵",
+ "镶",
+ "長",
+ "长",
+ "門",
+ "閂",
+ "閃",
+ "閇",
+ "閉",
+ "閊",
+ "開",
+ "閎",
+ "閏",
+ "閑",
+ "閒",
+ "間",
+ "閔",
+ "閖",
+ "閘",
+ "閟",
+ "関",
+ "閣",
+ "閤",
+ "閥",
+ "閦",
+ "閨",
+ "閭",
+ "閱",
+ "閲",
+ "閹",
+ "閻",
+ "閼",
+ "閾",
+ "闃",
+ "闆",
+ "闇",
+ "闊",
+ "闌",
+ "闍",
+ "闕",
+ "闖",
+ "闘",
+ "關",
+ "闡",
+ "闢",
+ "闥",
+ "门",
+ "闩",
+ "闪",
+ "闫",
+ "闭",
+ "问",
+ "闯",
+ "闰",
+ "闱",
+ "闲",
+ "闳",
+ "间",
+ "闵",
+ "闷",
+ "闸",
+ "闹",
+ "闺",
+ "闻",
+ "闼",
+ "闽",
+ "闾",
+ "闿",
+ "阀",
+ "阁",
+ "阂",
+ "阃",
+ "阄",
+ "阅",
+ "阆",
+ "阇",
+ "阈",
+ "阉",
+ "阊",
+ "阋",
+ "阌",
+ "阍",
+ "阎",
+ "阏",
+ "阐",
+ "阑",
+ "阒",
+ "阔",
+ "阕",
+ "阖",
+ "阗",
+ "阙",
+ "阚",
+ "阜",
+ "阝",
+ "队",
+ "阡",
+ "阨",
+ "阪",
+ "阬",
+ "阮",
+ "阱",
+ "防",
+ "阳",
+ "阴",
+ "阵",
+ "阶",
+ "阻",
+ "阼",
+ "阽",
+ "阿",
+ "陀",
+ "陂",
+ "附",
+ "际",
+ "陆",
+ "陇",
+ "陈",
+ "陉",
+ "陋",
+ "陌",
+ "降",
+ "限",
+ "陔",
+ "陕",
+ "陛",
+ "陜",
+ "陝",
+ "陞",
+ "陟",
+ "陡",
+ "院",
+ "陣",
+ "除",
+ "陥",
+ "陦",
+ "陧",
+ "陨",
+ "险",
+ "陪",
+ "陬",
+ "陰",
+ "陲",
+ "陳",
+ "陵",
+ "陶",
+ "陷",
+ "陸",
+ "険",
+ "陽",
+ "隅",
+ "隆",
+ "隈",
+ "隊",
+ "隋",
+ "隍",
+ "階",
+ "随",
+ "隐",
+ "隔",
+ "隕",
+ "隗",
+ "隘",
+ "隙",
+ "際",
+ "障",
+ "隠",
+ "隣",
+ "隧",
+ "隨",
+ "險",
+ "隰",
+ "隱",
+ "隲",
+ "隳",
+ "隶",
+ "隷",
+ "隸",
+ "隹",
+ "隻",
+ "隼",
+ "隽",
+ "难",
+ "雀",
+ "雁",
+ "雄",
+ "雅",
+ "集",
+ "雇",
+ "雉",
+ "雋",
+ "雌",
+ "雍",
+ "雎",
+ "雏",
+ "雑",
+ "雒",
+ "雕",
+ "雖",
+ "雙",
+ "雛",
+ "雜",
+ "雞",
+ "雠",
+ "離",
+ "難",
+ "雨",
+ "雩",
+ "雪",
+ "雫",
+ "雯",
+ "雰",
+ "雱",
+ "雲",
+ "雳",
+ "零",
+ "雷",
+ "雹",
+ "電",
+ "雾",
+ "需",
+ "霁",
+ "霄",
+ "霆",
+ "震",
+ "霈",
+ "霉",
+ "霊",
+ "霍",
+ "霎",
+ "霏",
+ "霑",
+ "霓",
+ "霖",
+ "霙",
+ "霜",
+ "霞",
+ "霧",
+ "霪",
+ "霫",
+ "霭",
+ "霰",
+ "露",
+ "霸",
+ "霹",
+ "霽",
+ "霾",
+ "靂",
+ "靄",
+ "靆",
+ "靈",
+ "靉",
+ "靑",
+ "青",
+ "靓",
+ "靖",
+ "静",
+ "靚",
+ "靛",
+ "靜",
+ "非",
+ "靠",
+ "靡",
+ "面",
+ "靥",
+ "靦",
+ "靨",
+ "革",
+ "靫",
+ "靭",
+ "靱",
+ "靳",
+ "靴",
+ "靶",
+ "靸",
+ "靹",
+ "靺",
+ "靼",
+ "鞁",
+ "鞄",
+ "鞅",
+ "鞆",
+ "鞋",
+ "鞍",
+ "鞏",
+ "鞐",
+ "鞑",
+ "鞘",
+ "鞜",
+ "鞠",
+ "鞣",
+ "鞥",
+ "鞦",
+ "鞧",
+ "鞨",
+ "鞫",
+ "鞬",
+ "鞭",
+ "鞴",
+ "鞶",
+ "韂",
+ "韃",
+ "韋",
+ "韌",
+ "韓",
+ "韘",
+ "韜",
+ "韡",
+ "韦",
+ "韧",
+ "韩",
+ "韪",
+ "韫",
+ "韬",
+ "韭",
+ "韮",
+ "韲",
+ "音",
+ "韵",
+ "韶",
+ "韻",
+ "響",
+ "頁",
+ "頂",
+ "頃",
+ "項",
+ "順",
+ "須",
+ "頌",
+ "頏",
+ "預",
+ "頑",
+ "頒",
+ "頓",
+ "頗",
+ "領",
+ "頚",
+ "頠",
+ "頡",
+ "頤",
+ "頫",
+ "頬",
+ "頭",
+ "頰",
+ "頴",
+ "頷",
+ "頸",
+ "頹",
+ "頻",
+ "頼",
+ "頽",
+ "顆",
+ "顋",
+ "題",
+ "額",
+ "顎",
+ "顏",
+ "顒",
+ "顔",
+ "顕",
+ "顗",
+ "願",
+ "顛",
+ "類",
+ "顧",
+ "顫",
+ "顬",
+ "顯",
+ "顰",
+ "顱",
+ "顳",
+ "顴",
+ "页",
+ "顶",
+ "顷",
+ "顸",
+ "项",
+ "顺",
+ "须",
+ "顼",
+ "顽",
+ "顾",
+ "顿",
+ "颀",
+ "颁",
+ "颂",
+ "预",
+ "颅",
+ "领",
+ "颇",
+ "颈",
+ "颉",
+ "颊",
+ "颋",
+ "颌",
+ "颍",
+ "颎",
+ "颏",
+ "颐",
+ "频",
+ "颓",
+ "颔",
+ "颖",
+ "颗",
+ "题",
+ "颙",
+ "颚",
+ "颛",
+ "颜",
+ "额",
+ "颞",
+ "颟",
+ "颠",
+ "颡",
+ "颢",
+ "颤",
+ "颦",
+ "颧",
+ "風",
+ "颪",
+ "颯",
+ "颱",
+ "颶",
+ "飄",
+ "飆",
+ "飊",
+ "风",
+ "飐",
+ "飒",
+ "飓",
+ "飕",
+ "飖",
+ "飗",
+ "飘",
+ "飙",
+ "飚",
+ "飛",
+ "飞",
+ "食",
+ "飢",
+ "飧",
+ "飨",
+ "飩",
+ "飪",
+ "飫",
+ "飭",
+ "飯",
+ "飲",
+ "飴",
+ "飼",
+ "飽",
+ "飾",
+ "餃",
+ "餅",
+ "餉",
+ "養",
+ "餌",
+ "餍",
+ "餐",
+ "餑",
+ "餒",
+ "餓",
+ "餘",
+ "餚",
+ "餝",
+ "餞",
+ "餠",
+ "餡",
+ "館",
+ "餬",
+ "餮",
+ "餵",
+ "餸",
+ "饂",
+ "饅",
+ "饉",
+ "饋",
+ "饌",
+ "饐",
+ "饑",
+ "饒",
+ "饔",
+ "饕",
+ "饗",
+ "饤",
+ "饥",
+ "饧",
+ "饨",
+ "饪",
+ "饬",
+ "饭",
+ "饮",
+ "饯",
+ "饰",
+ "饱",
+ "饲",
+ "饴",
+ "饵",
+ "饶",
+ "饷",
+ "饸",
+ "饹",
+ "饺",
+ "饼",
+ "饽",
+ "饿",
+ "馀",
+ "馁",
+ "馃",
+ "馄",
+ "馅",
+ "馆",
+ "馇",
+ "馈",
+ "馊",
+ "馋",
+ "馍",
+ "馏",
+ "馐",
+ "馑",
+ "馒",
+ "馓",
+ "馔",
+ "馕",
+ "首",
+ "馗",
+ "馘",
+ "香",
+ "馥",
+ "馨",
+ "馬",
+ "馭",
+ "馮",
+ "馳",
+ "馴",
+ "馿",
+ "駁",
+ "駃",
+ "駄",
+ "駅",
+ "駆",
+ "駈",
+ "駐",
+ "駑",
+ "駒",
+ "駕",
+ "駘",
+ "駛",
+ "駝",
+ "駟",
+ "駢",
+ "駭",
+ "駮",
+ "駱",
+ "駸",
+ "駻",
+ "駿",
+ "騁",
+ "騎",
+ "騏",
+ "騑",
+ "騒",
+ "験",
+ "騕",
+ "騖",
+ "騙",
+ "騠",
+ "騨",
+ "騮",
+ "騰",
+ "騷",
+ "騾",
+ "驀",
+ "驃",
+ "驅",
+ "驍",
+ "驕",
+ "驗",
+ "驚",
+ "驛",
+ "驟",
+ "驢",
+ "驥",
+ "驩",
+ "驪",
+ "驫",
+ "马",
+ "驭",
+ "驮",
+ "驯",
+ "驰",
+ "驱",
+ "驳",
+ "驴",
+ "驶",
+ "驷",
+ "驸",
+ "驹",
+ "驺",
+ "驻",
+ "驼",
+ "驽",
+ "驾",
+ "驿",
+ "骀",
+ "骁",
+ "骂",
+ "骄",
+ "骅",
+ "骆",
+ "骇",
+ "骈",
+ "骊",
+ "骋",
+ "验",
+ "骍",
+ "骎",
+ "骏",
+ "骐",
+ "骑",
+ "骒",
+ "骓",
+ "骕",
+ "骖",
+ "骗",
+ "骘",
+ "骚",
+ "骛",
+ "骜",
+ "骝",
+ "骞",
+ "骟",
+ "骠",
+ "骡",
+ "骢",
+ "骤",
+ "骥",
+ "骧",
+ "骨",
+ "骯",
+ "骰",
+ "骶",
+ "骷",
+ "骸",
+ "骺",
+ "骼",
+ "髀",
+ "髁",
+ "髂",
+ "髃",
+ "髄",
+ "髅",
+ "髈",
+ "髋",
+ "髌",
+ "髎",
+ "髏",
+ "髑",
+ "髒",
+ "髓",
+ "體",
+ "高",
+ "髙",
+ "髟",
+ "髡",
+ "髢",
+ "髣",
+ "髦",
+ "髪",
+ "髫",
+ "髭",
+ "髮",
+ "髯",
+ "髱",
+ "髴",
+ "髷",
+ "髹",
+ "髻",
+ "髽",
+ "鬃",
+ "鬄",
+ "鬆",
+ "鬍",
+ "鬏",
+ "鬐",
+ "鬓",
+ "鬘",
+ "鬚",
+ "鬟",
+ "鬢",
+ "鬣",
+ "鬥",
+ "鬧",
+ "鬨",
+ "鬩",
+ "鬮",
+ "鬯",
+ "鬱",
+ "鬲",
+ "鬶",
+ "鬻",
+ "鬼",
+ "魁",
+ "魂",
+ "魃",
+ "魄",
+ "魅",
+ "魇",
+ "魈",
+ "魉",
+ "魍",
+ "魎",
+ "魏",
+ "魑",
+ "魔",
+ "魘",
+ "魚",
+ "魟",
+ "魣",
+ "魦",
+ "魬",
+ "魯",
+ "魳",
+ "魴",
+ "魵",
+ "鮀",
+ "鮃",
+ "鮄",
+ "鮉",
+ "鮊",
+ "鮋",
+ "鮎",
+ "鮏",
+ "鮐",
+ "鮑",
+ "鮒",
+ "鮓",
+ "鮔",
+ "鮖",
+ "鮗",
+ "鮟",
+ "鮠",
+ "鮧",
+ "鮨",
+ "鮪",
+ "鮫",
+ "鮭",
+ "鮮",
+ "鮱",
+ "鮲",
+ "鮴",
+ "鮸",
+ "鮹",
+ "鯀",
+ "鯆",
+ "鯇",
+ "鯉",
+ "鯊",
+ "鯎",
+ "鯏",
+ "鯑",
+ "鯒",
+ "鯔",
+ "鯖",
+ "鯛",
+ "鯡",
+ "鯢",
+ "鯣",
+ "鯥",
+ "鯧",
+ "鯨",
+ "鯪",
+ "鯰",
+ "鯱",
+ "鯲",
+ "鯳",
+ "鯵",
+ "鯷",
+ "鯽",
+ "鰄",
+ "鰆",
+ "鰈",
+ "鰉",
+ "鰊",
+ "鰌",
+ "鰍",
+ "鰐",
+ "鰑",
+ "鰒",
+ "鰓",
+ "鰔",
+ "鰕",
+ "鰖",
+ "鰘",
+ "鰙",
+ "鰚",
+ "鰡",
+ "鰤",
+ "鰥",
+ "鰧",
+ "鰭",
+ "鰮",
+ "鰯",
+ "鰰",
+ "鰲",
+ "鰶",
+ "鰹",
+ "鰺",
+ "鰻",
+ "鰾",
+ "鱀",
+ "鱅",
+ "鱆",
+ "鱇",
+ "鱈",
+ "鱏",
+ "鱒",
+ "鱓",
+ "鱗",
+ "鱘",
+ "鱚",
+ "鱝",
+ "鱠",
+ "鱧",
+ "鱮",
+ "鱰",
+ "鱵",
+ "鱶",
+ "鱸",
+ "鱼",
+ "鱿",
+ "鲀",
+ "鲁",
+ "鲂",
+ "鲅",
+ "鲇",
+ "鲈",
+ "鲊",
+ "鲋",
+ "鲌",
+ "鲍",
+ "鲐",
+ "鲑",
+ "鲒",
+ "鲔",
+ "鲖",
+ "鲚",
+ "鲛",
+ "鲜",
+ "鲞",
+ "鲟",
+ "鲠",
+ "鲡",
+ "鲢",
+ "鲣",
+ "鲤",
+ "鲥",
+ "鲦",
+ "鲧",
+ "鲨",
+ "鲩",
+ "鲫",
+ "鲭",
+ "鲮",
+ "鲱",
+ "鲲",
+ "鲳",
+ "鲴",
+ "鲵",
+ "鲶",
+ "鲷",
+ "鲸",
+ "鲻",
+ "鲼",
+ "鲽",
+ "鳀",
+ "鳃",
+ "鳄",
+ "鳅",
+ "鳇",
+ "鳉",
+ "鳊",
+ "鳌",
+ "鳍",
+ "鳎",
+ "鳏",
+ "鳐",
+ "鳔",
+ "鳕",
+ "鳖",
+ "鳗",
+ "鳙",
+ "鳜",
+ "鳝",
+ "鳞",
+ "鳟",
+ "鳣",
+ "鳥",
+ "鳧",
+ "鳩",
+ "鳫",
+ "鳰",
+ "鳳",
+ "鳴",
+ "鳶",
+ "鴂",
+ "鴃",
+ "鴆",
+ "鴇",
+ "鴈",
+ "鴉",
+ "鴋",
+ "鴎",
+ "鴐",
+ "鴒",
+ "鴛",
+ "鴞",
+ "鴟",
+ "鴣",
+ "鴦",
+ "鴨",
+ "鴫",
+ "鴬",
+ "鴲",
+ "鴻",
+ "鴾",
+ "鴿",
+ "鵀",
+ "鵄",
+ "鵆",
+ "鵇",
+ "鵐",
+ "鵑",
+ "鵙",
+ "鵜",
+ "鵝",
+ "鵞",
+ "鵟",
+ "鵠",
+ "鵡",
+ "鵤",
+ "鵫",
+ "鵬",
+ "鵯",
+ "鵰",
+ "鵲",
+ "鵺",
+ "鵼",
+ "鶇",
+ "鶉",
+ "鶏",
+ "鶒",
+ "鶖",
+ "鶗",
+ "鶚",
+ "鶡",
+ "鶤",
+ "鶩",
+ "鶫",
+ "鶯",
+ "鶲",
+ "鶴",
+ "鶸",
+ "鶺",
+ "鶻",
+ "鷁",
+ "鷂",
+ "鷃",
+ "鷆",
+ "鷓",
+ "鷙",
+ "鷚",
+ "鷠",
+ "鷦",
+ "鷭",
+ "鷯",
+ "鷲",
+ "鷸",
+ "鷹",
+ "鷺",
+ "鷽",
+ "鸂",
+ "鸙",
+ "鸚",
+ "鸛",
+ "鸞",
+ "鸟",
+ "鸠",
+ "鸡",
+ "鸢",
+ "鸣",
+ "鸥",
+ "鸦",
+ "鸨",
+ "鸩",
+ "鸪",
+ "鸫",
+ "鸬",
+ "鸭",
+ "鸮",
+ "鸯",
+ "鸰",
+ "鸱",
+ "鸳",
+ "鸵",
+ "鸶",
+ "鸷",
+ "鸸",
+ "鸹",
+ "鸽",
+ "鸾",
+ "鸿",
+ "鹀",
+ "鹁",
+ "鹂",
+ "鹃",
+ "鹄",
+ "鹅",
+ "鹆",
+ "鹇",
+ "鹈",
+ "鹉",
+ "鹊",
+ "鹋",
+ "鹌",
+ "鹎",
+ "鹏",
+ "鹑",
+ "鹕",
+ "鹖",
+ "鹗",
+ "鹘",
+ "鹚",
+ "鹜",
+ "鹞",
+ "鹣",
+ "鹤",
+ "鹦",
+ "鹧",
+ "鹨",
+ "鹩",
+ "鹪",
+ "鹫",
+ "鹬",
+ "鹭",
+ "鹮",
+ "鹯",
+ "鹰",
+ "鹱",
+ "鹳",
+ "鹵",
+ "鹸",
+ "鹹",
+ "鹽",
+ "鹾",
+ "鹿",
+ "麁",
+ "麂",
+ "麇",
+ "麈",
+ "麋",
+ "麒",
+ "麓",
+ "麕",
+ "麗",
+ "麝",
+ "麞",
+ "麟",
+ "麥",
+ "麦",
+ "麩",
+ "麪",
+ "麭",
+ "麴",
+ "麵",
+ "麸",
+ "麹",
+ "麺",
+ "麻",
+ "麼",
+ "麽",
+ "麾",
+ "麿",
+ "黃",
+ "黄",
+ "黉",
+ "黌",
+ "黍",
+ "黎",
+ "黏",
+ "黐",
+ "黑",
+ "黒",
+ "黔",
+ "默",
+ "黙",
+ "黛",
+ "黜",
+ "黝",
+ "點",
+ "黟",
+ "黠",
+ "黡",
+ "黢",
+ "黥",
+ "黧",
+ "黨",
+ "黩",
+ "黯",
+ "黴",
+ "黹",
+ "黻",
+ "黼",
+ "黽",
+ "鼇",
+ "鼈",
+ "鼋",
+ "鼍",
+ "鼎",
+ "鼐",
+ "鼓",
+ "龝",
+ "齦",
+ "鼻",
+ "齋",
+ "x",
+ "龉",
+ "龇",
+ "鼡",
+ "齧",
+ "龍",
+ "齡",
+ "鼯",
+ "鼱",
+ "鼠",
+ "齊",
+ "龙",
+ "龃",
+ "龐",
+ "鼬",
+ "龈",
+ "齟",
+ "龄",
+ "鼾",
+ "龊",
+ "龕",
+ "鼪",
+ "龢",
+ "齣",
+ "齉",
+ "齲",
+ "齎",
+ "鼹",
+ "𠱁",
+ "鼩",
+ "齷",
+ "龋",
+ "齑",
+ "龛",
+ "齁",
+ "齿",
+ "龜",
+ "齐",
+ "齔",
+ "鼢",
+ "龅",
+ "齒",
+ "龚",
+ "齬",
+ "龌",
+ "龠",
+ "齪",
+ "龟",
+ "y",
+ "齢",
+ "鼕",
+ "鼙",
+ "!",
+ "을",
+ "의",
+ "이",
+ "에",
+ "는",
+ "를",
+ "가",
+ "은",
+ "▁수",
+ "도",
+ "한",
+ "고",
+ "로",
+ "▁이",
+ "과",
+ "에서",
+ "지",
+ "으로",
+ "기",
+ "다",
+ "하는",
+ "인",
+ "해",
+ "와",
+ "하고",
+ "▁있다",
+ "할",
+ "▁그",
+ "일",
+ "▁있는",
+ "리",
+ "▁한",
+ "어",
+ "사",
+ "시",
+ "서",
+ "자",
+ "만",
+ "게",
+ "▁있습니다",
+ "▁전",
+ "스",
+ "면",
+ "년",
+ "수",
+ "▁고",
+ "했다",
+ "▁가",
+ "대",
+ "적",
+ "라",
+ "나",
+ "주",
+ "하게",
+ "아",
+ "성",
+ "상",
+ "원",
+ "이다",
+ "장",
+ "▁일",
+ "▁주",
+ "▁더",
+ "▁내",
+ "적인",
+ "진",
+ "정",
+ "화",
+ "드",
+ "된",
+ "부",
+ "▁대",
+ "▁할",
+ "▁유",
+ "▁보",
+ "▁것",
+ "▁사",
+ "▁시",
+ "▁중",
+ "▁대한",
+ "▁지",
+ "▁때",
+ "들이",
+ "요",
+ "▁다",
+ "▁것이",
+ "전",
+ "▁정",
+ "제",
+ "구",
+ "야",
+ "▁부",
+ "▁안",
+ "치",
+ "▁및",
+ "▁나",
+ "월",
+ "트",
+ "한다",
+ "보",
+ "하기",
+ "▁한다",
+ "▁신",
+ "입니다",
+ "에게",
+ "▁것이다",
+ "소",
+ "▁말",
+ "하지",
+ "▁등",
+ "▁기",
+ "적으로",
+ "▁비",
+ "▁해",
+ "▁위해",
+ "합니다",
+ "신",
+ "에는",
+ "산",
+ "선",
+ "위",
+ "▁소",
+ "▁자",
+ "관",
+ "하",
+ "비",
+ "▁마",
+ "니",
+ "러",
+ "세",
+ "▁하는",
+ "까지",
+ "들",
+ "▁아",
+ "당",
+ "▁상",
+ "용",
+ "▁제",
+ "▁인",
+ "▁오",
+ "▁두",
+ "▁다른",
+ "려",
+ "단",
+ "▁하",
+ "▁공",
+ "며",
+ "우",
+ "동",
+ "▁무",
+ "▁후",
+ "하여",
+ "조",
+ "▁것은",
+ "▁미",
+ "▁원",
+ "명",
+ "히",
+ "▁바",
+ "르",
+ "실",
+ "마",
+ "▁김",
+ "▁많은",
+ "국",
+ "여",
+ "▁가장",
+ "▁동",
+ "분",
+ "▁잘",
+ "방",
+ "회",
+ "▁구",
+ "행",
+ "식",
+ "▁거",
+ "▁연",
+ "차",
+ "▁통해",
+ "계",
+ "▁세",
+ "던",
+ "체",
+ "▁조",
+ "▁한국",
+ "중",
+ "재",
+ "▁같은",
+ "▁함께",
+ "질",
+ "▁모",
+ "미",
+ "▁모든",
+ "▁경우",
+ "연",
+ "학",
+ "호",
+ "▁때문에",
+ "▁사용",
+ "▁것을",
+ "안",
+ "▁불",
+ "들은",
+ "▁하지만",
+ "▁도",
+ "▁될",
+ "들을",
+ "개",
+ "▁선",
+ "물",
+ "▁재",
+ "▁우리",
+ "▁입",
+ "▁성",
+ "▁의",
+ "▁강",
+ "▁스",
+ "무",
+ "▁생각",
+ "문",
+ "▁저",
+ "이나",
+ "해야",
+ "간",
+ "내",
+ "▁장",
+ "▁서",
+ "되는",
+ "운",
+ "부터",
+ "경",
+ "▁어",
+ "▁그리고",
+ "하면",
+ "▁여",
+ "들의",
+ "▁발",
+ "하다",
+ "▁단",
+ "▁당",
+ "오",
+ "금",
+ "▁명",
+ "공",
+ "▁물",
+ "크",
+ "▁것으로",
+ "▁했다",
+ "▁양",
+ "▁배",
+ "법",
+ "형",
+ "▁또",
+ "▁간",
+ "▁개",
+ "▁또한",
+ "▁그러나",
+ "▁이런",
+ "▁차",
+ "▁큰",
+ "민",
+ "▁다양한",
+ "생",
+ "었다",
+ "▁남",
+ "력",
+ "유",
+ "▁따라",
+ "지만",
+ "권",
+ "▁게",
+ "모",
+ "▁경",
+ "▁위",
+ "▁없는",
+ "▁하나",
+ "에서는",
+ "워",
+ "▁시작",
+ "▁파",
+ "▁아니라",
+ "▁대해",
+ "▁만",
+ "▁실",
+ "▁알",
+ "▁없다",
+ "하며",
+ "▁합니다",
+ "▁된다",
+ "감",
+ "▁많이",
+ "영",
+ "▁지역",
+ "▁반",
+ "건",
+ "▁데",
+ "▁방",
+ "▁위한",
+ "직",
+ "거",
+ "▁하고",
+ "▁어떤",
+ "▁세계",
+ "▁적",
+ "양",
+ "▁분",
+ "점",
+ "데",
+ "보다",
+ "▁좋은",
+ "습니다",
+ "▁열",
+ "▁미국",
+ "▁초",
+ "역",
+ "면서",
+ "터",
+ "된다",
+ "▁다시",
+ "심",
+ "파",
+ "▁어떻게",
+ "종",
+ "타",
+ "▁본",
+ "▁살",
+ "급",
+ "▁중국",
+ "▁진",
+ "▁손",
+ "래",
+ "▁줄",
+ "▁매",
+ "석",
+ "▁여행",
+ "▁피",
+ "▁이상",
+ "교",
+ "▁지난",
+ "▁집",
+ "▁모두",
+ "약",
+ "프",
+ "린",
+ "▁자동",
+ "라는",
+ "라고",
+ "▁감",
+ "포",
+ "▁있도록",
+ "▁진행",
+ "토",
+ "▁박",
+ "음",
+ "▁것입니다",
+ "▁못",
+ "천",
+ "지는",
+ "▁우",
+ "란",
+ "▁또는",
+ "▁노",
+ "▁포",
+ "▁화",
+ "군",
+ "달",
+ "입",
+ "업",
+ "▁이용",
+ "▁되",
+ "▁현재",
+ "▁타",
+ "▁걸",
+ "저",
+ "해서",
+ "▁그런",
+ "바",
+ "까",
+ "▁번",
+ "▁건",
+ "될",
+ "청",
+ "디",
+ "▁최",
+ "▁예",
+ "▁이후",
+ "증",
+ "임",
+ "▁일본",
+ "속",
+ "▁외",
+ "티",
+ "▁특히",
+ "격",
+ "▁볼",
+ "료",
+ "▁있을",
+ "▁지금",
+ "▁관련",
+ "▁아이",
+ "▁들",
+ "▁들어",
+ "레",
+ "▁문제",
+ "두",
+ "출",
+ "되어",
+ "▁이번",
+ "에도",
+ "▁산",
+ "작",
+ "설",
+ "▁사회",
+ "▁시간",
+ "▁사실",
+ "▁있었다",
+ "▁된",
+ "▁그는",
+ "즈",
+ "▁날",
+ "발",
+ "▁뒤",
+ "▁새로운",
+ "매",
+ "처럼",
+ "▁나는",
+ "온",
+ "난",
+ "▁교육",
+ "▁출",
+ "▁각",
+ "▁편",
+ "▁지원",
+ "▁호",
+ "▁심",
+ "▁영",
+ "▁계",
+ "▁서비스",
+ "는데",
+ "▁바로",
+ "들에게",
+ "▁정도",
+ "▁문",
+ "▁시장",
+ "이라는",
+ "길",
+ "품",
+ "▁선택",
+ "절",
+ "기를",
+ "▁이어",
+ "색",
+ "되고",
+ "목",
+ "았다",
+ "▁여러",
+ "▁가지",
+ "류",
+ "▁법",
+ "▁에",
+ "거나",
+ "▁서울",
+ "▁다음",
+ "키",
+ "▁달",
+ "▁확인",
+ "▁약",
+ "▁제공",
+ "▁교",
+ "립",
+ "▁사람",
+ "▁동안",
+ "피",
+ "릴",
+ "▁자신의",
+ "▁영화",
+ "▁과",
+ "▁없",
+ "배",
+ "▁치",
+ "▁맞",
+ "▁기업",
+ "▁국",
+ "▁이러한",
+ "▁않고",
+ "네",
+ "카",
+ "▁이야기",
+ "▁그래서",
+ "▁속",
+ "▁연구",
+ "그",
+ "▁만들어",
+ "▁눈",
+ "져",
+ "▁우리는",
+ "강",
+ "통",
+ "▁최근",
+ "▁국가",
+ "▁책",
+ "루",
+ "집",
+ "님",
+ "▁임",
+ "판",
+ "죠",
+ "른",
+ "▁시설",
+ "▁때문이다",
+ "울",
+ "하면서",
+ "▁추",
+ "▁않은",
+ "▁정보",
+ "했습니다",
+ "든",
+ "▁곳",
+ "각",
+ "▁총",
+ "▁않을",
+ "림",
+ "▁않는",
+ "태",
+ "향",
+ "후",
+ "▁생",
+ "▁결과",
+ "▁되는",
+ "▁학",
+ "▁찾아",
+ "결",
+ "등",
+ "▁있다는",
+ "였다",
+ "버",
+ "론",
+ "▁게임",
+ "▁말했다",
+ "▁채",
+ "▁사람이",
+ "▁있어",
+ "성을",
+ "현",
+ "▁보다",
+ "환",
+ "▁관",
+ "이라고",
+ "▁고객",
+ "▁몸",
+ "량",
+ "▁막",
+ "▁귀",
+ "▁먹",
+ "▁변",
+ "▁기술",
+ "▁로",
+ "▁너무",
+ "▁새",
+ "▁물론",
+ "▁제품",
+ "▁경제",
+ "날",
+ "▁직접",
+ "남",
+ "▁준비",
+ "합",
+ "▁사업",
+ "▁천",
+ "노",
+ "박",
+ "됩니다",
+ "▁용",
+ "엔",
+ "▁메",
+ "스트",
+ "▁운영",
+ "▁있",
+ "▁개발",
+ "자가",
+ "▁없이",
+ "▁코",
+ "▁내가",
+ "▁토",
+ "▁매우",
+ "담",
+ "▁금",
+ "언",
+ "시간",
+ "▁그런데",
+ "능",
+ "준",
+ "▁리",
+ "▁종",
+ "▁회사",
+ "▁복",
+ "▁사항을",
+ "▁국내",
+ "으며",
+ "▁사진",
+ "▁몇",
+ "으면",
+ "▁이렇게",
+ "처",
+ "름",
+ "▁노력",
+ "▁애",
+ "▁수도",
+ "케",
+ "락",
+ "이었다",
+ "▁첫",
+ "복",
+ "▁대표",
+ "▁더욱",
+ "됐다",
+ "▁통",
+ "▁역사",
+ "▁의미",
+ "▁호텔",
+ "▁온",
+ "갈",
+ "▁식",
+ "▁어느",
+ "▁이해",
+ "▁년",
+ "▁청",
+ "▁문화",
+ "했던",
+ "편",
+ "▁관리",
+ "▁여성",
+ "외",
+ "▁상태",
+ "▁바랍니다",
+ "▁처음",
+ "망",
+ "병",
+ "령",
+ "▁결정",
+ "졌다",
+ "▁있고",
+ "션",
+ "층",
+ "리는",
+ "▁북한",
+ "▁잡",
+ "▁좀",
+ "으",
+ "근",
+ "별",
+ "브",
+ "▁현",
+ "▁당시",
+ "▁순",
+ "승",
+ "▁것도",
+ "▁기대",
+ "▁허",
+ "평",
+ "더",
+ "▁역시",
+ "▁보고",
+ "▁회",
+ "반",
+ "▁필요",
+ "▁개인",
+ "▁설명",
+ "▁일부",
+ "▁정말",
+ "▁올",
+ "초",
+ "▁군",
+ "너",
+ "백",
+ "지고",
+ "함",
+ "▁계속",
+ "▁마음",
+ "▁가지고",
+ "▁사람들이",
+ "▁않는다",
+ "술",
+ "▁가격",
+ "▁권",
+ "▁담",
+ "▁길",
+ "▁작품",
+ "▁사랑",
+ "되지",
+ "▁목",
+ "▁부분",
+ "▁건강",
+ "▁돌",
+ "▁보면",
+ "▁해당",
+ "▁참",
+ "▁환경",
+ "북",
+ "▁아니",
+ "▁중요한",
+ "기도",
+ "▁난",
+ "▁자기",
+ "▁있으며",
+ "▁백",
+ "▁쓰",
+ "▁이미",
+ "▁참여",
+ "▁창",
+ "▁아닌",
+ "▁이를",
+ "창",
+ "▁존재",
+ "▁글",
+ "▁우리가",
+ "▁경기",
+ "▁대학",
+ "▁드",
+ "추",
+ "▁없습니다",
+ "겨",
+ "▁학교",
+ "들과",
+ "기에",
+ "열",
+ "▁추가",
+ "▁해결",
+ "▁치료",
+ "▁성장",
+ "독",
+ "▁전체",
+ "▁변화",
+ "율",
+ "▁아니다",
+ "▁높은",
+ "▁체",
+ "▁회원",
+ "투",
+ "코",
+ "▁농",
+ "▁요",
+ "예",
+ "▁평",
+ "▁제안",
+ "대로",
+ "▁왜",
+ "▁이제",
+ "▁있다고",
+ "▁월",
+ "▁나라",
+ "▁포함",
+ "▁공간",
+ "축",
+ "▁점",
+ "▁필요한",
+ "지를",
+ "▁등을",
+ "▁말씀",
+ "하거나",
+ "있는",
+ "▁쉽게",
+ "▁않",
+ "▁정책",
+ "▁같이",
+ "▁활동",
+ "▁않았다",
+ "▁같다",
+ "▁투자",
+ "▁생활",
+ "▁되어",
+ "주의",
+ "익",
+ "▁정치",
+ "▁죽",
+ "▁요구",
+ "▁활용",
+ "▁그렇게",
+ "살",
+ "책",
+ "▁커",
+ "진다",
+ "▁평가",
+ "례",
+ "▁성공",
+ "도록",
+ "▁정부",
+ "에서도",
+ "▁오늘",
+ "▁일이",
+ "쪽",
+ "▁안전",
+ "▁몰",
+ "▁표시",
+ "▁경험",
+ "었습니다",
+ "▁유지",
+ "▁해야",
+ "▁도시",
+ "▁올해",
+ "▁라고",
+ "▁않습니다",
+ "표",
+ "▁있기",
+ "어요",
+ "▁취",
+ "▁먼저",
+ "되",
+ "▁사이",
+ "▁검토",
+ "니까",
+ "▁인간",
+ "▁와",
+ "철",
+ "▁주장",
+ "침",
+ "다는",
+ "▁적용",
+ "▁번역",
+ "친",
+ "탄",
+ "▁시대",
+ "▁결국",
+ "▁삼",
+ "▁사건",
+ "▁수정",
+ "▁시스템",
+ "▁가족",
+ "▁따라서",
+ "▁독",
+ "▁늘",
+ "▁레",
+ "▁갈",
+ "▁앞으로",
+ "니다",
+ "사를",
+ "▁카",
+ "▁질문",
+ "▁역",
+ "번",
+ "습",
+ "▁광",
+ "▁만나",
+ "긴",
+ "▁북",
+ "▁하지",
+ "움",
+ "▁아래",
+ "▁절",
+ "▁읽",
+ "볼",
+ "▁결",
+ "▁자리",
+ "본",
+ "▁계획",
+ "돼",
+ "순",
+ "▁태",
+ "▁발전",
+ "▁기록",
+ "▁됩니다",
+ "▁팀",
+ "▁크",
+ "▁밝혔다",
+ "▁되었다",
+ "착",
+ "▁세상",
+ "▁국민",
+ "▁설",
+ "▁의견을",
+ "▁버",
+ "▁이것은",
+ "▁살아",
+ "▁발생",
+ "▁분석",
+ "었",
+ "쳐",
+ "자는",
+ "▁현실",
+ "▁듯",
+ "말",
+ "▁수준",
+ "▁운동",
+ "▁놓",
+ "▁있지만",
+ "광",
+ "▁그의",
+ "▁방문",
+ "▁배우",
+ "기가",
+ "▁끝",
+ "▁방법",
+ "▁뜻",
+ "▁합",
+ "▁서로",
+ "▁접",
+ "▁생산",
+ "▁않다",
+ "▁발표",
+ "▁하나님",
+ "▁하루",
+ "링",
+ "▁급",
+ "애",
+ "▁표현",
+ "▁병",
+ "▁싶",
+ "▁음식",
+ "▁정보를",
+ "▁좋아",
+ "▁아직",
+ "▁미래",
+ "▁인터넷",
+ "없이",
+ "▁모습",
+ "▁은",
+ "▁크게",
+ "씨",
+ "▁야",
+ "▁알고",
+ "렸다",
+ "▁판매",
+ "▁프로그램",
+ "▁교회",
+ "▁받아",
+ "팅",
+ "▁직",
+ "▁앞",
+ "▁관계",
+ "▁구성",
+ "다고",
+ "랑",
+ "▁자신",
+ "▁높",
+ "▁조금",
+ "았",
+ "▁승",
+ "족",
+ "▁만들",
+ "▁베",
+ "▁키",
+ "▁믿",
+ "▁작은",
+ "▁현대",
+ "▁예약",
+ "플",
+ "▁아이들",
+ "▁자연",
+ "규",
+ "▁전문",
+ "력을",
+ "범",
+ "항",
+ "▁만큼",
+ "이며",
+ "련",
+ "▁테",
+ "▁있었",
+ "▁대통령",
+ "장은",
+ "▁찾",
+ "▁패",
+ "▁이유",
+ "네요",
+ "성이",
+ "▁않았",
+ "▁기억",
+ "▁골",
+ "테",
+ "▁행",
+ "▁증가",
+ "▁밀",
+ "▁별",
+ "▁돌아",
+ "▁대부분",
+ "▁문제가",
+ "▁감사합니다",
+ "송",
+ "▁누",
+ "▁넘",
+ "▁마련",
+ "▁질",
+ "이라",
+ "▁증",
+ "▁가능",
+ "▁잠",
+ "▁형",
+ "▁감독",
+ "▁행복",
+ "▁환",
+ "황",
+ "▁제가",
+ "▁이름",
+ "▁공개",
+ "있",
+ "장을",
+ "▁민",
+ "▁황",
+ "▁거의",
+ "극",
+ "▁가운데",
+ "▁맛",
+ "악",
+ "셔",
+ "막",
+ "▁있으나",
+ "▁기존",
+ "▁소개",
+ "▁디자인",
+ "자를",
+ "▁기능",
+ "커",
+ "▁설치",
+ "▁산업",
+ "▁온라인",
+ "변",
+ "▁목표",
+ "▁번째",
+ "▁악",
+ "▁폭",
+ "자의",
+ "감을",
+ "불",
+ "록",
+ "▁보호",
+ "▁행사",
+ "▁표",
+ "▁침",
+ "택",
+ "▁투",
+ "▁향",
+ "▁스스로",
+ "▁기자",
+ "▁시간이",
+ "▁기간",
+ "▁없어",
+ "▁일을",
+ "희",
+ "런",
+ "줄",
+ "로서",
+ "▁기본",
+ "▁상품",
+ "▁특",
+ "▁내용",
+ "▁인해",
+ "▁탈",
+ "▁지난해",
+ "받",
+ "▁지나",
+ "▁있게",
+ "▁하면",
+ "리를",
+ "▁학생",
+ "▁협",
+ "▁여러분의",
+ "▁충",
+ "활",
+ "▁연결",
+ "▁공부",
+ "▁제대로",
+ "▁보내",
+ "곤",
+ "▁터",
+ "▁음악",
+ "▁주변",
+ "▁돈",
+ "▁방송",
+ "▁환자",
+ "▁이는",
+ "▁떠",
+ "▁고민",
+ "▁네",
+ "▁가능한",
+ "▁위치",
+ "곡",
+ "▁우리의",
+ "졌",
+ "▁무료",
+ "▁위험",
+ "▁며",
+ "▁이날",
+ "▁꼭",
+ "▁즉",
+ "▁같",
+ "▁주요",
+ "▁많다",
+ "▁삶",
+ "흥",
+ "찰",
+ "올",
+ "▁전에",
+ "▁그림",
+ "▁저는",
+ "▁암",
+ "▁벌",
+ "▁철",
+ "▁이라고",
+ "압",
+ "▁영향을",
+ "▁국제",
+ "염",
+ "▁보인다",
+ "십",
+ "▁함",
+ "▁학생들",
+ "확",
+ "▁힘",
+ "▁조사",
+ "객",
+ "▁면",
+ "▁등의",
+ "▁아주",
+ "▁작업",
+ "▁행동",
+ "▁과거",
+ "▁때문",
+ "퍼",
+ "▁왕",
+ "베",
+ "▁과정",
+ "▁우리나라",
+ "▁있기를",
+ "▁발견",
+ "레이",
+ "▁의원",
+ "▁꿈",
+ "채",
+ "▁사람은",
+ "▁모습을",
+ "▁구조",
+ "글",
+ "▁육",
+ "▁방식",
+ "▁시간을",
+ "▁숙박",
+ "▁했",
+ "점을",
+ "▁있어서",
+ "하였다",
+ "▁처",
+ "▁트",
+ "▁도움이",
+ "칠",
+ "팀",
+ "인데",
+ "▁음",
+ "▁자유",
+ "▁일반",
+ "▁친",
+ "▁놀",
+ "었던",
+ "▁팔",
+ "▁됐다",
+ "기는",
+ "▁가진",
+ "▁변경",
+ "률",
+ "▁해외",
+ "마다",
+ "▁항",
+ "했고",
+ "거리",
+ "▁현장",
+ "▁개선",
+ "▁후보",
+ "▁극",
+ "▁다만",
+ "▁집중",
+ "▁근",
+ "위원회",
+ "▁의사",
+ "▁얘기",
+ "▁구매",
+ "▁프로",
+ "▁관한",
+ "▁감사",
+ "▁이에",
+ "되었다",
+ "때",
+ "▁사이트",
+ "▁올라",
+ "▁맡",
+ "▁사람들",
+ "▁추진",
+ "▁서비스를",
+ "▁고려",
+ "협",
+ "께",
+ "▁풀",
+ "▁계획에",
+ "였",
+ "▁중입니다",
+ "▁여행자들",
+ "▁넘어",
+ "▁씨",
+ "▁되고",
+ "▁친구",
+ "▁붙",
+ "▁브랜드",
+ "훈",
+ "▁처리",
+ "▁둘",
+ "▁나오",
+ "▁순간",
+ "▁조금이나마",
+ "▁조직",
+ "▁같습니다",
+ "▁사용자",
+ "▁낮",
+ "▁상황",
+ "메",
+ "▁사고",
+ "▁한국어로",
+ "들도",
+ "왔다",
+ "▁자체",
+ "▁받고",
+ "▁힘들",
+ "▁뿐",
+ "밀",
+ "▁선수",
+ "▁없었다",
+ "▁여기",
+ "▁판",
+ "더라도",
+ "사가",
+ "▁업무",
+ "▁회원님의",
+ "액",
+ "▁작",
+ "▁그것은",
+ "하지만",
+ "▁개인정보",
+ "▁피부",
+ "▁예상",
+ "▁입장",
+ "리고",
+ "하십시오",
+ "▁거리",
+ "▁달라",
+ "▁풍",
+ "▁작가",
+ "▁비용",
+ "▁많",
+ "머",
+ "▁오래",
+ "▁리뷰는",
+ "▁완벽하지",
+ "▁사람들은",
+ "▁제작",
+ "▁업체",
+ "▁퀄리티가",
+ "▁이동",
+ "▁싶다",
+ "▁강화",
+ "숙",
+ "▁번역되었습니다",
+ "헌",
+ "▁분위기",
+ "▁싶은",
+ "▁보여",
+ "▁의해",
+ "▁문제를",
+ "▁느끼",
+ "▁항상",
+ "▁신청",
+ "▁윤",
+ "취",
+ "▁참고가",
+ "▁참고하실",
+ "▁판단",
+ "▁실제",
+ "▁지적",
+ "▁번역을",
+ "▁소리",
+ "▁정신",
+ "▁반대",
+ "▁대상",
+ "어서",
+ "▁얼마나",
+ "▁실제로",
+ "▁분야",
+ "▁숨",
+ "▁공격",
+ "위를",
+ "▁정도로",
+ "▁이야기를",
+ "낼",
+ "▁달리",
+ "▁기준",
+ "▁자신이",
+ "▁디",
+ "▁검색",
+ "▁번역의",
+ "▁따",
+ "장이",
+ "한다는",
+ "하실",
+ "▁브",
+ "▁효과",
+ "▁라",
+ "▁운",
+ "▁따르면",
+ "▁객실",
+ "▁클",
+ "▁경찰",
+ "사회",
+ "▁받은",
+ "▁그대로",
+ "다면",
+ "▁책임",
+ "혀",
+ "충",
+ "하도록",
+ "▁필",
+ "▁경쟁",
+ "▁들어가",
+ "것",
+ "널",
+ "했",
+ "▁부담",
+ "▁역할을",
+ "갔다",
+ "▁한번",
+ "▁가치",
+ "▁이용자",
+ "교육",
+ "▁전략",
+ "▁위해서",
+ "▁금융",
+ "낸",
+ "▁해서",
+ "▁속에서",
+ "견",
+ "▁피해",
+ "▁거래",
+ "▁최대",
+ "▁있는데",
+ "▁그러",
+ "라도",
+ "▁등장",
+ "▁내려",
+ "블",
+ "▁일정",
+ "▁대신",
+ "▁자료",
+ "▁필요하다",
+ "▁지방",
+ "냈다",
+ "▁지속",
+ "▁확대",
+ "▁않아",
+ "▁우선",
+ "시장",
+ "▁만드는",
+ "▁겪",
+ "▁밤",
+ "페",
+ "▁얼굴",
+ "▁대해서",
+ "▁비교",
+ "▁좋다",
+ "▁페",
+ "화를",
+ "▁말을",
+ "▁바람",
+ "츠",
+ "인지",
+ "▁가져",
+ "▁선거",
+ "효",
+ "탁",
+ "▁이미지",
+ "▁최고",
+ "냐",
+ "▁폐",
+ "주는",
+ "▁인식",
+ "로부터",
+ "명이",
+ "개월",
+ "로운",
+ "이고",
+ "▁누구",
+ "▁갖고",
+ "돌",
+ "▁교수",
+ "▁좋",
+ "▁이곳",
+ "▁인기",
+ "렸",
+ "▁등록",
+ "▁과학",
+ "린다",
+ "까요",
+ "▁하다",
+ "▁오히려",
+ "득",
+ "▁모델",
+ "▁광고",
+ "▁경우가",
+ "력이",
+ "척",
+ "틀",
+ "▁추천",
+ "총",
+ "람",
+ "▁잔",
+ "▁한다는",
+ "▁해도",
+ "▁송",
+ "걸",
+ "끼",
+ "▁땅",
+ "겠",
+ "하던",
+ "▁언론",
+ "▁나가",
+ "물을",
+ "이지만",
+ "▁남자",
+ "▁제시",
+ "▁그들은",
+ "▁단계",
+ "▁아버지",
+ "데요",
+ "지도",
+ "어야",
+ "▁국회",
+ "▁하기",
+ "▁꽃",
+ "덕",
+ "▁설정",
+ "▁그리",
+ "검",
+ "풍",
+ "센",
+ "씩",
+ "육",
+ "함을",
+ "▁축",
+ "하기도",
+ "▁하나님의",
+ "▁견",
+ "▁어디",
+ "▁전국",
+ "폭",
+ "▁보통",
+ "▁보는",
+ "▁오는",
+ "▁인생",
+ "골",
+ "▁어린이",
+ "콘",
+ "▁여자",
+ "▁자동차",
+ "럽",
+ "▁수행",
+ "▁어려운",
+ "▁마지막",
+ "▁원인",
+ "▁여전히",
+ "▁생각이",
+ "▁아침",
+ "▁섬",
+ "▁측",
+ "시는",
+ "▁오후",
+ "▁녹",
+ "▁그냥",
+ "▁보여주",
+ "▁위해서는",
+ "수를",
+ "스크",
+ "하세요",
+ "곳",
+ "▁목적",
+ "기로",
+ "렌",
+ "▁되면",
+ "▁소비자",
+ "▁대한민국",
+ "이란",
+ "▁사용할",
+ "▁경우에는",
+ "▁라는",
+ "▁동시에",
+ "▁가정",
+ "▁데이터",
+ "▁전쟁",
+ "▁못한",
+ "듯",
+ "▁인사",
+ "억",
+ "▁자주",
+ "칭",
+ "▁중심",
+ "▁요청",
+ "▁전혀",
+ "▁회장",
+ "▁이들",
+ "▁찍",
+ "▁엄",
+ "▁있지",
+ "▁머리",
+ "▁아무",
+ "상을",
+ "▁마치",
+ "▁조선",
+ "▁되었",
+ "▁규모",
+ "▁돼",
+ "사는",
+ "필",
+ "▁마사지",
+ "▁인정",
+ "▁영상",
+ "▁다음과",
+ "▁안정",
+ "새",
+ "▁반응",
+ "▁특정",
+ "▁답",
+ "탈",
+ "▁요즘",
+ "▁사례",
+ "▁핵심",
+ "스터",
+ "▁한편",
+ "▁저희",
+ "▁이전",
+ "▁최고의",
+ "▁장소",
+ "험",
+ "▁아마",
+ "▁빠",
+ "▁때는",
+ "▁슬",
+ "▁엄마",
+ "▁필요가",
+ "▁결혼",
+ "▁빛",
+ "▁상대",
+ "▁대화",
+ "▁주는",
+ "클",
+ "패",
+ "▁유럽",
+ "▁보니",
+ "▁공급",
+ "슬",
+ "▁책을",
+ "십시오",
+ "컨",
+ "▁좌",
+ "▁원하는",
+ "▁이유는",
+ "딩",
+ "▁생명",
+ "왕",
+ "▁말이",
+ "▁받을",
+ "▁홍",
+ "▁사회적",
+ "▁마음을",
+ "▁빈",
+ "▁것이라고",
+ "▁부모",
+ "▁공연",
+ "스를",
+ "▁울",
+ "▁그렇",
+ "시키는",
+ "했을",
+ "▁계약",
+ "려고",
+ "▁노동",
+ "▁넓",
+ "▁걱정",
+ "시켜",
+ "▁따른",
+ "▁만든",
+ "▁일상",
+ "▁요금",
+ "균",
+ "▁전화",
+ "▁전통",
+ "념",
+ "▁부족",
+ "▁공유",
+ "찬",
+ "쟁",
+ "지요",
+ "잡",
+ "▁제한",
+ "▁아니오",
+ "▁정상",
+ "▁욕",
+ "▁나와",
+ "▁생각하시나요",
+ "손",
+ "략",
+ "▁시민",
+ "하신",
+ "▁특징",
+ "암",
+ "▁제도",
+ "▁능력",
+ "▁시행",
+ "▁전달",
+ "▁상황이",
+ "▁식사",
+ "힌",
+ "사업",
+ "▁반드시",
+ "▁여러분",
+ "▁격",
+ "▁내부",
+ "킹",
+ "▁되지",
+ "▁감정",
+ "▁탄",
+ "▁준",
+ "▁에너지",
+ "▁제출해주셔",
+ "▁나서",
+ "접",
+ "▁플",
+ "라면",
+ "▁매일",
+ "▁내용을",
+ "▁생각해",
+ "밖",
+ "▁직원",
+ "▁있다면",
+ "▁수많은",
+ "▁너",
+ "▁수밖에",
+ "▁나이",
+ "났다",
+ "묘",
+ "▁지지",
+ "▁뭐",
+ "원을",
+ "▁알아",
+ "▁느낌",
+ "▁시도",
+ "주세요",
+ "났",
+ "▁현지",
+ "▁본인",
+ "가지",
+ "인이",
+ "봉",
+ "▁기사",
+ "보고",
+ "수록",
+ "▁넣",
+ "▁경영",
+ "생활",
+ "▁죄",
+ "▁주목",
+ "하자",
+ "▁중요",
+ "▁요소",
+ "치를",
+ "▁병원",
+ "자들이",
+ "▁조건",
+ "▁검찰",
+ "제를",
+ "명을",
+ "▁영어",
+ "서는",
+ "▁우려",
+ "▁두고",
+ "▁접근",
+ "일에",
+ "식을",
+ "없는",
+ "▁것처럼",
+ "끄",
+ "▁받는",
+ "랜드",
+ "▁많아",
+ "▁예술",
+ "▁동물",
+ "하는데",
+ "▁예정",
+ "기관",
+ "▁긴",
+ "측",
+ "▁의료",
+ "▁가능성이",
+ "춘",
+ "▁삶을",
+ "▁항공",
+ "했다고",
+ "벨",
+ "▁깨",
+ "▁건물",
+ "▁비판",
+ "▁지식",
+ "▁시절",
+ "▁이뤄",
+ "▁목소리",
+ "▁부산",
+ "벌",
+ "▁노래",
+ "▁관심을",
+ "▁가입",
+ "▁없을",
+ "▁억",
+ "얼",
+ "▁과정에서",
+ "▁실시",
+ "▁관심",
+ "▁알려",
+ "▁검사",
+ "▁제주",
+ "▁여기에",
+ "▁최소",
+ "▁느껴",
+ "▁석",
+ "▁사람의",
+ "음을",
+ "▁묻",
+ "수가",
+ "▁정리",
+ "보다는",
+ "▁높이",
+ "▁혹은",
+ "▁연기",
+ "▁쌓",
+ "▁콘텐츠",
+ "▁망",
+ "▁희망",
+ "센터",
+ "스러운",
+ "▁컴퓨터",
+ "년간",
+ "▁열린",
+ "▁시기",
+ "갔",
+ "정을",
+ "▁평화",
+ "▁곧",
+ "명의",
+ "▁앞서",
+ "▁방법을",
+ "▁그것",
+ "롭",
+ "권을",
+ "▁쪽",
+ "▁확보",
+ "▁모바일",
+ "▁대비",
+ "▁영국",
+ "▁가능성",
+ "치는",
+ "▁검",
+ "▁저렴한",
+ "▁퍼",
+ "▁밖에",
+ "맹",
+ "폐",
+ "▁생각을",
+ "▁받았다",
+ "▁웹",
+ "▁밝",
+ "폰",
+ "▁빌",
+ "▁속에",
+ "관계",
+ "▁통합",
+ "▁대중",
+ "리가",
+ "▁비해",
+ "텔",
+ "▁헤",
+ "사의",
+ "▁여름",
+ "문화",
+ "▁프로젝트",
+ "▁문제는",
+ "▁전망",
+ "원이",
+ "▁색",
+ "▁보기",
+ "▁등이",
+ "엘",
+ "▁있던",
+ "▁예정이다",
+ "▁나무",
+ "▁있어요",
+ "한다면",
+ "▁않으면",
+ "▁훨씬",
+ "▁인물",
+ "▁절대",
+ "▁떠나",
+ "핑",
+ "▁만족",
+ "▁돈을",
+ "▁매력",
+ "느냐",
+ "▁시즌",
+ "▁분들",
+ "▁술",
+ "되면",
+ "혹",
+ "▁보이는",
+ "▁그들의",
+ "▁속도",
+ "▁루",
+ "▁듣",
+ "▁모양",
+ "으나",
+ "겠습니다",
+ "▁주제",
+ "▁대응",
+ "▁중앙",
+ "▁얼마",
+ "녀",
+ "으니",
+ "▁어렵",
+ "▁지켜",
+ "▁촬영",
+ "▁있는지",
+ "트를",
+ "▁찬",
+ "▁체험",
+ "▁높아",
+ "되기",
+ "▁퇴",
+ "있다",
+ "스는",
+ "▁사전",
+ "▁신경",
+ "서를",
+ "▁못하고",
+ "▁하며",
+ "▁영어로",
+ "랐",
+ "▁부정",
+ "▁전자",
+ "▁일어나",
+ "▁현상",
+ "참",
+ "▁파일",
+ "▁위기",
+ "▁뇌",
+ "▁기도",
+ "▁참고",
+ "▁강조",
+ "▁칼",
+ "▁사실을",
+ "▁그동안",
+ "▁휴",
+ "▁언어",
+ "▁조치",
+ "▁신뢰",
+ "▁후에",
+ "▁형태",
+ "▁나누",
+ "▁가는",
+ "▁공식",
+ "▁그것을",
+ "▁사용하는",
+ "금을",
+ "▁기관",
+ "▁궁금",
+ "▁각종",
+ "▁행정",
+ "▁특성",
+ "▁당신이",
+ "▁그가",
+ "▁꾸",
+ "하시",
+ "놓",
+ "▁도전",
+ "▁마을",
+ "▁문서",
+ "▁규정",
+ "▁중에",
+ "혜",
+ "▁관광",
+ "하였",
+ "▁한다고",
+ "▁작성",
+ "▁도입",
+ "▁맞는",
+ "▁생기",
+ "▁시험",
+ "▁차량",
+ "▁사는",
+ "했지만",
+ "▁안에",
+ "▁파악",
+ "▁사람을",
+ "▁선정",
+ "▁앱",
+ "잃",
+ "▁논의",
+ "▁아파트",
+ "▁그때",
+ "▁인상",
+ "▁전시",
+ "▁증상",
+ "한다고",
+ "▁하나의",
+ "▁장관",
+ "▁답변",
+ "드는",
+ "▁품",
+ "▁수업",
+ "▁글로벌",
+ "▁행위",
+ "▁스타일",
+ "▁잊",
+ "이기도",
+ "자들은",
+ "▁있어야",
+ "▁나타나",
+ "▁딸",
+ "▁캐릭터",
+ "▁탐",
+ "▁제거",
+ "으로서",
+ "▁독일",
+ "▁있을까",
+ "벤",
+ "▁힘을",
+ "▁언급",
+ "▁이것",
+ "출장",
+ "▁참석",
+ "▁차지",
+ "▁일단",
+ "적이",
+ "르는",
+ "되었",
+ "▁즐기",
+ "▁모르",
+ "하시는",
+ "▁하늘",
+ "▁주차",
+ "▁상승",
+ "▁카드",
+ "▁싶어",
+ "▁수익",
+ "▁지금까지",
+ "▁사항",
+ "되면서",
+ "존",
+ "성과",
+ "▁분명",
+ "▁것과",
+ "▁당신",
+ "▁완전히",
+ "▁당신의",
+ "▁예산",
+ "▁것에",
+ "겠다",
+ "▁써",
+ "▁시작했다",
+ "자로",
+ "▁개정",
+ "슨",
+ "▁착",
+ "▁중요하다",
+ "▁혼자",
+ "▁청년",
+ "▁말한다",
+ "시설",
+ "▁반영",
+ "리아",
+ "▁형성",
+ "▁건설",
+ "▁소재",
+ "학생",
+ "▁보장",
+ "▁삼성",
+ "▁의견",
+ "감이",
+ "▁겨울",
+ "▁개념",
+ "적이고",
+ "▁이루어",
+ "▁고통",
+ "▁적이",
+ "▁대부분의",
+ "▁눈에",
+ "탕",
+ "▁기타",
+ "▁옷",
+ "▁만약",
+ "싸",
+ "들에",
+ "만원",
+ "▁출시",
+ "▁하여",
+ "▁영역",
+ "▁못하는",
+ "▁자녀",
+ "▁성과",
+ "▁보험",
+ "▁남성",
+ "▁핵",
+ "▁보도",
+ "▁협력",
+ "▁정부가",
+ "▁이용할",
+ "▁편안",
+ "▁주로",
+ "▁생각한다",
+ "관리",
+ "▁완성",
+ "▁방향",
+ "▁있으면",
+ "▁커피",
+ "▁열심히",
+ "▁없다는",
+ "아야",
+ "▁지구",
+ "▁혼",
+ "학교",
+ "텐",
+ "▁하는데",
+ "섭",
+ "▁특별한",
+ "쁘",
+ "▁스포츠",
+ "▁작성된",
+ "▁제외",
+ "▁바다",
+ "하라",
+ "▁실패",
+ "▁쓸",
+ "▁때문입니다",
+ "지지",
+ "▁감소",
+ "▁글을",
+ "▁종류",
+ "▁다니",
+ "▁곳이",
+ "▁차이",
+ "▁제기",
+ "▁찾을",
+ "▁혁신",
+ "털",
+ "옥",
+ "셨",
+ "▁충분히",
+ "▁트럼프",
+ "▁존",
+ "▁하였다",
+ "▁불안",
+ "만큼",
+ "보면",
+ "▁아닙니다",
+ "▁예방",
+ "르고",
+ "▁상황에서",
+ "▁어머니",
+ "▁외부",
+ "▁낙",
+ "▁아름다운",
+ "▁오랜",
+ "▁그룹",
+ "되며",
+ "▁회의",
+ "▁가득",
+ "▁대회",
+ "▁옆",
+ "▁아들",
+ "▁트립어드바이저",
+ "▁자신을",
+ "▁전문가",
+ "욕",
+ "▁반복",
+ "럼",
+ "▁위하여",
+ "▁머",
+ "▁푸",
+ "▁그렇지",
+ "▁삶의",
+ "▁당신은",
+ "전을",
+ "▁틀",
+ "▁공동",
+ "▁그리스도",
+ "스타",
+ "▁공공",
+ "대학교",
+ "▁적극",
+ "▁불편",
+ "▁반면",
+ "▁있었던",
+ "▁했습니다",
+ "▁뉴스",
+ "▁나오는",
+ "께서",
+ "보험",
+ "▁드라마",
+ "▁겁니다",
+ "문을",
+ "활동",
+ "▁익",
+ "▁하면서",
+ "▁빠르게",
+ "▁회복",
+ "▁비즈니스",
+ "▁어린",
+ "운동",
+ "▁역할",
+ "닝",
+ "▁제공하는",
+ "▁구입",
+ "쾌",
+ "▁길을",
+ "▁염",
+ "▁요리",
+ "▁혈",
+ "▁크기",
+ "▁있었습니다",
+ "▁문재인",
+ "▁담당",
+ "▁소식",
+ "▁뛰어",
+ "▁전환",
+ "▁구축",
+ "▁젊은",
+ "▁지정",
+ "▁기회",
+ "▁편의",
+ "▁학습",
+ "비를",
+ "▁지키",
+ "세를",
+ "▁등에",
+ "▁예수님",
+ "▁직장",
+ "개의",
+ "▁이상의",
+ "내는",
+ "리지",
+ "하려면",
+ "정부",
+ "▁선물",
+ "▁언제",
+ "▁늦",
+ "▁동의",
+ "▁미리",
+ "회의",
+ "▁단체",
+ "▁도착",
+ "사이트",
+ "▁장면",
+ "▁쓴",
+ "▁정의",
+ "려면",
+ "▁자세한",
+ "보는",
+ "▁번역입니다",
+ "▁대체",
+ "▁장기",
+ "▁위에",
+ "▁어려움",
+ "▁배경",
+ "▁찾는",
+ "년에",
+ "▁이루",
+ "▁리뷰의",
+ "▁수있는",
+ "▁같아요",
+ "▁무대",
+ "보세요",
+ "귀",
+ "▁스마트폰",
+ "▁벌어",
+ "▁왔다",
+ "라이",
+ "▁방안",
+ "준다",
+ "▁설계",
+ "▁이벤트",
+ "▁업",
+ "랜",
+ "오는",
+ "간다",
+ "▁다양",
+ "▁중심으로",
+ "▁사람들의",
+ "경제",
+ "▁가능하다",
+ "▁논란",
+ "기업",
+ "▁다가",
+ "리그",
+ "년대",
+ "▁기분",
+ "▁효율",
+ "▁벽",
+ "▁출장",
+ "았습니다",
+ "세요",
+ "▁무슨",
+ "▁잘못",
+ "▁주문",
+ "▁각각",
+ "산업",
+ "먹",
+ "▁만에",
+ "▁남북",
+ "▁드러",
+ "▁약속",
+ "▁전기",
+ "▁독립",
+ "서비스",
+ "답",
+ "▁정부는",
+ "▁결과를",
+ "▁다음은",
+ "▁블",
+ "▁생각합니다",
+ "▁소통",
+ "▁끼",
+ "▁프랑스",
+ "▁모습이",
+ "▁액",
+ "쿠",
+ "▁앞에",
+ "▁되기",
+ "정보",
+ "▁수술",
+ "▁불구하고",
+ "▁오전",
+ "▁화면",
+ "▁곡",
+ "▁대상으로",
+ "▁출신",
+ "갑",
+ "▁숙",
+ "▁러시아",
+ "▁쉬",
+ "▁프",
+ "웠",
+ "됐",
+ "▁마음이",
+ "▁못했다",
+ "▁관심이",
+ "▁종교",
+ "퇴",
+ "▁선생님",
+ "▁도움을",
+ "▁정부의",
+ "▁주택",
+ "혈",
+ "▁이와",
+ "닥",
+ "▁활동을",
+ "대를",
+ "하려는",
+ "▁관련된",
+ "▁받",
+ "▁필수",
+ "싱",
+ "▁기능을",
+ "▁끌",
+ "▁부동산",
+ "▁바뀌",
+ "이라면",
+ "집니다",
+ "▁대해서는",
+ "▁운전",
+ "좌",
+ "회를",
+ "▁시각",
+ "자와",
+ "▁초기",
+ "법을",
+ "▁상상",
+ "임을",
+ "쳤다",
+ "▁장점",
+ "점이",
+ "▁개의",
+ "지역",
+ "▁이들은",
+ "시킬",
+ "겠다는",
+ "므로",
+ "▁봉",
+ "▁무엇보다",
+ "▁여부",
+ "▁규제",
+ "▁가슴",
+ "▁봄",
+ "▁비슷한",
+ "▁나의",
+ "▁쉽지",
+ "▁인천",
+ "▁건축",
+ "▁기반",
+ "▁빠른",
+ "▁통해서",
+ "▁향상",
+ "으로부터",
+ "농",
+ "▁예수",
+ "▁소비",
+ "▁기획",
+ "▁인터뷰",
+ "억원",
+ "▁웃",
+ "▁좋습니다",
+ "▁홈페이지",
+ "▁평균",
+ "▁소설",
+ "▁죽음",
+ "▁훈련",
+ "▁성경",
+ "하다는",
+ "▁사망",
+ "원은",
+ "함으로써",
+ "▁그래도",
+ "자에게",
+ "▁과정을",
+ "▁마케팅",
+ "▁안내",
+ "일부터",
+ "▁나온",
+ "▁청와대",
+ "▁대구",
+ "▁개최",
+ "▁받았",
+ "▁제품을",
+ "▁특별",
+ "꺼",
+ "지가",
+ "▁홈",
+ "앙",
+ "▁체크",
+ "장에서",
+ "촌",
+ "▁유명",
+ "▁제조",
+ "기간",
+ "▁응",
+ "나요",
+ "리스",
+ "▁딱",
+ "▁바꾸",
+ "▁빨리",
+ "었고",
+ "▁없고",
+ "끈",
+ "▁살펴보",
+ "▁점점",
+ "심을",
+ "▁어렵다",
+ "▁이하",
+ "▁금액",
+ "▁승리",
+ "▁절차",
+ "▁남편",
+ "▁해석",
+ "▁여기서",
+ "▁클릭",
+ "▁나를",
+ "▁교통",
+ "었는데",
+ "▁편집",
+ "물이",
+ "웃",
+ "▁사이에",
+ "▁졸업",
+ "▁그녀",
+ "▁메시지",
+ "▁단순",
+ "첨",
+ "폴",
+ "혼",
+ "▁누구나",
+ "▁제공합니다",
+ "▁입니다",
+ "▁청소년",
+ "하다고",
+ "▁올리",
+ "▁받으",
+ "▁알게",
+ "하고자",
+ "▁지금은",
+ "되어야",
+ "▁쿠",
+ "▁거기",
+ "스가",
+ "▁됐",
+ "▁저자",
+ "▁먹는",
+ "하려고",
+ "자들의",
+ "▁그것이",
+ "▁디지털",
+ "▁바라보",
+ "▁즐길",
+ "▁레이",
+ "▁라이",
+ "▁미국의",
+ "보니",
+ "▁확",
+ "▁구글",
+ "▁감염",
+ "▁보유",
+ "▁늘어",
+ "▁주민",
+ "턴",
+ "▁참가",
+ "▁바라",
+ "둥",
+ "웠다",
+ "▁무료로",
+ "인은",
+ "쯤",
+ "▁이유로",
+ "조사",
+ "▁내용은",
+ "▁질병",
+ "힐",
+ "정책",
+ "에선",
+ "▁짓",
+ "▁대통령이",
+ "▁걷",
+ "▁타고",
+ "▁부분이",
+ "완",
+ "▁지도",
+ "드리",
+ "▁아내",
+ "▁뿐만",
+ "기술",
+ "▁통한",
+ "▁불가능",
+ "▁보안",
+ "▁정당",
+ "줍니다",
+ "▁확장",
+ "▁캐",
+ "▁합의",
+ "▁최종",
+ "▁저장",
+ "▁팬",
+ "▁주고",
+ "▁티",
+ "징",
+ "짐",
+ "▁기회를",
+ "▁낮은",
+ "▁고용",
+ "촉",
+ "킨",
+ "▁플랫폼",
+ "슈",
+ "▁노출",
+ "▁실행",
+ "▁바탕으로",
+ "소를",
+ "▁봐",
+ "시아",
+ "▁페이지",
+ "삼",
+ "▁포기",
+ "▁아시아",
+ "▁내년",
+ "▁약간",
+ "▁진짜",
+ "▁워",
+ "▁사람들에게",
+ "▁끝나",
+ "▁범",
+ "▁인도",
+ "▁일자리",
+ "출장마사지",
+ "휴",
+ "겠지만",
+ "▁인한",
+ "▁나온다",
+ "▁본다",
+ "▁조성",
+ "▁스타",
+ "▁평소",
+ "빙",
+ "▁성격",
+ "▁갈등",
+ "▁점을",
+ "▁흔",
+ "▁깊은",
+ "▁전했다",
+ "▁업계",
+ "▁방식으로",
+ "▁좋아하는",
+ "▁저녁",
+ "되었습니다",
+ "▁기계",
+ "▁근거",
+ "▁달러",
+ "셀",
+ "짝",
+ "▁기초",
+ "▁과연",
+ "롤",
+ "▁누군가",
+ "▁굳",
+ "▁의지",
+ "하겠다",
+ "▁잠시",
+ "▁상담",
+ "뿐만",
+ "▁얼",
+ "업체",
+ "▁맥",
+ "▁믿음",
+ "▁쓰는",
+ "▁목사",
+ "▁전반",
+ "▁항공권",
+ "▁해주",
+ "▁직업",
+ "▁인간의",
+ "봐야",
+ "▁타이",
+ "▁때까지",
+ "치고",
+ "▁상당히",
+ "렬",
+ "▁멀",
+ "▁예를",
+ "시킨",
+ "▁주인공",
+ "▁기념",
+ "▁되었습니다",
+ "뿐",
+ "▁소유",
+ "▁코로나",
+ "▁끊",
+ "▁은행",
+ "▁빠져",
+ "했는데",
+ "▁수요",
+ "▁다운로드",
+ "▁단어",
+ "▁빼",
+ "낭",
+ "▁대통령은",
+ "느",
+ "▁조정",
+ "▁싸",
+ "▁있으니",
+ "▁웃음",
+ "▁출연",
+ "부는",
+ "▁단지",
+ "▁그렇다면",
+ "▁중단",
+ "▁시점",
+ "▁부르",
+ "▁힘든",
+ "조차",
+ "▁앞에서",
+ "몬",
+ "▁냉",
+ "▁수출",
+ "▁원래",
+ "▁때마다",
+ "▁축구",
+ "▁외국인",
+ "▁흥미",
+ "▁중에서",
+ "빛",
+ "▁재미",
+ "▁권리",
+ "▁자랑",
+ "▁말이다",
+ "▁그들이",
+ "▁느낄",
+ "겁",
+ "뜨",
+ "▁복잡",
+ "▁정권",
+ "▁활성화",
+ "▁매출",
+ "▁재미있",
+ "▁조합",
+ "웨",
+ "▁괴",
+ "▁대하여",
+ "▁갖추",
+ "다가",
+ "▁친구들",
+ "▁생각하는",
+ "▁일은",
+ "▁듣고",
+ "▁살고",
+ "▁연락",
+ "▁홀",
+ "▁했던",
+ "▁옵션",
+ "▁장치",
+ "▁우주",
+ "▁있겠",
+ "▁주의",
+ "가요",
+ "듯이",
+ "▁완",
+ "하니",
+ "▁이름을",
+ "▁것이라는",
+ "▁파트너",
+ "▁상황을",
+ "▁먹고",
+ "▁관계자는",
+ "▁없다고",
+ "▁거부",
+ "▁토론",
+ "▁논",
+ "▁사태",
+ "▁진단",
+ "▁보수",
+ "▁유리",
+ "▁징",
+ "이라도",
+ "▁지급",
+ "▁경험을",
+ "▁홍보",
+ "▁공정",
+ "▁마시",
+ "일까지",
+ "▁꽤",
+ "▁대형",
+ "▁돌아가",
+ "▁리뷰",
+ "했다는",
+ "▁포인트",
+ "▁취업",
+ "▁새로",
+ "▁빨",
+ "▁실천",
+ "▁꼽",
+ "▁진출",
+ "▁수집",
+ "▁맞춰",
+ "▁센터",
+ "▁향후",
+ "사항",
+ "궁",
+ "▁기다리",
+ "▁흐름",
+ "톤",
+ "▁블로그",
+ "콜걸",
+ "▁인구",
+ "렉",
+ "▁더불어",
+ "▁효과를",
+ "▁가까운",
+ "▁곳에",
+ "보기",
+ "었지만",
+ "▁밥",
+ "▁창업",
+ "▁강한",
+ "▁공장",
+ "▁혜택",
+ "교회",
+ "▁펼쳐",
+ "▁불러",
+ "▁도구",
+ "▁원칙",
+ "죄",
+ "▁결코",
+ "▁얻을",
+ "▁여행자",
+ "▁이번에",
+ "▁카페",
+ "맨",
+ "▁방법이",
+ "▁오르",
+ "▁권력",
+ "▁없었",
+ "▁값",
+ "멸",
+ "▁설명했다",
+ "▁위원장",
+ "▁그녀는",
+ "째",
+ "룸",
+ "▁물건",
+ "▁편리",
+ "▁이것이",
+ "▁카메라",
+ "풀",
+ "▁여유",
+ "▁메뉴",
+ "▁외국",
+ "찌",
+ "▁민주",
+ "▁통일",
+ "▁소속",
+ "쓰",
+ "▁꾸준히",
+ "받는",
+ "▁품질",
+ "출장안마",
+ "▁사진을",
+ "▁네트워크",
+ "▁차별",
+ "▁것인가",
+ "▁자리를",
+ "▁방법은",
+ "▁차례",
+ "멘",
+ "▁않으",
+ "허",
+ "▁세대",
+ "룩",
+ "▁제출",
+ "▁긍정적",
+ "혁",
+ "화된",
+ "▁장애",
+ "▁공감",
+ "▁한국의",
+ "▁교사",
+ "▁거쳐",
+ "쇄",
+ "▁완벽한",
+ "▁안에서",
+ "▁코스",
+ "▁들고",
+ "▁갖",
+ "량이",
+ "▁이제는",
+ "▁확인할",
+ "빈",
+ "▁자격",
+ "거든요",
+ "으면서",
+ "씨는",
+ "▁깊",
+ "틴",
+ "스의",
+ "▁민족",
+ "▁누가",
+ "특",
+ "▁작용",
+ "▁민주당",
+ "윤",
+ "칙",
+ "해도",
+ "개발",
+ "▁사람들을",
+ "▁떨어지",
+ "응",
+ "▁이때",
+ "▁만들기",
+ "▁명의",
+ "▁수입",
+ "앉",
+ "▁아무리",
+ "드립니다",
+ "맥",
+ "▁뉴",
+ "▁기울",
+ "▁보이지",
+ "▁실험",
+ "▁점에서",
+ "냈",
+ "▁계획이다",
+ "▁자체가",
+ "▁않도록",
+ "▁입력",
+ "▁우리에게",
+ "은행",
+ "▁법률",
+ "년부터",
+ "▁플레이",
+ "▁세금",
+ "▁자세",
+ "늘",
+ "짜",
+ "▁히",
+ "▁영향",
+ "▁납",
+ "▁베이",
+ "▁만들고",
+ "▁물질",
+ "단체",
+ "▁문의",
+ "▁시작한",
+ "꾸",
+ "▁설립",
+ "▁불법",
+ "▁등으로",
+ "▁벗어나",
+ "▁맺",
+ "▁출발",
+ "▁영업",
+ "▁발언",
+ "▁신체",
+ "▁왔",
+ "▁심리",
+ "▁솔",
+ "▁길이",
+ "▁통과",
+ "연합",
+ "적이다",
+ "켜",
+ "듬",
+ "▁마음에",
+ "▁무엇이",
+ "스럽",
+ "▁아이디어",
+ "▁놓고",
+ "▁기술을",
+ "▁자극",
+ "짓",
+ "혔",
+ "▁않게",
+ "겼다",
+ "▁스트레스",
+ "▁업데이트",
+ "▁대책",
+ "둔",
+ "▁일반적으로",
+ "▁내용이",
+ "▁사장",
+ "▁이용하실",
+ "▁곳에서",
+ "▁범위",
+ "▁준다",
+ "함이",
+ "▁벗",
+ "튼",
+ "▁걸어",
+ "더니",
+ "▁높다",
+ "▁말하는",
+ "하였습니다",
+ "▁무엇을",
+ "게임",
+ "▁샤",
+ "▁마무리",
+ "▁그만큼",
+ "▁굉장히",
+ "엄",
+ "▁간단",
+ "별로",
+ "▁그러면",
+ "김",
+ "▁확산",
+ "▁위협",
+ "했어요",
+ "▁의식",
+ "▁근무",
+ "하기로",
+ "▁중간",
+ "▁매장",
+ "▁효",
+ "▁일이다",
+ "▁공항",
+ "▁성적",
+ "▁말고",
+ "왔",
+ "▁강의",
+ "였습니다",
+ "▁변화를",
+ "트리",
+ "▁적합",
+ "▁풀어",
+ "▁유형",
+ "인들이",
+ "▁이처럼",
+ "▁짐",
+ "▁아는",
+ "▁앉아",
+ "▁주님",
+ "였던",
+ "▁둔",
+ "▁의무",
+ "앤",
+ "▁프로그램을",
+ "▁식물",
+ "▁체계",
+ "▁덜",
+ "쉬",
+ "▁민간",
+ "벽",
+ "▁나아가",
+ "▁가능합니다",
+ "▁덕",
+ "▁태도",
+ "▁뜨",
+ "▁알아보",
+ "▁강력한",
+ "▁재판",
+ "▁상처",
+ "▁매년",
+ "▁덕분에",
+ "▁대표는",
+ "컬",
+ "▁차이가",
+ "세기",
+ "▁않을까",
+ "▁배치",
+ "▁위원",
+ "▁깨끗",
+ "낸다",
+ "톡",
+ "▁예측",
+ "▁장비",
+ "▁카지노",
+ "▁위로",
+ "▁이유가",
+ "▁한반도",
+ "▁예전",
+ "▁끌어",
+ "몰",
+ "▁들었다",
+ "▁주식",
+ "▁강조했다",
+ "▁진실",
+ "▁밑",
+ "▁선수들",
+ "몽",
+ "▁대전",
+ "▁협상",
+ "▁극복",
+ "았던",
+ "▁오늘날",
+ "▁불과",
+ "▁정확한",
+ "▁시선",
+ "▁정치적",
+ "버린",
+ "▁세상을",
+ "번째",
+ "▁남아",
+ "량을",
+ "▁성능",
+ "먼",
+ "펜",
+ "▁모르는",
+ "▁바닥",
+ "▁밝혀",
+ "▁괜찮",
+ "▁재정",
+ "▁달려",
+ "▁보였다",
+ "▁책임을",
+ "▁사용하여",
+ "▁스마트",
+ "▁개혁",
+ "킬",
+ "그룹",
+ "▁모르겠",
+ "▁중이다",
+ "▁경우도",
+ "▁사업을",
+ "▁크다",
+ "▁부부",
+ "▁좋았",
+ "▁노인",
+ "▁읽어",
+ "▁의심",
+ "대학",
+ "▁복지",
+ "▁가치를",
+ "▁유치",
+ "픽",
+ "▁버스",
+ "▁가격이",
+ "▁회사는",
+ "▁범죄",
+ "▁내놓",
+ "▁뿌리",
+ "잉",
+ "▁최저가",
+ "▁혐의",
+ "▁사람에게",
+ "▁점이",
+ "릭",
+ "▁모른다",
+ "꾼",
+ "▁그럴",
+ "▁상징",
+ "나무",
+ "▁달성",
+ "하셨",
+ "▁지배",
+ "▁작동",
+ "▁갑자기",
+ "▁어떠한",
+ "▁주민들",
+ "없",
+ "▁부여",
+ "▁단순히",
+ "▁창조",
+ "▁도로",
+ "▁관점",
+ "▁느낌이",
+ "▁이용해",
+ "▁중인",
+ "▁있음을",
+ "▁종종",
+ "▁그러한",
+ "▁군사",
+ "▁광주",
+ "▁따로",
+ "회사",
+ "▁나왔다",
+ "▁연습",
+ "▁씨는",
+ "▁연출",
+ "▁과제",
+ "▁충격",
+ "▁휴가",
+ "맛",
+ "젠",
+ "▁이론",
+ "홀",
+ "▁외교",
+ "컴",
+ "▁인류",
+ "▁봤",
+ "▁재료",
+ "었어요",
+ "값",
+ "지면서",
+ "▁상황에",
+ "▁시리즈",
+ "▁날씨",
+ "▁뽑",
+ "었을",
+ "▁종합",
+ "▁맨",
+ "▁제공하고",
+ "▁형식",
+ "▁신문",
+ "▁효과가",
+ "▁게다가",
+ "▁오픈",
+ "▁통하여",
+ "▁완전",
+ "▁움직이",
+ "▁철학",
+ "▁모여",
+ "튀",
+ "▁의혹",
+ "▁받지",
+ "냥",
+ "▁좋을",
+ "▁가서",
+ "지원",
+ "▁소프트웨어",
+ "▁집단",
+ "시키고",
+ "▁방법으로",
+ "▁호텔을",
+ "▁느",
+ "싼",
+ "▁소득",
+ "▁미술",
+ "▁보관",
+ "▁대선",
+ "▁박근혜",
+ "▁테스트",
+ "▁무선",
+ "돈",
+ "▁떨어",
+ "겐",
+ "▁아니면",
+ "▁미디어",
+ "▁경우에",
+ "▁기독교",
+ "▁질환",
+ "롱",
+ "떨",
+ "랄",
+ "▁향해",
+ "▁서울시",
+ "▁비롯한",
+ "▁않기",
+ "▁증거",
+ "▁제일",
+ "▁처음으로",
+ "▁대통령의",
+ "▁다소",
+ "▁맛있",
+ "▁기여",
+ "섰",
+ "쁜",
+ "▁다루",
+ "▁신앙",
+ "▁최대한",
+ "▁쏟아",
+ "웨이",
+ "▁만한",
+ "▁전투",
+ "▁직원들",
+ "세대",
+ "겠다고",
+ "▁힘이",
+ "썼",
+ "▁국정",
+ "거래",
+ "랍",
+ "▁우승",
+ "▁축제",
+ "▁짜",
+ "▁탓",
+ "▁발생한",
+ "동안",
+ "▁시민들",
+ "▁것인지",
+ "▁작업을",
+ "▁책은",
+ "▁발달",
+ "▁계산",
+ "▁의미를",
+ "▁사랑을",
+ "▁고급",
+ "▁확실",
+ "▁긴장",
+ "레스",
+ "▁구분",
+ "자리",
+ "덤",
+ "▁당연히",
+ "▁좋지",
+ "▁신고",
+ "▁잡아",
+ "▁드리",
+ "▁할인",
+ "▁추구",
+ "▁쉬운",
+ "▁금지",
+ "▁연속",
+ "▁하게",
+ "▁근처",
+ "▁모두가",
+ "얻",
+ "▁허용",
+ "대표",
+ "▁풍경",
+ "▁훌륭한",
+ "▁스토리",
+ "병원",
+ "▁아닌가",
+ "같은",
+ "▁기회가",
+ "▁뭔가",
+ "▁다르다",
+ "▁심지어",
+ "▁측정",
+ "▁새롭게",
+ "▁사상",
+ "▁사실상",
+ "▁아닐까",
+ "해주는",
+ "▁라인",
+ "시대",
+ "맞",
+ "▁만난",
+ "왔습니다",
+ "▁조절",
+ "▁똑같",
+ "▁지난달",
+ "▁요인",
+ "▁채용",
+ "▁생긴",
+ "▁삭제",
+ "카드",
+ "▁대출",
+ "학년",
+ "따",
+ "▁국민의",
+ "▁라며",
+ "▁마찬가지",
+ "▁비율",
+ "위원",
+ "▁겸",
+ "▁깊이",
+ "▁늘어나",
+ "푸",
+ "▁옥",
+ "▁나중에",
+ "춤",
+ "▁갑",
+ "▁관계를",
+ "▁식당",
+ "▁쓰고",
+ "▁었",
+ "▁실현",
+ "▁봉사",
+ "으려",
+ "▁유통",
+ "▁태양",
+ "▁열정",
+ "▁실력",
+ "▁꼬",
+ "▁선언",
+ "▁관계자",
+ "▁공무원",
+ "▁독자",
+ "▁멋진",
+ "써",
+ "▁말할",
+ "▁대답",
+ "픈",
+ "릅니다",
+ "▁약관",
+ "▁했지만",
+ "▁인권",
+ "▁분들이",
+ "▁통신",
+ "▁가까이",
+ "▁완료",
+ "칸",
+ "하여야",
+ "▁경쟁력",
+ "▁방지",
+ "죽",
+ "▁제목",
+ "했기",
+ "▁것만",
+ "▁당장",
+ "봤다",
+ "▁변호사",
+ "어져",
+ "꿀",
+ "구나",
+ "▁아동",
+ "▁성인",
+ "▁신규",
+ "▁뒷",
+ "▁별로",
+ "▁보고서",
+ "둘",
+ "▁휘",
+ "탑",
+ "▁먼",
+ "▁그러므로",
+ "▁지불",
+ "껏",
+ "▁띄",
+ "틱",
+ "져야",
+ "▁영양",
+ "▁통증",
+ "▁지속적으로",
+ "▁레스토랑",
+ "▁섭취",
+ "▁점은",
+ "▁멤버",
+ "▁내리",
+ "▁코드",
+ "했으며",
+ "습니까",
+ "▁뒤에",
+ "숨",
+ "문제",
+ "▁진정한",
+ "▁롯데",
+ "출장샵",
+ "▁키우",
+ "룡",
+ "▁취소",
+ "▁주말",
+ "셨습니다",
+ "▁심각한",
+ "▁알리",
+ "▁엄청난",
+ "▁익숙",
+ "▁자금",
+ "▁흔들",
+ "▁흐",
+ "▁버리",
+ "▁아니고",
+ "▁능력을",
+ "▁움직임",
+ "▁공기",
+ "▁잇",
+ "▁짧은",
+ "▁적절한",
+ "▁즉시",
+ "▁전부",
+ "▁콜",
+ "휘",
+ "받은",
+ "▁굴",
+ "▁못한다",
+ "▁올려",
+ "▁근본",
+ "▁모아",
+ "하겠다는",
+ "▁맞추",
+ "▁적극적으로",
+ "▁작년",
+ "▁식품",
+ "▁결론",
+ "▁노동자",
+ "▁나올",
+ "쇠",
+ "▁너무나",
+ "▁고양이",
+ "▁항목",
+ "▁무엇인가",
+ "스코",
+ "졌습니다",
+ "▁희",
+ "알",
+ "▁뉴욕",
+ "▁그녀의",
+ "▁위치한",
+ "▁다리",
+ "▁댓글",
+ "▁마련되어",
+ "▁버전",
+ "▁앞두고",
+ "▁그럼에도",
+ "놓고",
+ "▁눈물",
+ "프레",
+ "해야합니다",
+ "즐",
+ "▁총리",
+ "롭게",
+ "▁국민들",
+ "▁전문가들",
+ "핀",
+ "▁아직도",
+ "▁언제나",
+ "▁못할",
+ "▁통제",
+ "팩",
+ "협회",
+ "버리",
+ "▁같아",
+ "▁특수",
+ "▁자산",
+ "릇",
+ "▁나머지",
+ "든지",
+ "▁패션",
+ "▁그저",
+ "▁구원",
+ "▁데이터를",
+ "▁평생",
+ "▁여론",
+ "▁보상",
+ "룰",
+ "▁팬들",
+ "▁한국인",
+ "▁유명한",
+ "▁감동",
+ "▁장애인",
+ "▁나타났다",
+ "쥐",
+ "▁강남",
+ "▁아이템",
+ "▁제공됩니다",
+ "▁시청",
+ "▁상호",
+ "▁바란다",
+ "▁뿐이다",
+ "▁맞아",
+ "▁하락",
+ "쌍",
+ "▁동영상",
+ "▁했는데",
+ "▁인증",
+ "답니다",
+ "▁집에서",
+ "▁거예요",
+ "룬",
+ "닉",
+ "▁넘는",
+ "▁숫자",
+ "▁손님",
+ "▁투표",
+ "▁홍콩",
+ "▁출장안마",
+ "누",
+ "▁가구",
+ "▁박사",
+ "▁따뜻한",
+ "▁생성",
+ "쳤",
+ "▁그럼",
+ "꽃",
+ "▁세우",
+ "▁목록",
+ "▁무시",
+ "▁낳",
+ "▁교수는",
+ "▁셈이다",
+ "▁결제",
+ "▁의원은",
+ "▁조언",
+ "딜",
+ "▁이슈",
+ "▁바이러스",
+ "밍",
+ "▁각자",
+ "리스트",
+ "욱",
+ "▁최선을",
+ "▁블랙",
+ "빠",
+ "홍",
+ "▁알려져",
+ "닭",
+ "▁최신",
+ "▁통계",
+ "▁복음",
+ "▁선호",
+ "▁피해자",
+ "▁논리",
+ "▁애플",
+ "▁부상",
+ "륙",
+ "▁비밀",
+ "▁입장에서",
+ "▁무기",
+ "콤",
+ "▁개별",
+ "셨다",
+ "오피",
+ "▁이웃",
+ "▁숲",
+ "프트",
+ "▁해보",
+ "▁신속",
+ "▁프리",
+ "▁무리",
+ "뷰",
+ "넷",
+ "▁경기출장",
+ "졸",
+ "▁인근",
+ "▁진정",
+ "▁찾기",
+ "▁그려",
+ "흘",
+ "▁실수",
+ "▁체제",
+ "▁문자",
+ "▁드립니다",
+ "쌀",
+ "▁버튼",
+ "▁쇼",
+ "▁참조",
+ "놀",
+ "▁알려졌다",
+ "▁공사",
+ "닐",
+ "▁아빠",
+ "▁부탁",
+ "▁아기",
+ "멍",
+ "▁비슷",
+ "▁다수",
+ "▁숙소",
+ "럴",
+ "▁희생",
+ "최",
+ "▁필요합니다",
+ "▁컬러",
+ "▁서버",
+ "▁기준으로",
+ "▁읽고",
+ "▁문학",
+ "▁경기도",
+ "▁선발",
+ "▁베트남",
+ "머니",
+ "▁위반",
+ "스럽게",
+ "▁성분",
+ "하시면",
+ "▁거주",
+ "▁온도",
+ "▁부분은",
+ "▁만남",
+ "▁것보다",
+ "같이",
+ "▁대안",
+ "▁전용",
+ "▁파괴",
+ "▁동료",
+ "▁누리",
+ "하려",
+ "▁들어서",
+ "하면서도",
+ "▁담아",
+ "▁채널",
+ "▁부모님",
+ "▁하겠습니다",
+ "웅",
+ "▁불만",
+ "▁생존",
+ "▁좋겠다",
+ "켓",
+ "▁자연스럽게",
+ "▁심사",
+ "큐",
+ "▁이끌어",
+ "대회",
+ "▁역량",
+ "잎",
+ "▁그린",
+ "해졌다",
+ "▁살펴",
+ "▁전공",
+ "틈",
+ "으로써",
+ "▁들어오",
+ "▁무역",
+ "▁묵",
+ "▁경계",
+ "▁궁",
+ "괄",
+ "한테",
+ "환경",
+ "▁결합",
+ "위원장",
+ "▁흑",
+ "럭",
+ "티브",
+ "▁잘못된",
+ "▁진보",
+ "▁균형",
+ "▁규칙",
+ "통신",
+ "▁실내",
+ "▁경제적",
+ "▁없기",
+ "솔",
+ "▁좁",
+ "▁임금",
+ "▁주소",
+ "▁넣어",
+ "▁탄생",
+ "잔",
+ "▁덧붙였다",
+ "▁이전에",
+ "▁멀리",
+ "▁그곳",
+ "소리",
+ "▁분리",
+ "닿",
+ "▁손상",
+ "▁동일한",
+ "▁왼쪽",
+ "▁관광객",
+ "▁헌법",
+ "▁형태로",
+ "▁휴식",
+ "▁점이다",
+ "▁자전거",
+ "캠",
+ "▁헬",
+ "▁갖는",
+ "이에요",
+ "▁근육",
+ "▁거듭",
+ "▁자본",
+ "▁그러면서",
+ "▁발생하는",
+ "▁구현",
+ "발전",
+ "▁하자",
+ "▁청구",
+ "봤",
+ "▁공동체",
+ "방법",
+ "▁비난",
+ "▁링크",
+ "▁습관",
+ "▁마찬가지로",
+ "▁걸쳐",
+ "▁싶습니다",
+ "▁혹시",
+ "▁올림픽",
+ "▁골프",
+ "▁와서",
+ "▁오랫동안",
+ "▁분명히",
+ "▁발휘",
+ "▁않아도",
+ "잖아요",
+ "계획",
+ "납",
+ "▁재산",
+ "▁흘러",
+ "젤",
+ "▁갖춘",
+ "▁머물",
+ "▁연주",
+ "▁착용",
+ "▁보이고",
+ "엽",
+ "▁확정",
+ "친다",
+ "받고",
+ "빵",
+ "▁감각",
+ "▁로봇",
+ "▁대표적인",
+ "▁완벽",
+ "▁조용",
+ "▁창출",
+ "▁뛰어난",
+ "▁해소",
+ "▁생겨",
+ "▁나에게",
+ "▁마지막으로",
+ "업계",
+ "▁빚",
+ "▁호흡",
+ "▁표정",
+ "▁밝히",
+ "톱",
+ "▁가끔",
+ "▁필자",
+ "즘",
+ "▁통화",
+ "▁대기업",
+ "문학",
+ "▁심장",
+ "▁활발",
+ "▁봅니다",
+ "▁오른쪽",
+ "▁없지만",
+ "▁사랑하는",
+ "▁나쁜",
+ "켰",
+ "▁닫",
+ "▁판결",
+ "▁열어",
+ "▁부족한",
+ "▁자원",
+ "섞",
+ "본부",
+ "▁폭력",
+ "▁측면",
+ "▁중앙일보",
+ "▁교체",
+ "님께서",
+ "▁만들었다",
+ "▁멋",
+ "흡",
+ "버스",
+ "▁당선",
+ "▁의문",
+ "소득",
+ "릿",
+ "▁검증",
+ "하겠습니다",
+ "쇼",
+ "재단",
+ "렇",
+ "주택",
+ "▁발생할",
+ "▁이스라엘",
+ "▁응원",
+ "▁다녀",
+ "획",
+ "▁헤어",
+ "▁표준",
+ "노동",
+ "▁연장",
+ "▁것이었다",
+ "월부터",
+ "▁있으",
+ "▁명령",
+ "▁선교",
+ "▁무엇인지",
+ "▁있습니까",
+ "▁부문",
+ "▁친절",
+ "▁차단",
+ "▁간단한",
+ "엇",
+ "봐",
+ "▁흔히",
+ "▁이라며",
+ "램",
+ "▁생겼",
+ "▁추억",
+ "▁이끌",
+ "▁맞춤",
+ "영화",
+ "▁아예",
+ "▁절반",
+ "델",
+ "▁않지만",
+ "뼈",
+ "▁않았습니다",
+ "▁농업",
+ "▁구체적인",
+ "렀다",
+ "▁본질",
+ "▁일반적인",
+ "▁점차",
+ "▁조금씩",
+ "▁사유",
+ "▁이루어지",
+ "▁세워",
+ "▁건조",
+ "▁기업들",
+ "텍",
+ "▁완화",
+ "▁계정",
+ "▁보존",
+ "▁재생",
+ "▁지혜",
+ "▁오른",
+ "▁포장",
+ "공사",
+ "▁수수료",
+ "▁그러다",
+ "▁세력",
+ "▁지내",
+ "▁따르",
+ "곱",
+ "▁자신감",
+ "▁총선",
+ "▁주위",
+ "▁있음",
+ "본다",
+ "계약",
+ "▁만날",
+ "덩",
+ "삭",
+ "▁승인",
+ "▁증명",
+ "▁스파",
+ "▁빠지",
+ "▁공통",
+ "핸",
+ "▁관객",
+ "▁분류",
+ "▁색상",
+ "▁정확히",
+ "▁인재",
+ "▁덮",
+ "▁면접",
+ "▁유발",
+ "▁그렇다고",
+ "▁뛰",
+ "겹",
+ "▁관람",
+ "▁악화",
+ "렴",
+ "▁패턴",
+ "▁독특한",
+ "▁대규모",
+ "▁확신",
+ "코리아",
+ "▁법원",
+ "등록",
+ "떡",
+ "▁보면서",
+ "▁분노",
+ "▁중소기업",
+ "▁후반",
+ "▁혼란",
+ "더라",
+ "▁앨범",
+ "▁임대",
+ "▁임신",
+ "▁많습니다",
+ "▁점검",
+ "▁인력",
+ "▁약물",
+ "제품",
+ "▁솔루션",
+ "▁많지",
+ "퀴",
+ "깃",
+ "떼",
+ "▁관찰",
+ "▁강제",
+ "▁실적",
+ "▁전력",
+ "▁문제점",
+ "▁트레",
+ "▁다르게",
+ "▁장식",
+ "▁끊임없이",
+ "▁민주주의",
+ "▁논문",
+ "콜",
+ "▁목적으로",
+ "▁뜨거운",
+ "묵",
+ "▁스테",
+ "▁놀라",
+ "했으나",
+ "빗",
+ "▁알려진",
+ "▁들려",
+ "▁심각",
+ "닌",
+ "밥",
+ "윈",
+ "▁대변",
+ "▁유일한",
+ "▁자세히",
+ "▁진화",
+ "▁분야에서",
+ "굴",
+ "▁체결",
+ "▁세포",
+ "투자",
+ "▁그랬",
+ "깔",
+ "하우스",
+ "▁성령",
+ "▁페이스북",
+ "▁기쁨",
+ "▁느꼈",
+ "▁대처",
+ "▁지도자",
+ "▁오류",
+ "▁초반",
+ "▁배출",
+ "▁응용",
+ "하겠다고",
+ "▁조심",
+ "▁데뷔",
+ "▁할머니",
+ "밭",
+ "시켰다",
+ "추천",
+ "▁별도의",
+ "렵",
+ "토리",
+ "랭",
+ "빅",
+ "▁상대방",
+ "▁모니터",
+ "▁사라지",
+ "▁점수",
+ "▁마스크",
+ "▁소송",
+ "▁입학",
+ "됨",
+ "옛",
+ "▁아무런",
+ "▁동네",
+ "▁적응",
+ "▁많았",
+ "▁출판",
+ "겠죠",
+ "▁충분한",
+ "▁응답",
+ "▁구속",
+ "▁받는다",
+ "▁외에도",
+ "▁쉽고",
+ "▁하느님",
+ "짧",
+ "▁받아들이",
+ "▁느낀",
+ "릉",
+ "▁문장",
+ "뿌",
+ "▁방향으로",
+ "▁동반",
+ "▁줄어들",
+ "▁새벽",
+ "옳",
+ "콩",
+ "▁모임",
+ "▁나타난",
+ "▁좋겠",
+ "▁확실히",
+ "▁받기",
+ "▁떨어진",
+ "▁깨닫",
+ "▁예배",
+ "십니다",
+ "▁못했",
+ "▁야구",
+ "▁표면",
+ "▁구름",
+ "줬다",
+ "▁비디오",
+ "▁쇼핑",
+ "▁우수한",
+ "▁싸움",
+ "▁용기",
+ "팔",
+ "읍",
+ "햇",
+ "▁공포",
+ "엑",
+ "▁있나요",
+ "▁추세",
+ "▁평가하기",
+ "롯",
+ "▁울산",
+ "▁국회의원",
+ "야말로",
+ "▁엔진",
+ "▁군대",
+ "▁날짜",
+ "▁모집",
+ "▁웹사이트",
+ "▁충전",
+ "▁바꿔",
+ "▁도움",
+ "▁살아가는",
+ "▁로마",
+ "▁지점",
+ "▁배터리",
+ "멜",
+ "▁혁명",
+ "▁경력",
+ "▁걸리",
+ "▁아울러",
+ "▁가이드",
+ "▁리더",
+ "▁투쟁",
+ "▁하나님께서",
+ "▁만든다",
+ "▁전망이다",
+ "랙",
+ "▁아닐",
+ "▁기반으로",
+ "증권",
+ "춰",
+ "▁조작",
+ "▁혈액",
+ "▁백성",
+ "컵",
+ "▁놀라운",
+ "▁배송",
+ "밸",
+ "▁거죠",
+ "맘",
+ "▁소녀",
+ "▁많았다",
+ "랩",
+ "▁그걸",
+ "▁네이버",
+ "▁미세먼지",
+ "립니다",
+ "▁아니었다",
+ "▁상대적으로",
+ "▁치열",
+ "▁은혜",
+ "▁알려주",
+ "▁국립",
+ "듀",
+ "▁최초로",
+ "▁폭발",
+ "▁냄새",
+ "▁든다",
+ "▁김정은",
+ "▁적어도",
+ "▁사무실",
+ "마저",
+ "벼",
+ "▁침대",
+ "▁아프",
+ "▁프라",
+ "▁즐겁",
+ "▁충분",
+ "▁조각",
+ "▁플레이어",
+ "▁추정",
+ "▁환영",
+ "▁실질적",
+ "▁삼성전자",
+ "▁올바른",
+ "▁화학",
+ "둑",
+ "▁받게",
+ "▁드러내",
+ "라이트",
+ "▁거대한",
+ "▁연합뉴스",
+ "▁부품",
+ "▁지닌",
+ "▁압박",
+ "▁커뮤니티",
+ "▁의존",
+ "▁청소",
+ "▁중요합니다",
+ "▁있으므로",
+ "▁노조",
+ "▁처벌",
+ "셋",
+ "▁들여",
+ "▁아니지만",
+ "땀",
+ "▁합격",
+ "▁나쁨",
+ "▁어찌",
+ "돕",
+ "더군요",
+ "▁어려워",
+ "▁이메일",
+ "▁테이블",
+ "▁일으키",
+ "▁계절",
+ "팽",
+ "▁동작",
+ "▁바카라",
+ "▁돌려",
+ "▁음료",
+ "▁옮겨",
+ "▁집안",
+ "▁합리적",
+ "깝",
+ "▁영향력",
+ "▁종료",
+ "▁왜냐하면",
+ "▁유용한",
+ "믹",
+ "▁개인적으로",
+ "▁순위",
+ "왔던",
+ "▁집행",
+ "▁어디서",
+ "▁좋음",
+ "▁야외",
+ "▁슈퍼",
+ "▁예비",
+ "▁블록체인",
+ "▁미치는",
+ "▁영혼",
+ "▁고등학교",
+ "▁오퍼",
+ "펀",
+ "▁무조건",
+ "▁셀프",
+ "뉴스",
+ "▁수영장",
+ "갑니다",
+ "▁분양",
+ "▁비교적",
+ "▁떨어져",
+ "▁끝까지",
+ "▁것일까",
+ "▁비롯해",
+ "▁일찍",
+ "▁몇몇",
+ "스턴",
+ "▁흐르",
+ "씻",
+ "▁확률",
+ "공항",
+ "줘",
+ "▁다섯",
+ "▁투입",
+ "더라고요",
+ "▁확인함",
+ "▁측면에서",
+ "▁너희",
+ "▁어깨",
+ "팁",
+ "▁선배",
+ "▁경남",
+ "▁즐거운",
+ "쿨",
+ "▁있었는데",
+ "▁참여해주셔",
+ "펼",
+ "▁나왔",
+ "쫓",
+ "▁소중한",
+ "넘",
+ "▁매체",
+ "▁교환",
+ "▁유튜브",
+ "▁취재",
+ "▁얻는",
+ "▁있는데요",
+ "빌",
+ "▁주시기",
+ "▁아름답",
+ "▁인공지능",
+ "▁나눠",
+ "▁쿠키",
+ "끔",
+ "▁어쩌면",
+ "밟",
+ "뮤",
+ "▁변동",
+ "돋",
+ "▁즐거움",
+ "▁나섰다",
+ "▁계속해서",
+ "렸습니다",
+ "하시기",
+ "▁중요성",
+ "▁저항",
+ "▁건너",
+ "▁진입",
+ "▁깔끔",
+ "▁투명",
+ "▁담긴",
+ "시키기",
+ "묶",
+ "▁교류",
+ "▁시청자",
+ "▁연령",
+ "▁부활",
+ "▁명예",
+ "▁설득",
+ "▁나타내",
+ "주셔서",
+ "▁끝난",
+ "렁",
+ "▁활약",
+ "▁투자자",
+ "턱",
+ "▁벌써",
+ "▁운명",
+ "▁법안",
+ "▁소셜",
+ "맑",
+ "▁생물",
+ "▁블루",
+ "항공",
+ "▁스페셜",
+ "틸",
+ "드리겠습니다",
+ "▁적절",
+ "캔",
+ "▁남겨",
+ "옹",
+ "▁알아야",
+ "튜",
+ "▁얻어",
+ "▁풍부한",
+ "▁갖게",
+ "▁열리는",
+ "▁이다",
+ "▁후보자",
+ "▁몰랐",
+ "캡",
+ "흉",
+ "숭",
+ "뇌",
+ "▁대학생",
+ "포트",
+ "겼",
+ "▁영광",
+ "▁직후",
+ "▁존중",
+ "▁구성원",
+ "쉽",
+ "▁필요성",
+ "▁싫어",
+ "으므로",
+ "▁면역",
+ "▁가르치",
+ "▁있죠",
+ "▁흡수",
+ "▁카카오",
+ "▁현금",
+ "▁정확하게",
+ "▁기본적으로",
+ "▁개입",
+ "▁인정받",
+ "▁없었던",
+ "엉",
+ "▁리조트",
+ "▁담겨",
+ "▁지하철",
+ "▁일주일",
+ "곁",
+ "샵",
+ "▁먹어",
+ "긋",
+ "▁일어난",
+ "섯",
+ "▁즐기실",
+ "▁이탈리아",
+ "줘야",
+ "▁충족",
+ "▁화장품",
+ "▁드러나",
+ "않",
+ "▁들어간",
+ "얀",
+ "▁여겨",
+ "▁파티",
+ "곰",
+ "▁부작용",
+ "▁비록",
+ "하므로",
+ "봅",
+ "▁무언가",
+ "▁개봉",
+ "▁보여준다",
+ "▁강남안마",
+ "냅",
+ "▁널리",
+ "▁영웅",
+ "딘",
+ "넥",
+ "방송",
+ "▁무척",
+ "▁비행기",
+ "▁없애",
+ "▁트렌드",
+ "땅",
+ "▁며칠",
+ "▁자유롭게",
+ "▁얻은",
+ "젖",
+ "▁캐나다",
+ "개혁",
+ "▁촉구",
+ "▁클라우드",
+ "▁다이어트",
+ "▁포함되어",
+ "▁취급",
+ "▁때로는",
+ "▁취약",
+ "▁끝내",
+ "렀",
+ "▁직무",
+ "▁둘째",
+ "캐",
+ "뉴",
+ "▁얻었",
+ "▁점심",
+ "뢰",
+ "벅",
+ "▁노하우",
+ "끓",
+ "▁이외에",
+ "했는지",
+ "▁한마디",
+ "▁취임",
+ "▁아무것도",
+ "▁잃어",
+ "▁접촉",
+ "셈",
+ "윗",
+ "▁보낸",
+ "▁분쟁",
+ "▁있었지만",
+ "▁어울리",
+ "닮",
+ "쩍",
+ "능력",
+ "▁보완",
+ "▁쓰레기",
+ "연구소",
+ "▁멈추",
+ "셉",
+ "뱅",
+ "▁전세계",
+ "롬",
+ "▁민감",
+ "첩",
+ "▁돕는",
+ "▁라이브",
+ "폼",
+ "붙",
+ "붕",
+ "놈",
+ "펴",
+ "뭘",
+ "탱",
+ "뚫",
+ "눌",
+ "뚝",
+ "핵",
+ "닦",
+ "몫",
+ "싫",
+ "갱",
+ "뻐",
+ "섹",
+ "곽",
+ "샌",
+ "컸",
+ "줬",
+ "덴",
+ "몸",
+ "섬",
+ "옮",
+ "칼",
+ "뻔",
+ "낫",
+ "댄",
+ "눈",
+ "렛",
+ "띠",
+ "땐",
+ "칫",
+ "칩",
+ "쓸",
+ "찍",
+ "겉",
+ "짚",
+ "횡",
+ "멈",
+ "펙",
+ "삽",
+ "셰",
+ "굽",
+ "밤",
+ "논",
+ "쏘",
+ "붓",
+ "꼴",
+ "엠",
+ "흙",
+ "쏠",
+ "껍",
+ "눔",
+ "뭉",
+ "컷",
+ "긍",
+ "닷",
+ "픔",
+ "녔",
+ "앞",
+ "뭇",
+ "넣",
+ "팡",
+ "앗",
+ "샘",
+ "녕",
+ "낙",
+ "헤",
+ "흐",
+ "싹",
+ "찾",
+ "궤",
+ "융",
+ "잖",
+ "팝",
+ "뚱",
+ "찮",
+ "혐",
+ "놨",
+ "앓",
+ "퓨",
+ "얇",
+ "솟",
+ "핫",
+ "맵",
+ "딪",
+ "엿",
+ "줌",
+ "잭",
+ "썩",
+ "븐",
+ "핏",
+ "맙",
+ "췄",
+ "깥",
+ "둠",
+ "넬",
+ "닛",
+ "좋",
+ "뉘",
+ "륨",
+ "숍",
+ "쩌",
+ "샷",
+ "넌",
+ "덧",
+ "툴",
+ "밴",
+ "뚜",
+ "젊",
+ "즌",
+ "쭉",
+ "뇨",
+ "딱",
+ "앵",
+ "윌",
+ "펌",
+ "킷",
+ "뒀",
+ "탠",
+ "흠",
+ "잠",
+ "깨",
+ "슐",
+ "낯",
+ "륜",
+ "잦",
+ "뀐",
+ "탭",
+ "썰",
+ "휩",
+ "샤",
+ "웰",
+ "뜻",
+ "앨",
+ "뜩",
+ "휠",
+ "팬",
+ "툰",
+ "쿼",
+ "펠",
+ "큰",
+ "흰",
+ "볶",
+ "떠",
+ "랫",
+ "갇",
+ "퀘",
+ "갓",
+ "콕",
+ "쉐",
+ "얽",
+ "굿",
+ "괴",
+ "웬",
+ "횟",
+ "깁",
+ "텀",
+ "늦",
+ "못",
+ "뜬",
+ "뤄",
+ "푼",
+ "꺾",
+ "봄",
+ "왠",
+ "힘",
+ "짙",
+ "빨",
+ "옷",
+ "늬",
+ "쉴",
+ "윙",
+ "냄",
+ "뻗",
+ "쪼",
+ "뜸",
+ "딴",
+ "핍",
+ "꿈",
+ "헛",
+ "깎",
+ "옵",
+ "싶",
+ "늑",
+ "팟",
+ "탐",
+ "슴",
+ "푹",
+ "팎",
+ "끝",
+ "갚",
+ "씬",
+ "템",
+ "꽂",
+ "꼬",
+ "뱀",
+ "헐",
+ "듈",
+ "쑥",
+ "셜",
+ "켈",
+ "솜",
+ "큼",
+ "넓",
+ "뮬",
+ "또",
+ "댁",
+ "낡",
+ "꽉",
+ "힙",
+ "붐",
+ "럿",
+ "톨",
+ "펄",
+ "뤘",
+ "꼽",
+ "높",
+ "퉁",
+ "햄",
+ "툼",
+ "덥",
+ "샀",
+ "삐",
+ "궐",
+ "뜰",
+ "잘",
+ "깜",
+ "둬",
+ "뒤",
+ "뱃",
+ "훌",
+ "흔",
+ "콧",
+ "늙",
+ "젓",
+ "찔",
+ "얹",
+ "돔",
+ "홈",
+ "렘",
+ "쏙",
+ "뜯",
+ "뷔",
+ "풋",
+ "헨",
+ "캄",
+ "쏟",
+ "씹",
+ "둡",
+ "썬",
+ "엎",
+ "봇",
+ "꿨",
+ "벳",
+ "킴",
+ "엣",
+ "쉼",
+ "잣",
+ "볕",
+ "앱",
+ "듭",
+ "훔",
+ "챙",
+ "뀔",
+ "갯",
+ "덱",
+ "톰",
+ "퀄",
+ "엮",
+ "낚",
+ "볍",
+ "팍",
+ "뭔",
+ "뽐",
+ "끽",
+ "짱",
+ "찢",
+ "껴",
+ "펫",
+ "랴",
+ "똥",
+ "쓴",
+ "껑",
+ "굶",
+ "뿜",
+ "멀",
+ "벚",
+ "샴",
+ "괜",
+ "밋",
+ "젝",
+ "슘",
+ "꽁",
+ "훼",
+ "덜",
+ "쑤",
+ "촘",
+ "똑",
+ "늠",
+ "왼",
+ "첼",
+ "놔",
+ "딛",
+ "홉",
+ "뱉",
+ "켄",
+ "잇",
+ "낱",
+ "췌",
+ "샐",
+ "빡",
+ "옴",
+ "눅",
+ "꾀",
+ "펑",
+ "닙",
+ "씁",
+ "킥",
+ "싣",
+ "떻",
+ "짖",
+ "찜",
+ "낮",
+ "같",
+ "얘",
+ "쥬",
+ "곧",
+ "깊",
+ "훗",
+ "앰",
+ "몹",
+ "씌",
+ "퀸",
+ "댐",
+ "꼼",
+ "탔",
+ "뎌",
+ "눴",
+ "뿔",
+ "팜",
+ "깐",
+ "걀",
+ "즙",
+ "뽀",
+ "낌",
+ "겟",
+ "띈",
+ "빔",
+ "렐",
+ "붉",
+ "꿰",
+ "맷",
+ "넨",
+ "겔",
+ "짠",
+ "벡",
+ "텅",
+ "늄",
+ "룻",
+ "얄",
+ "촬",
+ "춥",
+ "딥",
+ "멧",
+ "캘",
+ "딸",
+ "헝",
+ "탬",
+ "짤",
+ "툭",
+ "덟",
+ "딧",
+ "젯",
+ "엌",
+ "뭄",
+ "깅",
+ "긁",
+ "썹",
+ "숲",
+ "궈",
+ "큽",
+ "꼭",
+ "뵙",
+ "흑",
+ "칵",
+ "띤",
+ "랬",
+ "썸",
+ "굉",
+ "줍",
+ "귤",
+ "몄",
+ "넛",
+ "왜",
+ "듣",
+ "꿔",
+ "큘",
+ "쫄",
+ "낀",
+ "냉",
+ "꿇",
+ "땠",
+ "똘",
+ "갤",
+ "딕",
+ "텃",
+ "컫",
+ "닫",
+ "벙",
+ "숱",
+ "겸",
+ "떴",
+ "돗",
+ "팥",
+ "팸",
+ "랗",
+ "팠",
+ "녹",
+ "웁",
+ "눕",
+ "쩡",
+ "왈",
+ "뺏",
+ "덮",
+ "깡",
+ "삿",
+ "읽",
+ "낍",
+ "솥",
+ "츰",
+ "뺀",
+ "챌",
+ "굼",
+ "댓",
+ "댈",
+ "쥔",
+ "헬",
+ "헷",
+ "뉜",
+ "콥",
+ "폈",
+ "뽕",
+ "땡",
+ "뿍",
+ "쭈",
+ "끌",
+ "떳",
+ "찼",
+ "씀",
+ "뾰",
+ "뻑",
+ "슛",
+ "헹",
+ "늪",
+ "쎄",
+ "왓",
+ "짬",
+ "빽",
+ "옙",
+ "밑",
+ "얕",
+ "릅",
+ "맴",
+ "튬",
+ "댔",
+ "쉰",
+ "챔",
+ "텝",
+ "묻",
+ "왁",
+ "꾹",
+ "쿵",
+ "좇",
+ "킵",
+ "찻",
+ "됩",
+ "섀",
+ "윽",
+ "륵",
+ "귄",
+ "섣",
+ "맡",
+ "꿋",
+ "깍",
+ "팰",
+ "좀",
+ "벗",
+ "즉",
+ "짊",
+ "뻤",
+ "켠",
+ "뛰",
+ "걱",
+ "숫",
+ "많",
+ "낄",
+ "므",
+ "렷",
+ "넉",
+ "웹",
+ "멤",
+ "쨌",
+ "룹",
+ "녁",
+ "빼",
+ "꼈",
+ "및",
+ "멋",
+ "슷",
+ "끗",
+ "좁",
+ "옆",
+ "멕",
+ "쩔",
+ "훨",
+ "쿄",
+ "떤",
+ "촛",
+ "뭐",
+ "맺",
+ "뀌",
+ "륭",
+ "믿",
+ "쌓",
+ "뽑",
+ "갖",
+ "쁨",
+ "띄",
+ "탓",
+ "걷",
+ "삶",
+ "첫",
+ "빚",
+ "몇",
+ "뒷",
+ "굳",
+ "밝",
+ "잊",
+ "끊",
+ "릎",
+ "낳",
+ "눠",
+ "겪",
+ "밌",
+ "굵",
+ "흩",
+ "꽤",
+ "(",
+ ")",
+ ",",
+ "-",
+ ":",
+ ";",
+ "?",
+ "<|zh|>",
+ "<|en|>",
+ "<|zh/en|>",
+ "<|en/zh|>",
+ "<|yue|>",
+ "<|minnan|>",
+ "<|wuyu|>",
+ "<|dialect|>",
+ "<|ja|>",
+ "<|de|>",
+ "<|es|>",
+ "<|ru|>",
+ "<|ko|>",
+ "<|fr|>",
+ "<|pt|>",
+ "<|tr|>",
+ "<|pl|>",
+ "<|ca|>",
+ "<|nl|>",
+ "<|ar|>",
+ "<|sv|>",
+ "<|it|>",
+ "<|id|>",
+ "<|hi|>",
+ "<|fi|>",
+ "<|vi|>",
+ "<|he|>",
+ "<|uk|>",
+ "<|el|>",
+ "<|ms|>",
+ "<|cs|>",
+ "<|ro|>",
+ "<|da|>",
+ "<|hu|>",
+ "<|ta|>",
+ "<|no|>",
+ "<|th|>",
+ "<|ur|>",
+ "<|hr|>",
+ "<|bg|>",
+ "<|lt|>",
+ "<|la|>",
+ "<|mi|>",
+ "<|ml|>",
+ "<|cy|>",
+ "<|sk|>",
+ "<|te|>",
+ "<|fa|>",
+ "<|lv|>",
+ "<|bn|>",
+ "<|sr|>",
+ "<|az|>",
+ "<|sl|>",
+ "<|kn|>",
+ "<|et|>",
+ "<|mk|>",
+ "<|br|>",
+ "<|eu|>",
+ "<|is|>",
+ "<|hy|>",
+ "<|ne|>",
+ "<|mn|>",
+ "<|bs|>",
+ "<|kk|>",
+ "<|sq|>",
+ "<|sw|>",
+ "<|gl|>",
+ "<|mr|>",
+ "<|pa|>",
+ "<|si|>",
+ "<|km|>",
+ "<|sn|>",
+ "<|yo|>",
+ "<|so|>",
+ "<|af|>",
+ "<|oc|>",
+ "<|ka|>",
+ "<|be|>",
+ "<|tg|>",
+ "<|sd|>",
+ "<|gu|>",
+ "<|am|>",
+ "<|yi|>",
+ "<|lo|>",
+ "<|uz|>",
+ "<|fo|>",
+ "<|ht|>",
+ "<|ps|>",
+ "<|tk|>",
+ "<|nn|>",
+ "<|mt|>",
+ "<|sa|>",
+ "<|lb|>",
+ "<|my|>",
+ "<|bo|>",
+ "<|tl|>",
+ "<|mg|>",
+ "<|as|>",
+ "<|tt|>",
+ "<|haw|>",
+ "<|ln|>",
+ "<|ha|>",
+ "<|ba|>",
+ "<|jw|>",
+ "<|su|>",
+ "<|ASR|>",
+ "<|AED|>",
+ "<|SER|>",
+ "<|nospeech|>",
+ "<|Speech|>",
+ "<|/Speech|>",
+ "<|BGM|>",
+ "<|/BGM|>",
+ "<|Laughter|>",
+ "<|/Laughter|>",
+ "<|Applause|>",
+ "<|/Applause|>",
+ "<|HAPPY|>",
+ "<|SAD|>",
+ "<|ANGRY|>",
+ "<|NEUTRAL|>",
+ "<|FEARFUL|>",
+ "<|DISGUSTED|>",
+ "<|SURPRISED|>",
+ "<|OTHER|>",
+ "<|EMO_UNKNOWN|>",
+ "<|Cry|>",
+ "<|Sneeze|>",
+ "<|Breath|>",
+ "<|Cough|>",
+ "<|Sing|>",
+ "<|Speech_Noise|>",
+ "<|withitn|>",
+ "<|woitn|>",
+ "<|GBG|>",
+ "<|Event_UNK|>",
+ "<|SPECIAL_TOKEN_1|>",
+ "<|SPECIAL_TOKEN_2|>",
+ "<|SPECIAL_TOKEN_3|>",
+ "<|SPECIAL_TOKEN_4|>",
+ "<|SPECIAL_TOKEN_5|>",
+ "<|SPECIAL_TOKEN_6|>",
+ "<|SPECIAL_TOKEN_7|>",
+ "<|SPECIAL_TOKEN_8|>",
+ "<|SPECIAL_TOKEN_9|>",
+ "<|SPECIAL_TOKEN_10|>",
+ "<|SPECIAL_TOKEN_11|>",
+ "<|SPECIAL_TOKEN_12|>",
+ "<|SPECIAL_TOKEN_13|>",
+ "<|SPECIAL_TOKEN_14|>",
+ "<|SPECIAL_TOKEN_15|>",
+ "<|SPECIAL_TOKEN_16|>",
+ "<|SPECIAL_TOKEN_17|>",
+ "<|SPECIAL_TOKEN_18|>",
+ "<|SPECIAL_TOKEN_19|>",
+ "<|SPECIAL_TOKEN_20|>",
+ "<|SPECIAL_TOKEN_21|>",
+ "<|SPECIAL_TOKEN_22|>",
+ "<|SPECIAL_TOKEN_23|>",
+ "<|SPECIAL_TOKEN_24|>",
+ "<|SPECIAL_TOKEN_25|>",
+ "<|SPECIAL_TOKEN_26|>",
+ "<|SPECIAL_TOKEN_27|>",
+ "<|SPECIAL_TOKEN_28|>",
+ "<|SPECIAL_TOKEN_29|>",
+ "<|SPECIAL_TOKEN_30|>",
+ "<|SPECIAL_TOKEN_31|>",
+ "<|SPECIAL_TOKEN_32|>",
+ "<|SPECIAL_TOKEN_33|>",
+ "<|SPECIAL_TOKEN_34|>",
+ "<|SPECIAL_TOKEN_35|>"
+]
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/bug_report.md b/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/bug_report.md
new file mode 100644
index 000000000..af3202dcc
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/bug_report.md
@@ -0,0 +1,52 @@
+---
+name: Bug report
+about: Create a report to help us improve
+title: Bug report - [X]
+labels: bug
+assignees: snakers4
+
+---
+
+## 🐛 Bug
+
+
+
+## To Reproduce
+
+Steps to reproduce the behavior:
+
+1.
+2.
+3.
+
+
+
+## Expected behavior
+
+
+
+## Environment
+
+Please copy and paste the output from this
+[environment collection script](https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py)
+(or fill out the checklist below manually).
+
+You can get the script and run it with:
+```
+wget https://raw.githubusercontent.com/pytorch/pytorch/master/torch/utils/collect_env.py
+# For security purposes, please check the contents of collect_env.py before running it.
+python collect_env.py
+```
+
+ - PyTorch Version (e.g., 1.0):
+ - OS (e.g., Linux):
+ - How you installed PyTorch (`conda`, `pip`, source):
+ - Build command you used (if compiling from source):
+ - Python version:
+ - CUDA/cuDNN version:
+ - GPU models and configuration:
+ - Any other relevant information:
+
+## Additional context
+
+
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/feature_request.md b/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/feature_request.md
new file mode 100644
index 000000000..bfe42a28e
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/feature_request.md
@@ -0,0 +1,27 @@
+---
+name: Feature request
+about: Suggest an idea for this project
+title: Feature request - [X]
+labels: enhancement
+assignees: snakers4
+
+---
+
+## 🚀 Feature
+
+
+## Motivation
+
+
+
+## Pitch
+
+
+
+## Alternatives
+
+
+
+## Additional context
+
+
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/questions---help---support.md b/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/questions---help---support.md
new file mode 100644
index 000000000..1eed38e75
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/.github/ISSUE_TEMPLATE/questions---help---support.md
@@ -0,0 +1,12 @@
+---
+name: Questions / Help / Support
+about: Ask for help, support or ask a question
+title: "❓ Questions / Help / Support"
+labels: help wanted
+assignees: snakers4
+
+---
+
+## ❓ Questions and Help
+
+We have a [wiki](https://github.com/snakers4/silero-models/wiki) available for our users. Please make sure you have checked it out first.
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/.github/workflows/python-publish.yml b/main/xiaozhi-server/models/snakers4_silero-vad/.github/workflows/python-publish.yml
new file mode 100644
index 000000000..7860857b2
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/.github/workflows/python-publish.yml
@@ -0,0 +1,40 @@
+# This workflow will upload a Python Package using Twine when a release is created
+# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
+
+# This workflow uses actions that are not certified by GitHub.
+# They are provided by a third-party and are governed by
+# separate terms of service, privacy policy, and support
+# documentation.
+
+name: Upload Python Package
+
+on:
+ push:
+ tags:
+ - '*'
+
+permissions:
+ contents: read
+
+jobs:
+ deploy:
+
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+ - name: Set up Python
+ uses: actions/setup-python@v3
+ with:
+ python-version: '3.x'
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install build
+ - name: Build package
+ run: python -m build
+ - name: Publish package
+ uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
+ with:
+ user: __token__
+ password: ${{ secrets.PYPI_API_TOKEN }}
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/.github/workflows/test.yml b/main/xiaozhi-server/models/snakers4_silero-vad/.github/workflows/test.yml
new file mode 100644
index 000000000..eeeed2253
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/.github/workflows/test.yml
@@ -0,0 +1,40 @@
+name: Test Package
+
+on:
+ workflow_dispatch: # запуск вручную
+
+jobs:
+ test:
+ runs-on: ${{ matrix.os }}
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, windows-latest, macos-latest]
+ python-version: ["3.8","3.9","3.10","3.11","3.12","3.13"]
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Python
+ uses: actions/setup-python@v4
+ with:
+ python-version: ${{ matrix.python-version }}
+
+ - name: Install dependencies
+ run: |
+ python -m pip install --upgrade pip
+ pip install build hatchling pytest soundfile
+ pip install .[test]
+
+ - name: Build package
+ run: python -m build --wheel --outdir dist
+
+ - name: Install package
+ run: |
+ import glob, subprocess, sys
+ whl = glob.glob("dist/*.whl")[0]
+ subprocess.check_call([sys.executable, "-m", "pip", "install", whl])
+ shell: python
+
+ - name: Run tests
+ run: pytest tests
\ No newline at end of file
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/CITATION.cff b/main/xiaozhi-server/models/snakers4_silero-vad/CITATION.cff
new file mode 100644
index 000000000..e794c3eee
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/CITATION.cff
@@ -0,0 +1,20 @@
+cff-version: 1.2.0
+message: "If you use this software, please cite it as below."
+title: "Silero VAD"
+authors:
+ - family-names: "Silero Team"
+ email: "hello@silero.ai"
+type: software
+repository-code: "https://github.com/snakers4/silero-vad"
+license: MIT
+abstract: "Pre-trained enterprise-grade Voice Activity Detector (VAD), Number Detector and Language Classifier"
+preferred-citation:
+ type: software
+ authors:
+ - family-names: "Silero Team"
+ email: "hello@silero.ai"
+ title: "Silero VAD: pre-trained enterprise-grade Voice Activity Detector (VAD), Number Detector and Language Classifier"
+ year: 2024
+ publisher: "GitHub"
+ journal: "GitHub repository"
+ howpublished: "https://github.com/snakers4/silero-vad"
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/CODE_OF_CONDUCT.md b/main/xiaozhi-server/models/snakers4_silero-vad/CODE_OF_CONDUCT.md
new file mode 100644
index 000000000..c69125eba
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/CODE_OF_CONDUCT.md
@@ -0,0 +1,76 @@
+# Contributor Covenant Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to making participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity and expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+ advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+ address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies both within project spaces and in public spaces
+when an individual is representing the project or its community. Examples of
+representing a project or community include using an official project e-mail
+address, posting via an official social media account, or acting as an appointed
+representative at an online or offline event. Representation of a project may be
+further defined and clarified by project maintainers.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at aveysov@gmail.com. All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see
+https://www.contributor-covenant.org/faq
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/LICENSE b/main/xiaozhi-server/models/snakers4_silero-vad/LICENSE
new file mode 100644
index 000000000..0bf5e90ca
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020-present Silero Team
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/README.md b/main/xiaozhi-server/models/snakers4_silero-vad/README.md
new file mode 100644
index 000000000..57f72f99e
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/README.md
@@ -0,0 +1,178 @@
+[](mailto:hello@silero.ai) [](https://t.me/silero_speech) [](https://github.com/snakers4/silero-vad/blob/master/LICENSE) [](https://pypi.org/project/silero-vad/)
+
+[](https://colab.research.google.com/github/snakers4/silero-vad/blob/master/silero-vad.ipynb) [](https://github.com/snakers4/silero-vad/actions/workflows/test.yml) [](https://pypi.org/project/silero-vad/) [](https://pypi.org/project/silero-vad)
+
+
+
+
+Silero VAD
+
+
+**Silero VAD** - pre-trained enterprise-grade [Voice Activity Detector](https://en.wikipedia.org/wiki/Voice_activity_detection) (also see our [STT models](https://github.com/snakers4/silero-models)).
+
+
+
+
+
+
+
+
+
+Real Time Example
+
+https://user-images.githubusercontent.com/36505480/144874384-95f80f6d-a4f1-42cc-9be7-004c891dd481.mp4
+
+Please note, that video loads only if you are logged in your GitHub account.
+
+
+
+
+
+Fast start
+
+
+
+Dependencies
+
+ System requirements to run python examples on `x86-64` systems:
+
+ - `python 3.8+`;
+ - 1G+ RAM;
+ - A modern CPU with AVX, AVX2, AVX-512 or AMX instruction sets.
+
+ Dependencies:
+
+ - `torch>=1.12.0`;
+ - `torchaudio>=0.12.0` (for I/O only);
+ - `onnxruntime>=1.16.1` (for ONNX model usage).
+
+ Silero VAD uses torchaudio library for audio I/O (`torchaudio.info`, `torchaudio.load`, and `torchaudio.save`), so a proper audio backend is required:
+
+ - Option №1 - [**FFmpeg**](https://www.ffmpeg.org/) backend. `conda install -c conda-forge 'ffmpeg<7'`;
+ - Option №2 - [**sox_io**](https://pypi.org/project/sox/) backend. `apt-get install sox`, TorchAudio is tested on libsox 14.4.2;
+ - Option №3 - [**soundfile**](https://pypi.org/project/soundfile/) backend. `pip install soundfile`.
+
+If you are planning to run the VAD using solely the `onnx-runtime`, it will run on any other system architectures where onnx-runtume is [supported](https://onnxruntime.ai/getting-started). In this case please note that:
+
+- You will have to implement the I/O;
+- You will have to adapt the existing wrappers / examples / post-processing for your use-case.
+
+
+
+**Using pip**:
+`pip install silero-vad`
+
+```python3
+from silero_vad import load_silero_vad, read_audio, get_speech_timestamps
+model = load_silero_vad()
+wav = read_audio('path_to_audio_file')
+speech_timestamps = get_speech_timestamps(
+ wav,
+ model,
+ return_seconds=True, # Return speech timestamps in seconds (default is samples)
+)
+```
+
+**Using torch.hub**:
+```python3
+import torch
+torch.set_num_threads(1)
+
+model, utils = torch.hub.load(repo_or_dir='snakers4/silero-vad', model='silero_vad')
+(get_speech_timestamps, _, read_audio, _, _) = utils
+
+wav = read_audio('path_to_audio_file')
+speech_timestamps = get_speech_timestamps(
+ wav,
+ model,
+ return_seconds=True, # Return speech timestamps in seconds (default is samples)
+)
+```
+
+
+
+Key Features
+
+
+- **Stellar accuracy**
+
+ Silero VAD has [excellent results](https://github.com/snakers4/silero-vad/wiki/Quality-Metrics#vs-other-available-solutions) on speech detection tasks.
+
+- **Fast**
+
+ One audio chunk (30+ ms) [takes](https://github.com/snakers4/silero-vad/wiki/Performance-Metrics#silero-vad-performance-metrics) less than **1ms** to be processed on a single CPU thread. Using batching or GPU can also improve performance considerably. Under certain conditions ONNX may even run up to 4-5x faster.
+
+- **Lightweight**
+
+ JIT model is around two megabytes in size.
+
+- **General**
+
+ Silero VAD was trained on huge corpora that include over **6000** languages and it performs well on audios from different domains with various background noise and quality levels.
+
+- **Flexible sampling rate**
+
+ Silero VAD [supports](https://github.com/snakers4/silero-vad/wiki/Quality-Metrics#sample-rate-comparison) **8000 Hz** and **16000 Hz** [sampling rates](https://en.wikipedia.org/wiki/Sampling_(signal_processing)#Sampling_rate).
+
+- **Highly Portable**
+
+ Silero VAD reaps benefits from the rich ecosystems built around **PyTorch** and **ONNX** running everywhere where these runtimes are available.
+
+- **No Strings Attached**
+
+ Published under permissive license (MIT) Silero VAD has zero strings attached - no telemetry, no keys, no registration, no built-in expiration, no keys or vendor lock.
+
+
+
+Typical Use Cases
+
+
+- Voice activity detection for IOT / edge / mobile use cases
+- Data cleaning and preparation, voice detection in general
+- Telephony and call-center automation, voice bots
+- Voice interfaces
+
+
+Links
+
+
+
+- [Examples and Dependencies](https://github.com/snakers4/silero-vad/wiki/Examples-and-Dependencies#dependencies)
+- [Quality Metrics](https://github.com/snakers4/silero-vad/wiki/Quality-Metrics)
+- [Performance Metrics](https://github.com/snakers4/silero-vad/wiki/Performance-Metrics)
+- [Versions and Available Models](https://github.com/snakers4/silero-vad/wiki/Version-history-and-Available-Models)
+- [Further reading](https://github.com/snakers4/silero-models#further-reading)
+- [FAQ](https://github.com/snakers4/silero-vad/wiki/FAQ)
+
+
+Get In Touch
+
+
+Try our models, create an [issue](https://github.com/snakers4/silero-vad/issues/new), start a [discussion](https://github.com/snakers4/silero-vad/discussions/new), join our telegram [chat](https://t.me/silero_speech), [email](mailto:hello@silero.ai) us, read our [news](https://t.me/silero_news).
+
+Please see our [wiki](https://github.com/snakers4/silero-models/wiki) for relevant information and [email](mailto:hello@silero.ai) us directly.
+
+**Citations**
+
+```
+@misc{Silero VAD,
+ author = {Silero Team},
+ title = {Silero VAD: pre-trained enterprise-grade Voice Activity Detector (VAD), Number Detector and Language Classifier},
+ year = {2024},
+ publisher = {GitHub},
+ journal = {GitHub repository},
+ howpublished = {\url{https://github.com/snakers4/silero-vad}},
+ commit = {insert_some_commit_here},
+ email = {hello@silero.ai}
+}
+```
+
+
+Examples and VAD-based Community Apps
+
+
+- Example of VAD ONNX Runtime model usage in [C++](https://github.com/snakers4/silero-vad/tree/master/examples/cpp)
+
+- Voice activity detection for the [browser](https://github.com/ricky0123/vad) using ONNX Runtime Web
+
+- [Rust](https://github.com/snakers4/silero-vad/tree/master/examples/rust-example), [Go](https://github.com/snakers4/silero-vad/tree/master/examples/go), [Java](https://github.com/snakers4/silero-vad/tree/master/examples/java-example), [C++](https://github.com/snakers4/silero-vad/tree/master/examples/cpp), [C#](https://github.com/snakers4/silero-vad/tree/master/examples/csharp) and [other](https://github.com/snakers4/silero-vad/tree/master/examples) community examples
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/datasets/README.md b/main/xiaozhi-server/models/snakers4_silero-vad/datasets/README.md
new file mode 100644
index 000000000..fd03e6b8a
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/datasets/README.md
@@ -0,0 +1,84 @@
+# Датасет Silero-VAD
+
+> Датасет создан при поддержке Фонда содействия инновациям в рамках федерального проекта «Искусственный
+интеллект» национальной программы «Цифровая экономика Российской Федерации».
+
+По ссылкам ниже представлены `.feather` файлы, содержащие размеченные с помощью Silero VAD открытые наборы аудиоданных, а также короткое описание каждого набора данных с примерами загрузки. `.feather` файлы можно открыть с помощью библиотеки `pandas`:
+```python3
+import pandas as pd
+dataframe = pd.read_feather(PATH_TO_FEATHER_FILE)
+```
+
+Каждый `.feather` файл с разметкой содержит следующие колонки:
+- `speech_timings` - разметка данного аудио. Это список, содержащий словари вида `{'start': START_SECOND, 'end': END_SECOND}`, где `START_SECOND` и `END_SECOND` - время начала и конца речи в секундах. Количество данных словарей равно количеству речевых аудио отрывков, найденных в данном аудио;
+- `language` - ISO код языка данного аудио.
+
+Колонки, содержащие информацию о загрузке аудио файла различаются и описаны для каждого набора данных ниже.
+
+**Все данные размечены при временной дискретизации в ~30 миллисекунд (`num_samples` - 512)**
+
+| Название | Число часов | Число языков | Ссылка | Лицензия | md5sum |
+|----------------------|-------------|-------------|--------|----------|----------|
+| **Bible.is** | 53,138 | 1,596 | [URL](https://live.bible.is/) | [Уникальная](https://live.bible.is/terms) | ea404eeaf2cd283b8223f63002be11f9 |
+| **globalrecordings.net** | 9,743 | 6,171[^1] | [URL](https://globalrecordings.net/en) | CC BY-NC-SA 4.0 | 3c5c0f31b0abd9fe94ddbe8b1e2eb326 |
+| **VoxLingua107** | 6,628 | 107 | [URL](https://bark.phon.ioc.ee/voxlingua107/) | CC BY 4.0 | 5dfef33b4d091b6d399cfaf3d05f2140 |
+| **Common Voice** | 30,329 | 120 | [URL](https://commonvoice.mozilla.org/en/datasets) | CC0 | 5e30a85126adf74a5fd1496e6ac8695d |
+| **MLS** | 50,709 | 8 | [URL](https://www.openslr.org/94/) | CC BY 4.0 | a339d0e94bdf41bba3c003756254ac4e |
+| **Итого** | **150,547** | **6,171+** | | | |
+
+## Bible.is
+
+[Ссылка на `.feather` файл с разметкой](https://models.silero.ai/vad_datasets/BibleIs.feather)
+
+- Колонка `audio_link` содержит ссылки на конкретные аудио файлы.
+
+## globalrecordings.net
+
+[Ссылка на `.feather` файл с разметкой](https://models.silero.ai/vad_datasets/globalrecordings.feather)
+
+- Колонка `folder_link` содержит ссылки на скачивание `.zip` архива для конкретного языка. Внимание! Ссылки на архивы дублируются, т.к каждый архив может содержать множество аудио.
+- Колонка `audio_path` содержит пути до конкретного аудио после распаковки соответствующего архива из колонки `folder_link`
+
+``Количество уникальных ISO кодов данного датасета не совпадает с фактическим количеством представленных языков, т.к некоторые близкие языки могут кодироваться одним и тем же ISO кодом.``
+
+## VoxLingua107
+
+[Ссылка на `.feather` файл с разметкой](https://models.silero.ai/vad_datasets/VoxLingua107.feather)
+
+- Колонка `folder_link` содержит ссылки на скачивание `.zip` архива для конкретного языка. Внимание! Ссылки на архивы дублируются, т.к каждый архив может содержать множество аудио.
+- Колонка `audio_path` содержит пути до конкретного аудио после распаковки соответствующего архива из колонки `folder_link`
+
+## Common Voice
+
+[Ссылка на `.feather` файл с разметкой](https://models.silero.ai/vad_datasets/common_voice.feather)
+
+Этот датасет невозможно скачать по статичным ссылкам. Для загрузки необходимо перейти по [ссылке](https://commonvoice.mozilla.org/en/datasets) и, получив доступ в соответствующей форме, скачать архивы для каждого доступного языка. Внимание! Представленная разметка актуальна для версии исходного датасета `Common Voice Corpus 16.1`.
+
+- Колонка `audio_path` содержит уникальные названия `.mp3` файлов, полученных после скачивания соответствующего датасета.
+
+## MLS
+
+[Ссылка на `.feather` файл с разметкой](https://models.silero.ai/vad_datasets/MLS.feather)
+
+- Колонка `folder_link` содержит ссылки на скачивание `.zip` архива для конкретного языка. Внимание! Ссылки на архивы дублируются, т.к каждый архив может содержать множество аудио.
+- Колонка `audio_path` содержит пути до конкретного аудио после распаковки соответствующего архива из колонки `folder_link`
+
+## Лицензия
+
+Данный датасет распространяется под [лицензией](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) `CC BY-NC-SA 4.0`.
+
+## Цитирование
+
+```
+@misc{Silero VAD Dataset,
+ author = {Silero Team},
+ title = {Silero-VAD Dataset: a large public Internet-scale dataset for voice activity detection for 6000+ languages},
+ year = {2024},
+ publisher = {GitHub},
+ journal = {GitHub repository},
+ howpublished = {\url{https://github.com/snakers4/silero-vad/datasets/README.md}},
+ email = {hello@silero.ai}
+}
+```
+
+[^1]: ``Количество уникальных ISO кодов данного датасета не совпадает с фактическим количеством представленных языков, т.к некоторые близкие языки могут кодироваться одним и тем же ISO кодом.``
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/README.md b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/README.md
new file mode 100644
index 000000000..dbd86744a
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/README.md
@@ -0,0 +1,49 @@
+# Silero-VAD V6 in C++ (based on LibTorch)
+
+This is the source code for Silero-VAD V6 in C++, utilizing LibTorch & Onnxruntime.
+You should compare its results with the Python version.
+Results at 16 and 8kHz have been tested. Batch and CUDA inference options are deprecated.
+
+
+## Requirements
+- GCC 11.4.0 (GCC >= 5.1)
+- Onnxruntime 1.11.0 (other versions are also acceptable)
+- LibTorch 1.13.0 (other versions are also acceptable)
+
+## Download LibTorch
+
+```bash
+-Onnxruntime
+$wget https://github.com/microsoft/onnxruntime/releases/download/v1.11.1/onnxruntime-linux-x64-1.11.1.tgz
+$tar -xvf onnxruntime-linux-x64-1.11.1.tgz
+$ln -s onnxruntime-linux-x64-1.11.1 onnxruntime-linux #soft-link
+
+-Libtorch
+$wget https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-1.13.0%2Bcpu.zip
+$unzip libtorch-shared-with-deps-1.13.0+cpu.zip
+```
+
+## Compilation
+
+```bash
+-ONNX-build
+$g++ main.cc silero.cc -I ./onnxruntime-linux/include/ -L ./onnxruntime-linux/lib/ -lonnxruntime -Wl,-rpath,./onnxruntime-linux/lib/ -o silero -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 -DUSE_ONNX
+
+-TORCH-build
+$g++ main.cc silero.cc -I ./libtorch/include/ -I ./libtorch/include/torch/csrc/api/include -L ./libtorch/lib/ -ltorch -ltorch_cpu -lc10 -Wl,-rpath,./libtorch/lib/ -o silero -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 -DUSE_TORCH
+```
+
+## Optional Compilation Flags
+-DUSE_TORCH
+-DUSE_ONNX
+
+## Run the Program
+To run the program, use the following command:
+
+`./silero `
+`./silero aepyx.wav 16000 0.5`
+`./silero aepyx_8k.wav 8000 0.5`
+
+The sample file aepyx.wav is part of the Voxconverse dataset.
+File details: aepyx.wav is a 16kHz, 16-bit audio file.
+File details: aepyx_8k.wav is a 8kHz, 16-bit audio file.
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/main.cc b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/main.cc
new file mode 100644
index 000000000..ec6203f7b
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/main.cc
@@ -0,0 +1,61 @@
+#include
+#include "silero.h"
+#include "wav.h"
+
+int main(int argc, char* argv[]) {
+
+ if(argc != 4){
+ std::cerr<<"Usage : "< "< input_wav(wav_reader.num_samples());
+
+ for (int i = 0; i < wav_reader.num_samples(); i++)
+ {
+ input_wav[i] = static_cast(*(wav_reader.data() + i));
+ }
+
+ vad.SpeechProbs(input_wav);
+
+ std::vector speeches = vad.GetSpeechTimestamps();
+ for(const auto& speech : speeches){
+ if(vad.print_as_samples){
+ std::cout<<"{'start': "<(speech.start)<<", 'end': "<(speech.end)<<"}"<& input_wav) {
+ int num_samples = input_wav.size();
+ int num_chunks = num_samples / window_size_samples;
+ int remainder_samples = num_samples % window_size_samples;
+ total_sample_size += num_samples;
+
+ std::vector chunks;
+
+ for (int i = 0; i < num_chunks; i++) {
+ float* chunk_start = input_wav.data() + i * window_size_samples;
+ torch::Tensor chunk = torch::from_blob(chunk_start, {1, window_size_samples}, torch::kFloat32);
+ chunks.push_back(chunk);
+
+ if (i == num_chunks - 1 && remainder_samples > 0) {
+ int remaining_samples = num_samples - num_chunks * window_size_samples;
+ float* chunk_start_remainder = input_wav.data() + num_chunks * window_size_samples;
+ torch::Tensor remainder_chunk = torch::from_blob(chunk_start_remainder, {1, remaining_samples}, torch::kFloat32);
+ torch::Tensor padded_chunk = torch::cat({remainder_chunk, torch::zeros({1, window_size_samples - remaining_samples}, torch::kFloat32)}, 1);
+ chunks.push_back(padded_chunk);
+ }
+ }
+
+ if (!chunks.empty()) {
+ std::vector outputs;
+ torch::Tensor batched_chunks = torch::stack(chunks);
+ for (size_t i = 0; i < chunks.size(); i++) {
+ torch::NoGradGuard no_grad;
+ std::vector inputs;
+ inputs.push_back(batched_chunks[i]);
+ inputs.push_back(sample_rate);
+ torch::Tensor output = model.forward(inputs).toTensor();
+ outputs.push_back(output);
+ }
+ torch::Tensor all_outputs = torch::stack(outputs);
+ for (size_t i = 0; i < chunks.size(); i++) {
+ float output_f = all_outputs[i].item();
+ outputs_prob.push_back(output_f);
+ //////To print Probs by libtorch
+ //std::cout << "Chunk " << i << " prob: " << output_f<< "\n";
+ }
+ }
+ }
+
+
+#elif USE_ONNX
+
+ VadIterator::VadIterator(const std::string &model_path,
+ float threshold,
+ int sample_rate,
+ int window_size_ms,
+ int speech_pad_ms,
+ int min_silence_duration_ms,
+ int min_speech_duration_ms,
+ int max_duration_merge_ms,
+ bool print_as_samples)
+ :sample_rate(sample_rate), threshold(threshold), window_size_ms(window_size_ms),
+ speech_pad_ms(speech_pad_ms), min_silence_duration_ms(min_silence_duration_ms),
+ min_speech_duration_ms(min_speech_duration_ms), max_duration_merge_ms(max_duration_merge_ms),
+ print_as_samples(print_as_samples),
+ env(ORT_LOGGING_LEVEL_ERROR, "Vad"), session_options(), session(nullptr), allocator(),
+ memory_info(Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeCPU)), context_samples(64),
+ _context(64, 0.0f), current_sample(0), size_state(2 * 1 * 128),
+ input_node_names({"input", "state", "sr"}), output_node_names({"output", "stateN"}),
+ state_node_dims{2, 1, 128}, sr_node_dims{1}
+
+ {
+ init_onnx_model(model_path);
+ }
+ VadIterator::~VadIterator(){
+ }
+
+ void VadIterator::init_onnx_model(const std::string& model_path) {
+ int inter_threads=1;
+ int intra_threads=1;
+ session_options.SetIntraOpNumThreads(intra_threads);
+ session_options.SetInterOpNumThreads(inter_threads);
+ session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
+ session = std::make_shared(env, model_path.c_str(), session_options);
+ std::cout<<"Silero onnx-Model loaded successfully"<& data_chunk) {
+ // _context와 현재 청크를 결합하여 입력 데이터 구성
+ std::vector new_data(effective_window_size, 0.0f);
+ std::copy(_context.begin(), _context.end(), new_data.begin());
+ std::copy(data_chunk.begin(), data_chunk.end(), new_data.begin() + context_samples);
+ input = new_data;
+
+ Ort::Value input_ort = Ort::Value::CreateTensor(
+ memory_info, input.data(), input.size(), input_node_dims, 2);
+ Ort::Value state_ort = Ort::Value::CreateTensor(
+ memory_info, _state.data(), _state.size(), state_node_dims, 3);
+ Ort::Value sr_ort = Ort::Value::CreateTensor(
+ memory_info, sr.data(), sr.size(), sr_node_dims, 1);
+ ort_inputs.clear();
+ ort_inputs.push_back(std::move(input_ort));
+ ort_inputs.push_back(std::move(state_ort));
+ ort_inputs.push_back(std::move(sr_ort));
+
+ ort_outputs = session->Run(
+ Ort::RunOptions{ nullptr },
+ input_node_names.data(), ort_inputs.data(), ort_inputs.size(),
+ output_node_names.data(), output_node_names.size());
+
+ float speech_prob = ort_outputs[0].GetTensorMutableData()[0]; // ONNX 출력: 첫 번째 값이 음성 확률
+
+ float* stateN = ort_outputs[1].GetTensorMutableData(); // 두 번째 출력값: 상태 업데이트
+ std::memcpy(_state.data(), stateN, size_state * sizeof(float));
+
+ std::copy(new_data.end() - context_samples, new_data.end(), _context.begin());
+ // _context 업데이트: new_data의 마지막 context_samples 유지
+
+ return speech_prob;
+ }
+ void VadIterator::SpeechProbs(std::vector& input_wav) {
+ reset_states();
+ total_sample_size = static_cast(input_wav.size());
+ for (size_t j = 0; j < static_cast(total_sample_size); j += window_size_samples) {
+ if (j + window_size_samples > static_cast(total_sample_size))
+ break;
+ std::vector chunk(input_wav.begin() + j, input_wav.begin() + j + window_size_samples);
+ float speech_prob = predict(chunk);
+ outputs_prob.push_back(speech_prob);
+ }
+ }
+
+#endif
+
+ void VadIterator::reset_states() {
+ triggered = false;
+ current_sample = 0;
+ temp_end = 0;
+ outputs_prob.clear();
+ total_sample_size = 0;
+
+#ifdef USE_TORCH
+ model.run_method("reset_states"); // Reset model states if applicable
+#elif USE_ONNX
+ std::memset(_state.data(), 0, _state.size() * sizeof(float));
+ std::fill(_context.begin(), _context.end(), 0.0f);
+#endif
+ }
+
+ std::vector VadIterator::GetSpeechTimestamps() {
+ std::vector speeches = DoVad();
+ if(!print_as_samples){
+ for (auto& speech : speeches) {
+ speech.start /= sample_rate;
+ speech.end /= sample_rate;
+ }
+ }
+ return speeches;
+ }
+
+ void VadIterator::SetVariables(){
+ // Initialize internal engine parameters
+ init_engine(window_size_ms);
+ }
+
+ void VadIterator::init_engine(int window_size_ms) {
+ min_silence_samples = sample_rate * min_silence_duration_ms / 1000;
+ speech_pad_samples = sample_rate * speech_pad_ms / 1000;
+ window_size_samples = sample_rate / 1000 * window_size_ms;
+ min_speech_samples = sample_rate * min_speech_duration_ms / 1000;
+#ifdef USE_ONNX
+ //for ONNX
+ context_samples=window_size_samples / 8;
+ _context.assign(context_samples, 0.0f);
+
+ effective_window_size = window_size_samples + context_samples; // 예: 512 + 64 = 576 samples
+ input_node_dims[0] = 1;
+ input_node_dims[1] = effective_window_size;
+ _state.resize(size_state);
+ sr.resize(1);
+ sr[0] = sample_rate;
+#endif
+ }
+
+ std::vector VadIterator::DoVad() {
+ std::vector speeches;
+ for (size_t i = 0; i < outputs_prob.size(); ++i) {
+ float speech_prob = outputs_prob[i];
+ current_sample += window_size_samples;
+ if (speech_prob >= threshold && temp_end != 0) {
+ temp_end = 0;
+ }
+
+ if (speech_prob >= threshold) {
+ if (!triggered) {
+ triggered = true;
+ Interval segment;
+ segment.start = std::max(0, current_sample - speech_pad_samples - window_size_samples);
+ speeches.push_back(segment);
+ }
+ }else {
+ if (triggered) {
+ if (speech_prob < threshold - 0.15f) {
+ if (temp_end == 0) {
+ temp_end = current_sample;
+ }
+ if (current_sample - temp_end >= min_silence_samples) {
+ Interval& segment = speeches.back();
+ segment.end = temp_end + speech_pad_samples - window_size_samples;
+ temp_end = 0;
+ triggered = false;
+ }
+ }
+ }
+ }
+
+
+ }
+
+ if (triggered) {
+ std::cout<<"Finalizing active speech segment at stream end."<speech_pad_samples) - (speech.start + this->speech_pad_samples) < min_speech_samples);
+ }), speeches.end());
+
+ reset_states();
+ return speeches;
+ }
+
+
+ } // namespace silero
+
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/silero.h b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/silero.h
new file mode 100644
index 000000000..8d4a11e1b
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/silero.h
@@ -0,0 +1,123 @@
+#ifndef SILERO_H
+#define SILERO_H
+
+// silero.h
+// Author : NathanJHLee
+// Created On : 2025-11-10
+// Description : silero 6.2 system for onnx-runtime(c++) and torch-script(c++)
+// Version : 1.3
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#ifdef USE_TORCH
+#include
+#include
+#elif USE_ONNX
+#include "onnxruntime_cxx_api.h"
+#endif
+
+namespace silero {
+
+ struct Interval {
+ float start;
+ float end;
+ int numberOfSubseg;
+
+ void initialize() {
+ start = 0;
+ end = 0;
+ numberOfSubseg = 0;
+ }
+ };
+
+ class VadIterator {
+ public:
+ VadIterator(const std::string &model_path,
+ float threshold = 0.5,
+ int sample_rate = 16000,
+ int window_size_ms = 32,
+ int speech_pad_ms = 30,
+ int min_silence_duration_ms = 100,
+ int min_speech_duration_ms = 250,
+ int max_duration_merge_ms = 300,
+ bool print_as_samples = false);
+ ~VadIterator();
+
+ // Batch (non-streaming) interface (for backward compatibility)
+ void SpeechProbs(std::vector& input_wav);
+ std::vector GetSpeechTimestamps();
+ void SetVariables();
+
+ // Public parameters (can be modified by user)
+ float threshold;
+ int sample_rate;
+ int window_size_ms;
+ int min_speech_duration_ms;
+ int max_duration_merge_ms;
+ bool print_as_samples;
+
+ private:
+#ifdef USE_TORCH
+ torch::jit::script::Module model;
+ void init_torch_model(const std::string& model_path);
+#elif USE_ONNX
+ Ort::Env env; // 환경 객체
+ Ort::SessionOptions session_options; // 세션 옵션
+ std::shared_ptr session; // ONNX 세션
+ Ort::AllocatorWithDefaultOptions allocator; // 기본 할당자
+ Ort::MemoryInfo memory_info; // 메모리 정보 (CPU)
+
+ void init_onnx_model(const std::string& model_path);
+ float predict(const std::vector& data_chunk);
+
+ //const int context_samples; // 예: 64 samples
+ int context_samples; // 예: 64 samples
+ std::vector _context; // 초기값 모두 0
+ int effective_window_size;
+
+ // ONNX 입력/출력 관련 버퍼 및 노드 이름들
+ std::vector ort_inputs;
+ std::vector input_node_names;
+ std::vector input;
+ unsigned int size_state; // 고정값: 2*1*128
+ std::vector _state;
+ std::vector sr;
+ int64_t input_node_dims[2]; // [1, effective_window_size]
+ const int64_t state_node_dims[3]; // [ 2, 1, 128 ]
+ const int64_t sr_node_dims[1]; // [ 1 ]
+ std::vector ort_outputs;
+ std::vector output_node_names; // 기본값: [ "output", "stateN" ]
+#endif
+ std::vector outputs_prob; // used in batch mode
+ int min_silence_samples;
+ int min_speech_samples;
+ int speech_pad_samples;
+ int window_size_samples;
+ int duration_merge_samples;
+ int current_sample = 0;
+ int total_sample_size = 0;
+ int min_silence_duration_ms;
+ int speech_pad_ms;
+ bool triggered = false;
+ int temp_end = 0;
+ int global_end = 0;
+ int erase_tail_count = 0;
+
+
+ void init_engine(int window_size_ms);
+ void reset_states();
+ std::vector DoVad();
+
+
+ };
+
+} // namespace silero
+
+#endif // SILERO_H
+
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/wav.h b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/wav.h
new file mode 100644
index 000000000..d567ee686
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/c++/wav.h
@@ -0,0 +1,237 @@
+// Copyright (c) 2016 Personal (Binbin Zhang)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef FRONTEND_WAV_H_
+#define FRONTEND_WAV_H_
+
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+// #include "utils/log.h"
+
+namespace wav {
+
+struct WavHeader {
+ char riff[4]; // "riff"
+ unsigned int size;
+ char wav[4]; // "WAVE"
+ char fmt[4]; // "fmt "
+ unsigned int fmt_size;
+ uint16_t format;
+ uint16_t channels;
+ unsigned int sample_rate;
+ unsigned int bytes_per_second;
+ uint16_t block_size;
+ uint16_t bit;
+ char data[4]; // "data"
+ unsigned int data_size;
+};
+
+class WavReader {
+ public:
+ WavReader() : data_(nullptr) {}
+ explicit WavReader(const std::string& filename) { Open(filename); }
+
+ bool Open(const std::string& filename) {
+ FILE* fp = fopen(filename.c_str(), "rb"); //文件读取
+ if (NULL == fp) {
+ std::cout << "Error in read " << filename;
+ return false;
+ }
+
+ WavHeader header;
+ fread(&header, 1, sizeof(header), fp);
+ if (header.fmt_size < 16) {
+ printf("WaveData: expect PCM format data "
+ "to have fmt chunk of at least size 16.\n");
+ return false;
+ } else if (header.fmt_size > 16) {
+ int offset = 44 - 8 + header.fmt_size - 16;
+ fseek(fp, offset, SEEK_SET);
+ fread(header.data, 8, sizeof(char), fp);
+ }
+ // check "riff" "WAVE" "fmt " "data"
+
+ // Skip any sub-chunks between "fmt" and "data". Usually there will
+ // be a single "fact" sub chunk, but on Windows there can also be a
+ // "list" sub chunk.
+ while (0 != strncmp(header.data, "data", 4)) {
+ // We will just ignore the data in these chunks.
+ fseek(fp, header.data_size, SEEK_CUR);
+ // read next sub chunk
+ fread(header.data, 8, sizeof(char), fp);
+ }
+
+ if (header.data_size == 0) {
+ int offset = ftell(fp);
+ fseek(fp, 0, SEEK_END);
+ header.data_size = ftell(fp) - offset;
+ fseek(fp, offset, SEEK_SET);
+ }
+
+ num_channel_ = header.channels;
+ sample_rate_ = header.sample_rate;
+ bits_per_sample_ = header.bit;
+ int num_data = header.data_size / (bits_per_sample_ / 8);
+ data_ = new float[num_data]; // Create 1-dim array
+ num_samples_ = num_data / num_channel_;
+
+ std::cout << "num_channel_ :" << num_channel_ << std::endl;
+ std::cout << "sample_rate_ :" << sample_rate_ << std::endl;
+ std::cout << "bits_per_sample_:" << bits_per_sample_ << std::endl;
+ std::cout << "num_samples :" << num_data << std::endl;
+ std::cout << "num_data_size :" << header.data_size << std::endl;
+
+ switch (bits_per_sample_) {
+ case 8: {
+ char sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(char), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ break;
+ }
+ case 16: {
+ int16_t sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(int16_t), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ break;
+ }
+ case 32:
+ {
+ if (header.format == 1) //S32
+ {
+ int sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(int), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ }
+ else if (header.format == 3) // IEEE-float
+ {
+ float sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(float), fp);
+ data_[i] = static_cast(sample);
+ }
+ }
+ else {
+ printf("unsupported quantization bits\n");
+ }
+ break;
+ }
+ default:
+ printf("unsupported quantization bits\n");
+ break;
+ }
+
+ fclose(fp);
+ return true;
+ }
+
+ int num_channel() const { return num_channel_; }
+ int sample_rate() const { return sample_rate_; }
+ int bits_per_sample() const { return bits_per_sample_; }
+ int num_samples() const { return num_samples_; }
+
+ ~WavReader() {
+ delete[] data_;
+ }
+
+ const float* data() const { return data_; }
+
+ private:
+ int num_channel_;
+ int sample_rate_;
+ int bits_per_sample_;
+ int num_samples_; // sample points per channel
+ float* data_;
+};
+
+class WavWriter {
+ public:
+ WavWriter(const float* data, int num_samples, int num_channel,
+ int sample_rate, int bits_per_sample)
+ : data_(data),
+ num_samples_(num_samples),
+ num_channel_(num_channel),
+ sample_rate_(sample_rate),
+ bits_per_sample_(bits_per_sample) {}
+
+ void Write(const std::string& filename) {
+ FILE* fp = fopen(filename.c_str(), "w");
+ // init char 'riff' 'WAVE' 'fmt ' 'data'
+ WavHeader header;
+ char wav_header[44] = {0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57,
+ 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00,
+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00};
+ memcpy(&header, wav_header, sizeof(header));
+ header.channels = num_channel_;
+ header.bit = bits_per_sample_;
+ header.sample_rate = sample_rate_;
+ header.data_size = num_samples_ * num_channel_ * (bits_per_sample_ / 8);
+ header.size = sizeof(header) - 8 + header.data_size;
+ header.bytes_per_second =
+ sample_rate_ * num_channel_ * (bits_per_sample_ / 8);
+ header.block_size = num_channel_ * (bits_per_sample_ / 8);
+
+ fwrite(&header, 1, sizeof(header), fp);
+
+ for (int i = 0; i < num_samples_; ++i) {
+ for (int j = 0; j < num_channel_; ++j) {
+ switch (bits_per_sample_) {
+ case 8: {
+ char sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ case 16: {
+ int16_t sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ case 32: {
+ int sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ }
+ }
+ }
+ fclose(fp);
+ }
+
+ private:
+ const float* data_;
+ int num_samples_; // total float points in data_
+ int num_channel_;
+ int sample_rate_;
+ int bits_per_sample_;
+};
+
+} // namespace wav
+
+#endif // FRONTEND_WAV_H_
+
+
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/colab_record_example.ipynb b/main/xiaozhi-server/models/snakers4_silero-vad/examples/colab_record_example.ipynb
new file mode 100644
index 000000000..4de7e2671
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/colab_record_example.ipynb
@@ -0,0 +1,237 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "bccAucKjnPHm"
+ },
+ "source": [
+ "### Dependencies and inputs"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "cSih95WFmwgi"
+ },
+ "outputs": [],
+ "source": [
+ "#!apt install ffmpeg\n",
+ "!pip -q install pydub\n",
+ "from google.colab import output\n",
+ "from base64 import b64decode, b64encode\n",
+ "from io import BytesIO\n",
+ "import numpy as np\n",
+ "from pydub import AudioSegment\n",
+ "from IPython.display import HTML, display\n",
+ "import torch\n",
+ "import matplotlib.pyplot as plt\n",
+ "import moviepy.editor as mpe\n",
+ "from matplotlib.animation import FuncAnimation, FFMpegWriter\n",
+ "import matplotlib\n",
+ "matplotlib.use('Agg')\n",
+ "\n",
+ "torch.set_num_threads(1)\n",
+ "\n",
+ "model, _ = torch.hub.load(repo_or_dir='snakers4/silero-vad',\n",
+ " model='silero_vad',\n",
+ " force_reload=True)\n",
+ "\n",
+ "def int2float(audio):\n",
+ " samples = audio.get_array_of_samples()\n",
+ " new_sound = audio._spawn(samples)\n",
+ " arr = np.array(samples).astype(np.float32)\n",
+ " arr = arr / np.abs(arr).max()\n",
+ " return arr\n",
+ "\n",
+ "AUDIO_HTML = \"\"\"\n",
+ "\n",
+ "\"\"\"\n",
+ "\n",
+ "def record(sec=10):\n",
+ " display(HTML(AUDIO_HTML))\n",
+ " s = output.eval_js(\"data\")\n",
+ " b = b64decode(s.split(',')[1])\n",
+ " audio = AudioSegment.from_file(BytesIO(b))\n",
+ " audio.export('test.mp3', format='mp3')\n",
+ " audio = audio.set_channels(1)\n",
+ " audio = audio.set_frame_rate(16000)\n",
+ " audio_float = int2float(audio)\n",
+ " audio_tens = torch.tensor(audio_float)\n",
+ " return audio_tens\n",
+ "\n",
+ "def make_animation(probs, audio_duration, interval=40):\n",
+ " fig = plt.figure(figsize=(16, 9))\n",
+ " ax = plt.axes(xlim=(0, audio_duration), ylim=(0, 1.02))\n",
+ " line, = ax.plot([], [], lw=2)\n",
+ " x = [i / 16000 * 512 for i in range(len(probs))]\n",
+ " plt.xlabel('Time, seconds', fontsize=16)\n",
+ " plt.ylabel('Speech Probability', fontsize=16)\n",
+ "\n",
+ " def init():\n",
+ " plt.fill_between(x, probs, color='#064273')\n",
+ " line.set_data([], [])\n",
+ " line.set_color('#990000')\n",
+ " return line,\n",
+ "\n",
+ " def animate(i):\n",
+ " x = i * interval / 1000 - 0.04\n",
+ " y = np.linspace(0, 1.02, 2)\n",
+ "\n",
+ " line.set_data(x, y)\n",
+ " line.set_color('#990000')\n",
+ " return line,\n",
+ " anim = FuncAnimation(fig, animate, init_func=init, interval=interval, save_count=int(audio_duration / (interval / 1000)))\n",
+ "\n",
+ " f = r\"animation.mp4\"\n",
+ " writervideo = FFMpegWriter(fps=1000/interval)\n",
+ " anim.save(f, writer=writervideo)\n",
+ " plt.close('all')\n",
+ "\n",
+ "def combine_audio(vidname, audname, outname, fps=25):\n",
+ " my_clip = mpe.VideoFileClip(vidname, verbose=False)\n",
+ " audio_background = mpe.AudioFileClip(audname)\n",
+ " final_clip = my_clip.set_audio(audio_background)\n",
+ " final_clip.write_videofile(outname,fps=fps,verbose=False)\n",
+ "\n",
+ "def record_make_animation():\n",
+ " tensor = record()\n",
+ " print('Calculating probabilities...')\n",
+ " speech_probs = []\n",
+ " window_size_samples = 512\n",
+ " speech_probs = model.audio_forward(tensor, sr=16000)[0].tolist()\n",
+ " model.reset_states()\n",
+ " print('Making animation...')\n",
+ " make_animation(speech_probs, len(tensor) / 16000)\n",
+ "\n",
+ " print('Merging your voice with animation...')\n",
+ " combine_audio('animation.mp4', 'test.mp3', 'merged.mp4')\n",
+ " print('Done!')\n",
+ " mp4 = open('merged.mp4','rb').read()\n",
+ " data_url = \"data:video/mp4;base64,\" + b64encode(mp4).decode()\n",
+ " display(HTML(\"\"\"\n",
+ " \n",
+ " \n",
+ " \n",
+ " \"\"\" % data_url))\n",
+ "\n",
+ " return speech_probs"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {
+ "id": "IFVs3GvTnpB1"
+ },
+ "source": [
+ "## Record example"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {
+ "id": "5EBjrTwiqAaQ"
+ },
+ "outputs": [],
+ "source": [
+ "speech_probs = record_make_animation()"
+ ]
+ }
+ ],
+ "metadata": {
+ "colab": {
+ "collapsed_sections": [
+ "bccAucKjnPHm"
+ ],
+ "name": "Untitled2.ipynb",
+ "provenance": []
+ },
+ "kernelspec": {
+ "display_name": "Python 3",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 0
+}
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/README.md b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/README.md
new file mode 100644
index 000000000..93a679159
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/README.md
@@ -0,0 +1,43 @@
+# Stream example in C++
+
+Here's a simple example of the vad model in c++ onnxruntime.
+
+
+
+## Requirements
+
+Code are tested in the environments bellow, feel free to try others.
+
+- WSL2 + Debian-bullseye (docker)
+- gcc 12.2.0
+- onnxruntime-linux-x64-1.12.1
+
+
+
+## Usage
+
+1. Install gcc 12.2.0, or just pull the docker image with `docker pull gcc:12.2.0-bullseye`
+
+2. Install onnxruntime-linux-x64-1.12.1
+
+ - Download lib onnxruntime:
+
+ `wget https://github.com/microsoft/onnxruntime/releases/download/v1.12.1/onnxruntime-linux-x64-1.12.1.tgz`
+
+ - Unzip. Assume the path is `/root/onnxruntime-linux-x64-1.12.1`
+
+3. Modify wav path & Test configs in main function
+
+ `wav::WavReader wav_reader("${path_to_your_wav_file}");`
+
+ test sample rate, frame per ms, threshold...
+
+4. Build with gcc and run
+
+ ```bash
+ # Build
+ g++ silero-vad-onnx.cpp -I /root/onnxruntime-linux-x64-1.12.1/include/ -L /root/onnxruntime-linux-x64-1.12.1/lib/ -lonnxruntime -Wl,-rpath,/root/onnxruntime-linux-x64-1.12.1/lib/ -o test
+
+ # Run
+ ./test
+ ```
\ No newline at end of file
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/silero-vad-onnx.cpp b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/silero-vad-onnx.cpp
new file mode 100644
index 000000000..380d76dae
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/silero-vad-onnx.cpp
@@ -0,0 +1,367 @@
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include // for std::rint
+#if __cplusplus < 201703L
+#include
+#endif
+
+//#define __DEBUG_SPEECH_PROB___
+
+#include "onnxruntime_cxx_api.h"
+#include "wav.h" // For reading WAV files
+
+// timestamp_t class: stores the start and end (in samples) of a speech segment.
+class timestamp_t {
+public:
+ int start;
+ int end;
+
+ timestamp_t(int start = -1, int end = -1)
+ : start(start), end(end) { }
+
+ timestamp_t& operator=(const timestamp_t& a) {
+ start = a.start;
+ end = a.end;
+ return *this;
+ }
+
+ bool operator==(const timestamp_t& a) const {
+ return (start == a.start && end == a.end);
+ }
+
+ // Returns a formatted string of the timestamp.
+ std::string c_str() const {
+ return format("{start:%08d, end:%08d}", start, end);
+ }
+private:
+ // Helper function for formatting.
+ std::string format(const char* fmt, ...) const {
+ char buf[256];
+ va_list args;
+ va_start(args, fmt);
+ const auto r = std::vsnprintf(buf, sizeof(buf), fmt, args);
+ va_end(args);
+ if (r < 0)
+ return {};
+ const size_t len = r;
+ if (len < sizeof(buf))
+ return std::string(buf, len);
+#if __cplusplus >= 201703L
+ std::string s(len, '\0');
+ va_start(args, fmt);
+ std::vsnprintf(s.data(), len + 1, fmt, args);
+ va_end(args);
+ return s;
+#else
+ auto vbuf = std::unique_ptr(new char[len + 1]);
+ va_start(args, fmt);
+ std::vsnprintf(vbuf.get(), len + 1, fmt, args);
+ va_end(args);
+ return std::string(vbuf.get(), len);
+#endif
+ }
+};
+
+// VadIterator class: uses ONNX Runtime to detect speech segments.
+class VadIterator {
+private:
+ // ONNX Runtime resources
+ Ort::Env env;
+ Ort::SessionOptions session_options;
+ std::shared_ptr session = nullptr;
+ Ort::AllocatorWithDefaultOptions allocator;
+ Ort::MemoryInfo memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeCPU);
+
+ // ----- Context-related additions -----
+ const int context_samples = 64; // For 16kHz, 64 samples are added as context.
+ std::vector _context; // Holds the last 64 samples from the previous chunk (initialized to zero).
+
+ // Original window size (e.g., 32ms corresponds to 512 samples)
+ int window_size_samples;
+ // Effective window size = window_size_samples + context_samples
+ int effective_window_size;
+
+ // Additional declaration: samples per millisecond
+ int sr_per_ms;
+
+ // ONNX Runtime input/output buffers
+ std::vector ort_inputs;
+ std::vector input_node_names = { "input", "state", "sr" };
+ std::vector input;
+ unsigned int size_state = 2 * 1 * 128;
+ std::vector _state;
+ std::vector sr;
+ int64_t input_node_dims[2] = {};
+ const int64_t state_node_dims[3] = { 2, 1, 128 };
+ const int64_t sr_node_dims[1] = { 1 };
+ std::vector ort_outputs;
+ std::vector output_node_names = { "output", "stateN" };
+
+ // Model configuration parameters
+ int sample_rate;
+ float threshold;
+ int min_silence_samples;
+ int min_silence_samples_at_max_speech;
+ int min_speech_samples;
+ float max_speech_samples;
+ int speech_pad_samples;
+ int audio_length_samples;
+
+ // State management
+ bool triggered = false;
+ unsigned int temp_end = 0;
+ unsigned int current_sample = 0;
+ int prev_end;
+ int next_start = 0;
+ std::vector speeches;
+ timestamp_t current_speech;
+
+ // Loads the ONNX model.
+ void init_onnx_model(const std::wstring& model_path) {
+ init_engine_threads(1, 1);
+ session = std::make_shared(env, model_path.c_str(), session_options);
+ }
+
+ // Initializes threading settings.
+ void init_engine_threads(int inter_threads, int intra_threads) {
+ session_options.SetIntraOpNumThreads(intra_threads);
+ session_options.SetInterOpNumThreads(inter_threads);
+ session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
+ }
+
+ // Resets internal state (_state, _context, etc.)
+ void reset_states() {
+ std::memset(_state.data(), 0, _state.size() * sizeof(float));
+ triggered = false;
+ temp_end = 0;
+ current_sample = 0;
+ prev_end = next_start = 0;
+ speeches.clear();
+ current_speech = timestamp_t();
+ std::fill(_context.begin(), _context.end(), 0.0f);
+ }
+
+ // Inference: runs inference on one chunk of input data.
+ // data_chunk is expected to have window_size_samples samples.
+ void predict(const std::vector& data_chunk) {
+ // Build new input: first context_samples from _context, followed by the current chunk (window_size_samples).
+ std::vector new_data(effective_window_size, 0.0f);
+ std::copy(_context.begin(), _context.end(), new_data.begin());
+ std::copy(data_chunk.begin(), data_chunk.end(), new_data.begin() + context_samples);
+ input = new_data;
+
+ // Create input tensor (input_node_dims[1] is already set to effective_window_size).
+ Ort::Value input_ort = Ort::Value::CreateTensor(
+ memory_info, input.data(), input.size(), input_node_dims, 2);
+ Ort::Value state_ort = Ort::Value::CreateTensor(
+ memory_info, _state.data(), _state.size(), state_node_dims, 3);
+ Ort::Value sr_ort = Ort::Value::CreateTensor(
+ memory_info, sr.data(), sr.size(), sr_node_dims, 1);
+ ort_inputs.clear();
+ ort_inputs.emplace_back(std::move(input_ort));
+ ort_inputs.emplace_back(std::move(state_ort));
+ ort_inputs.emplace_back(std::move(sr_ort));
+
+ // Run inference.
+ ort_outputs = session->Run(
+ Ort::RunOptions{ nullptr },
+ input_node_names.data(), ort_inputs.data(), ort_inputs.size(),
+ output_node_names.data(), output_node_names.size());
+
+ float speech_prob = ort_outputs[0].GetTensorMutableData()[0];
+ float* stateN = ort_outputs[1].GetTensorMutableData();
+ std::memcpy(_state.data(), stateN, size_state * sizeof(float));
+ current_sample += static_cast(window_size_samples); // Advance by the original window size.
+
+ // If speech is detected (probability >= threshold)
+ if (speech_prob >= threshold) {
+#ifdef __DEBUG_SPEECH_PROB___
+ float speech = current_sample - window_size_samples;
+ printf("{ start: %.3f s (%.3f) %08d}\n", 1.0f * speech / sample_rate, speech_prob, current_sample - window_size_samples);
+#endif
+ if (temp_end != 0) {
+ temp_end = 0;
+ if (next_start < prev_end)
+ next_start = current_sample - window_size_samples;
+ }
+ if (!triggered) {
+ triggered = true;
+ current_speech.start = current_sample - window_size_samples;
+ }
+ // Update context: copy the last context_samples from new_data.
+ std::copy(new_data.end() - context_samples, new_data.end(), _context.begin());
+ return;
+ }
+
+ // If the speech segment becomes too long.
+ if (triggered && ((current_sample - current_speech.start) > max_speech_samples)) {
+ if (prev_end > 0) {
+ current_speech.end = prev_end;
+ speeches.push_back(current_speech);
+ current_speech = timestamp_t();
+ if (next_start < prev_end)
+ triggered = false;
+ else
+ current_speech.start = next_start;
+ prev_end = 0;
+ next_start = 0;
+ temp_end = 0;
+ }
+ else {
+ current_speech.end = current_sample;
+ speeches.push_back(current_speech);
+ current_speech = timestamp_t();
+ prev_end = 0;
+ next_start = 0;
+ temp_end = 0;
+ triggered = false;
+ }
+ std::copy(new_data.end() - context_samples, new_data.end(), _context.begin());
+ return;
+ }
+
+ if ((speech_prob >= (threshold - 0.15)) && (speech_prob < threshold)) {
+ // When the speech probability temporarily drops but is still in speech, update context without changing state.
+ std::copy(new_data.end() - context_samples, new_data.end(), _context.begin());
+ return;
+ }
+
+ if (speech_prob < (threshold - 0.15)) {
+#ifdef __DEBUG_SPEECH_PROB___
+ float speech = current_sample - window_size_samples - speech_pad_samples;
+ printf("{ end: %.3f s (%.3f) %08d}\n", 1.0f * speech / sample_rate, speech_prob, current_sample - window_size_samples);
+#endif
+ if (triggered) {
+ if (temp_end == 0)
+ temp_end = current_sample;
+ if (current_sample - temp_end > min_silence_samples_at_max_speech)
+ prev_end = temp_end;
+ if ((current_sample - temp_end) >= min_silence_samples) {
+ current_speech.end = temp_end;
+ if (current_speech.end - current_speech.start > min_speech_samples) {
+ speeches.push_back(current_speech);
+ current_speech = timestamp_t();
+ prev_end = 0;
+ next_start = 0;
+ temp_end = 0;
+ triggered = false;
+ }
+ }
+ }
+ std::copy(new_data.end() - context_samples, new_data.end(), _context.begin());
+ return;
+ }
+ }
+
+public:
+ // Process the entire audio input.
+ void process(const std::vector& input_wav) {
+ reset_states();
+ audio_length_samples = static_cast(input_wav.size());
+ // Process audio in chunks of window_size_samples (e.g., 512 samples)
+ for (size_t j = 0; j < static_cast(audio_length_samples); j += static_cast(window_size_samples)) {
+ if (j + static_cast(window_size_samples) > static_cast(audio_length_samples))
+ break;
+ std::vector chunk(&input_wav[j], &input_wav[j] + window_size_samples);
+ predict(chunk);
+ }
+ if (current_speech.start >= 0) {
+ current_speech.end = audio_length_samples;
+ speeches.push_back(current_speech);
+ current_speech = timestamp_t();
+ prev_end = 0;
+ next_start = 0;
+ temp_end = 0;
+ triggered = false;
+ }
+ }
+
+ // Returns the detected speech timestamps.
+ const std::vector get_speech_timestamps() const {
+ return speeches;
+ }
+
+ // Public method to reset the internal state.
+ void reset() {
+ reset_states();
+ }
+
+public:
+ // Constructor: sets model path, sample rate, window size (ms), and other parameters.
+ // The parameters are set to match the Python version.
+ VadIterator(const std::wstring ModelPath,
+ int Sample_rate = 16000, int windows_frame_size = 32,
+ float Threshold = 0.5, int min_silence_duration_ms = 100,
+ int speech_pad_ms = 30, int min_speech_duration_ms = 250,
+ float max_speech_duration_s = std::numeric_limits::infinity())
+ : sample_rate(Sample_rate), threshold(Threshold), speech_pad_samples(speech_pad_ms), prev_end(0)
+ {
+ sr_per_ms = sample_rate / 1000; // e.g., 16000 / 1000 = 16
+ window_size_samples = windows_frame_size * sr_per_ms; // e.g., 32ms * 16 = 512 samples
+ effective_window_size = window_size_samples + context_samples; // e.g., 512 + 64 = 576 samples
+ input_node_dims[0] = 1;
+ input_node_dims[1] = effective_window_size;
+ _state.resize(size_state);
+ sr.resize(1);
+ sr[0] = sample_rate;
+ _context.assign(context_samples, 0.0f);
+ min_speech_samples = sr_per_ms * min_speech_duration_ms;
+ max_speech_samples = (sample_rate * max_speech_duration_s - window_size_samples - 2 * speech_pad_samples);
+ min_silence_samples = sr_per_ms * min_silence_duration_ms;
+ min_silence_samples_at_max_speech = sr_per_ms * 98;
+ init_onnx_model(ModelPath);
+ }
+};
+
+int main() {
+ // Read the WAV file (expects 16000 Hz, mono, PCM).
+ wav::WavReader wav_reader("audio/recorder.wav"); // File located in the "audio" folder.
+ int numSamples = wav_reader.num_samples();
+ std::vector input_wav(static_cast(numSamples));
+ for (size_t i = 0; i < static_cast(numSamples); i++) {
+ input_wav[i] = static_cast(*(wav_reader.data() + i));
+ }
+
+ // Set the ONNX model path (file located in the "model" folder).
+ std::wstring model_path = L"model/silero_vad.onnx";
+
+ // Initialize the VadIterator.
+ VadIterator vad(model_path);
+
+ // Process the audio.
+ vad.process(input_wav);
+
+ // Retrieve the speech timestamps (in samples).
+ std::vector stamps = vad.get_speech_timestamps();
+
+ // Convert timestamps to seconds and round to one decimal place (for 16000 Hz).
+ const float sample_rate_float = 16000.0f;
+ for (size_t i = 0; i < stamps.size(); i++) {
+ float start_sec = std::rint((stamps[i].start / sample_rate_float) * 10.0f) / 10.0f;
+ float end_sec = std::rint((stamps[i].end / sample_rate_float) * 10.0f) / 10.0f;
+ std::cout << "Speech detected from "
+ << std::fixed << std::setprecision(1) << start_sec
+ << " s to "
+ << std::fixed << std::setprecision(1) << end_sec
+ << " s" << std::endl;
+ }
+
+ // Optionally, reset the internal state.
+ vad.reset();
+
+ return 0;
+}
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/wav.h b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/wav.h
new file mode 100644
index 000000000..e6ef44251
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp/wav.h
@@ -0,0 +1,237 @@
+// Copyright (c) 2016 Personal (Binbin Zhang)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#ifndef FRONTEND_WAV_H_
+#define FRONTEND_WAV_H_
+
+
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+#include
+
+// #include "utils/log.h"
+
+namespace wav {
+
+struct WavHeader {
+ char riff[4]; // "riff"
+ unsigned int size;
+ char wav[4]; // "WAVE"
+ char fmt[4]; // "fmt "
+ unsigned int fmt_size;
+ uint16_t format;
+ uint16_t channels;
+ unsigned int sample_rate;
+ unsigned int bytes_per_second;
+ uint16_t block_size;
+ uint16_t bit;
+ char data[4]; // "data"
+ unsigned int data_size;
+};
+
+class WavReader {
+ public:
+ WavReader() : data_(nullptr) {}
+ explicit WavReader(const std::string& filename) { Open(filename); }
+
+ bool Open(const std::string& filename) {
+ FILE* fp = fopen(filename.c_str(), "rb"); //文件读取
+ if (NULL == fp) {
+ std::cout << "Error in read " << filename;
+ return false;
+ }
+
+ WavHeader header;
+ fread(&header, 1, sizeof(header), fp);
+ if (header.fmt_size < 16) {
+ printf("WaveData: expect PCM format data "
+ "to have fmt chunk of at least size 16.\n");
+ return false;
+ } else if (header.fmt_size > 16) {
+ int offset = 44 - 8 + header.fmt_size - 16;
+ fseek(fp, offset, SEEK_SET);
+ fread(header.data, 8, sizeof(char), fp);
+ }
+ // check "riff" "WAVE" "fmt " "data"
+
+ // Skip any sub-chunks between "fmt" and "data". Usually there will
+ // be a single "fact" sub chunk, but on Windows there can also be a
+ // "list" sub chunk.
+ while (0 != strncmp(header.data, "data", 4)) {
+ // We will just ignore the data in these chunks.
+ fseek(fp, header.data_size, SEEK_CUR);
+ // read next sub chunk
+ fread(header.data, 8, sizeof(char), fp);
+ }
+
+ if (header.data_size == 0) {
+ int offset = ftell(fp);
+ fseek(fp, 0, SEEK_END);
+ header.data_size = ftell(fp) - offset;
+ fseek(fp, offset, SEEK_SET);
+ }
+
+ num_channel_ = header.channels;
+ sample_rate_ = header.sample_rate;
+ bits_per_sample_ = header.bit;
+ int num_data = header.data_size / (bits_per_sample_ / 8);
+ data_ = new float[num_data]; // Create 1-dim array
+ num_samples_ = num_data / num_channel_;
+
+ std::cout << "num_channel_ :" << num_channel_ << std::endl;
+ std::cout << "sample_rate_ :" << sample_rate_ << std::endl;
+ std::cout << "bits_per_sample_:" << bits_per_sample_ << std::endl;
+ std::cout << "num_samples :" << num_data << std::endl;
+ std::cout << "num_data_size :" << header.data_size << std::endl;
+
+ switch (bits_per_sample_) {
+ case 8: {
+ char sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(char), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ break;
+ }
+ case 16: {
+ int16_t sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(int16_t), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ break;
+ }
+ case 32:
+ {
+ if (header.format == 1) //S32
+ {
+ int sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(int), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ }
+ else if (header.format == 3) // IEEE-float
+ {
+ float sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(float), fp);
+ data_[i] = static_cast(sample);
+ }
+ }
+ else {
+ printf("unsupported quantization bits\n");
+ }
+ break;
+ }
+ default:
+ printf("unsupported quantization bits\n");
+ break;
+ }
+
+ fclose(fp);
+ return true;
+ }
+
+ int num_channel() const { return num_channel_; }
+ int sample_rate() const { return sample_rate_; }
+ int bits_per_sample() const { return bits_per_sample_; }
+ int num_samples() const { return num_samples_; }
+
+ ~WavReader() {
+ delete[] data_;
+ }
+
+ const float* data() const { return data_; }
+
+ private:
+ int num_channel_;
+ int sample_rate_;
+ int bits_per_sample_;
+ int num_samples_; // sample points per channel
+ float* data_;
+};
+
+class WavWriter {
+ public:
+ WavWriter(const float* data, int num_samples, int num_channel,
+ int sample_rate, int bits_per_sample)
+ : data_(data),
+ num_samples_(num_samples),
+ num_channel_(num_channel),
+ sample_rate_(sample_rate),
+ bits_per_sample_(bits_per_sample) {}
+
+ void Write(const std::string& filename) {
+ FILE* fp = fopen(filename.c_str(), "w");
+ // init char 'riff' 'WAVE' 'fmt ' 'data'
+ WavHeader header;
+ char wav_header[44] = {0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57,
+ 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00,
+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00};
+ memcpy(&header, wav_header, sizeof(header));
+ header.channels = num_channel_;
+ header.bit = bits_per_sample_;
+ header.sample_rate = sample_rate_;
+ header.data_size = num_samples_ * num_channel_ * (bits_per_sample_ / 8);
+ header.size = sizeof(header) - 8 + header.data_size;
+ header.bytes_per_second =
+ sample_rate_ * num_channel_ * (bits_per_sample_ / 8);
+ header.block_size = num_channel_ * (bits_per_sample_ / 8);
+
+ fwrite(&header, 1, sizeof(header), fp);
+
+ for (int i = 0; i < num_samples_; ++i) {
+ for (int j = 0; j < num_channel_; ++j) {
+ switch (bits_per_sample_) {
+ case 8: {
+ char sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ case 16: {
+ int16_t sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ case 32: {
+ int sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ }
+ }
+ }
+ fclose(fp);
+ }
+
+ private:
+ const float* data_;
+ int num_samples_; // total float points in data_
+ int num_channel_;
+ int sample_rate_;
+ int bits_per_sample_;
+};
+
+} // namespace wav
+
+#endif // FRONTEND_WAV_H_
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/README.md b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/README.md
new file mode 100644
index 000000000..be18ceeb3
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/README.md
@@ -0,0 +1,45 @@
+# Silero-VAD V5 in C++ (based on LibTorch)
+
+This is the source code for Silero-VAD V5 in C++, utilizing LibTorch. The primary implementation is CPU-based, and you should compare its results with the Python version. Only results at 16kHz have been tested.
+
+Additionally, batch and CUDA inference options are available if you want to explore further. Note that when using batch inference, the speech probabilities may slightly differ from the standard version, likely due to differences in caching. Unlike individual input processing, batch inference may not use the cache from previous chunks. Despite this, batch inference offers significantly faster processing. For optimal performance, consider adjusting the threshold when using batch inference.
+
+## Requirements
+
+- GCC 11.4.0 (GCC >= 5.1)
+- LibTorch 1.13.0 (other versions are also acceptable)
+
+## Download LibTorch
+
+```bash
+-CPU Version
+wget https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-1.13.0%2Bcpu.zip
+unzip libtorch-shared-with-deps-1.13.0+cpu.zip'
+
+-CUDA Version
+wget https://download.pytorch.org/libtorch/cu116/libtorch-shared-with-deps-1.13.0%2Bcu116.zip
+unzip libtorch-shared-with-deps-1.13.0+cu116.zip
+```
+
+## Compilation
+
+```bash
+-CPU Version
+g++ main.cc silero_torch.cc -I ./libtorch/include/ -I ./libtorch/include/torch/csrc/api/include -L ./libtorch/lib/ -ltorch -ltorch_cpu -lc10 -Wl,-rpath,./libtorch/lib/ -o silero -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0
+
+-CUDA Version
+g++ main.cc silero_torch.cc -I ./libtorch/include/ -I ./libtorch/include/torch/csrc/api/include -L ./libtorch/lib/ -ltorch -ltorch_cuda -ltorch_cpu -lc10 -Wl,-rpath,./libtorch/lib/ -o silero -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 -DUSE_GPU
+```
+
+
+## Optional Compilation Flags
+-DUSE_BATCH: Enable batch inference
+-DUSE_GPU: Use GPU for inference
+
+## Run the Program
+To run the program, use the following command:
+
+`./silero aepyx.wav 16000 0.5`
+
+The sample file aepyx.wav is part of the Voxconverse dataset.
+File details: aepyx.wav is a 16kHz, 16-bit audio file.
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/main.cc b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/main.cc
new file mode 100644
index 000000000..3f774e70b
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/main.cc
@@ -0,0 +1,54 @@
+#include
+#include "silero_torch.h"
+#include "wav.h"
+
+int main(int argc, char* argv[]) {
+
+ if(argc != 4){
+ std::cerr<<"Usage : "< "< input_wav(wav_reader.num_samples());
+
+ for (int i = 0; i < wav_reader.num_samples(); i++)
+ {
+ input_wav[i] = static_cast(*(wav_reader.data() + i));
+ }
+
+ vad.SpeechProbs(input_wav);
+
+ std::vector speeches = vad.GetSpeechTimestamps();
+ for(const auto& speech : speeches){
+ if(vad.print_as_samples){
+ std::cout<<"{'start': "<(speech.start)<<", 'end': "<(speech.end)<<"}"<& input_wav){
+ // Set the sample rate (must match the model's expected sample rate)
+ // Process the waveform in chunks of 512 samples
+ int num_samples = input_wav.size();
+ int num_chunks = num_samples / window_size_samples;
+ int remainder_samples = num_samples % window_size_samples;
+
+ total_sample_size += num_samples;
+
+ torch::Tensor output;
+ std::vector chunks;
+
+ for (int i = 0; i < num_chunks; i++) {
+
+ float* chunk_start = input_wav.data() + i *window_size_samples;
+ torch::Tensor chunk = torch::from_blob(chunk_start, {1,window_size_samples}, torch::kFloat32);
+ //std::cout<<"chunk size : "<0){//마지막 chunk && 나머지가 존재
+ int remaining_samples = num_samples - num_chunks * window_size_samples;
+ //std::cout<<"Remainder size : "< inputs;
+ inputs.push_back(batched_chunks); // Batch of chunks
+ inputs.push_back(sample_rate); // Assuming sample_rate is a valid input for the model
+
+ // Run inference on the batch
+ torch::NoGradGuard no_grad;
+ torch::Tensor output = model.forward(inputs).toTensor();
+#ifdef USE_GPU
+ output = output.to(at::kCPU); // Move the output back to CPU once
+#endif
+ // Collect output probabilities
+ for (int i = 0; i < chunks.size(); i++) {
+ float output_f = output[i].item();
+ outputs_prob.push_back(output_f);
+ //std::cout << "Chunk " << i << " prob: " << output_f<< "\n";
+ }
+#else
+
+ std::vector outputs;
+ torch::Tensor batched_chunks = torch::stack(chunks);
+#ifdef USE_GPU
+ batched_chunks = batched_chunks.to(at::kCUDA);
+#endif
+ for (int i = 0; i < chunks.size(); i++) {
+ torch::NoGradGuard no_grad;
+ std::vector inputs;
+ inputs.push_back(batched_chunks[i]);
+ inputs.push_back(sample_rate);
+
+ torch::Tensor output = model.forward(inputs).toTensor();
+ outputs.push_back(output);
+ }
+ torch::Tensor all_outputs = torch::stack(outputs);
+#ifdef USE_GPU
+ all_outputs = all_outputs.to(at::kCPU);
+#endif
+ for (int i = 0; i < chunks.size(); i++) {
+ float output_f = all_outputs[i].item();
+ outputs_prob.push_back(output_f);
+ }
+
+
+
+#endif
+
+ }
+
+
+ }
+
+
+ std::vector VadIterator::GetSpeechTimestamps() {
+ std::vector speeches = DoVad();
+
+#ifdef USE_BATCH
+ //When you use BATCH inference. You would better use 'mergeSpeeches' function to arrage time stamp.
+ //It could be better get reasonable output because of distorted probs.
+ duration_merge_samples = sample_rate * max_duration_merge_ms / 1000;
+ std::vector speeches_merge = mergeSpeeches(speeches, duration_merge_samples);
+ if(!print_as_samples){
+ for (auto& speech : speeches_merge) { //samples to second
+ speech.start /= sample_rate;
+ speech.end /= sample_rate;
+ }
+ }
+
+ return speeches_merge;
+#else
+
+ if(!print_as_samples){
+ for (auto& speech : speeches) { //samples to second
+ speech.start /= sample_rate;
+ speech.end /= sample_rate;
+ }
+ }
+
+ return speeches;
+
+#endif
+
+ }
+ void VadIterator::SetVariables(){
+ init_engine(window_size_ms);
+ }
+
+ void VadIterator::init_engine(int window_size_ms) {
+ min_silence_samples = sample_rate * min_silence_duration_ms / 1000;
+ speech_pad_samples = sample_rate * speech_pad_ms / 1000;
+ window_size_samples = sample_rate / 1000 * window_size_ms;
+ min_speech_samples = sample_rate * min_speech_duration_ms / 1000;
+ }
+
+ void VadIterator::init_torch_model(const std::string& model_path) {
+ at::set_num_threads(1);
+ model = torch::jit::load(model_path);
+
+#ifdef USE_GPU
+ if (!torch::cuda::is_available()) {
+ std::cout<<"CUDA is not available! Please check your GPU settings"< VadIterator::DoVad() {
+ std::vector speeches;
+
+ for (size_t i = 0; i < outputs_prob.size(); ++i) {
+ float speech_prob = outputs_prob[i];
+ //std::cout << speech_prob << std::endl;
+ //std::cout << "Chunk " << i << " Prob: " << speech_prob << "\n";
+ //std::cout << speech_prob << " ";
+ current_sample += window_size_samples;
+
+ if (speech_prob >= threshold && temp_end != 0) {
+ temp_end = 0;
+ }
+
+ if (speech_prob >= threshold && !triggered) {
+ triggered = true;
+ SpeechSegment segment;
+ segment.start = std::max(static_cast(0), current_sample - speech_pad_samples - window_size_samples);
+ speeches.push_back(segment);
+ continue;
+ }
+
+ if (speech_prob < threshold - 0.15f && triggered) {
+ if (temp_end == 0) {
+ temp_end = current_sample;
+ }
+
+ if (current_sample - temp_end < min_silence_samples) {
+ continue;
+ } else {
+ SpeechSegment& segment = speeches.back();
+ segment.end = temp_end + speech_pad_samples - window_size_samples;
+ temp_end = 0;
+ triggered = false;
+ }
+ }
+ }
+
+ if (triggered) { //만약 낮은 확률을 보이다가 마지막프레임 prbos만 딱 확률이 높게 나오면 위에서 triggerd = true 메핑과 동시에 segment start가 돼서 문제가 될것 같은데? start = end 같은값? 후처리가 있으니 문제가 없으려나?
+ std::cout<<"when last triggered is keep working until last Probs"<speech_pad_samples) - (speech.start + this->speech_pad_samples) < min_speech_samples);
+ //min_speech_samples is 4000samples(0.25sec)
+ //여기서 포인트!! 계산 할때는 start,end sample에'speech_pad_samples' 사이즈를 추가한후 길이를 측정함.
+ }
+ ),
+ speeches.end()
+ );
+
+
+ //std::cout< VadIterator::mergeSpeeches(const std::vector& speeches, int duration_merge_samples) {
+ std::vector mergedSpeeches;
+
+ if (speeches.empty()) {
+ return mergedSpeeches; // 빈 벡터 반환
+ }
+
+ // 첫 번째 구간으로 초기화
+ SpeechSegment currentSegment = speeches[0];
+
+ for (size_t i = 1; i < speeches.size(); ++i) { //첫번째 start,end 정보 건너뛰기. 그래서 i=1부터
+ // 두 구간의 차이가 threshold(duration_merge_samples)보다 작은 경우, 합침
+ if (speeches[i].start - currentSegment.end < duration_merge_samples) {
+ // 현재 구간의 끝점을 업데이트
+ currentSegment.end = speeches[i].end;
+ } else {
+ // 차이가 threshold(duration_merge_samples) 이상이면 현재 구간을 저장하고 새로운 구간 시작
+ mergedSpeeches.push_back(currentSegment);
+ currentSegment = speeches[i];
+ }
+ }
+
+ // 마지막 구간 추가
+ mergedSpeeches.push_back(currentSegment);
+
+ return mergedSpeeches;
+ }
+
+ }
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/silero_torch.h b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/silero_torch.h
new file mode 100644
index 000000000..d8d3bc72b
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/silero_torch.h
@@ -0,0 +1,75 @@
+//Author : Nathan Lee
+//Created On : 2024-11-18
+//Description : silero 5.1 system for torch-script(c++).
+//Version : 1.0
+
+#ifndef SILERO_TORCH_H
+#define SILERO_TORCH_H
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include
+#include
+
+
+namespace silero{
+
+ struct SpeechSegment{
+ int start;
+ int end;
+ };
+
+ class VadIterator{
+ public:
+
+ VadIterator(const std::string &model_path, float threshold = 0.5, int sample_rate = 16000,
+ int window_size_ms = 32, int speech_pad_ms = 30, int min_silence_duration_ms = 100,
+ int min_speech_duration_ms = 250, int max_duration_merge_ms = 300, bool print_as_samples = false);
+ ~VadIterator();
+
+
+ void SpeechProbs(std::vector& input_wav);
+ std::vector GetSpeechTimestamps();
+ void SetVariables();
+
+ float threshold;
+ int sample_rate;
+ int window_size_ms;
+ int min_speech_duration_ms;
+ int max_duration_merge_ms;
+ bool print_as_samples;
+
+ private:
+ torch::jit::script::Module model;
+ std::vector outputs_prob;
+ int min_silence_samples;
+ int min_speech_samples;
+ int speech_pad_samples;
+ int window_size_samples;
+ int duration_merge_samples;
+ int current_sample = 0;
+
+ int total_sample_size=0;
+
+ int min_silence_duration_ms;
+ int speech_pad_ms;
+ bool triggered = false;
+ int temp_end = 0;
+
+ void init_engine(int window_size_ms);
+ void init_torch_model(const std::string& model_path);
+ void reset_states();
+ std::vector DoVad();
+ std::vector mergeSpeeches(const std::vector& speeches, int duration_merge_samples);
+
+ };
+
+}
+#endif // SILERO_TORCH_H
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/wav.h b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/wav.h
new file mode 100644
index 000000000..249d7e34d
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch/wav.h
@@ -0,0 +1,235 @@
+// Copyright (c) 2016 Personal (Binbin Zhang)
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+
+#ifndef FRONTEND_WAV_H_
+#define FRONTEND_WAV_H_
+
+#include
+#include
+#include
+#include
+#include
+
+#include
+
+// #include "utils/log.h"
+
+namespace wav {
+
+struct WavHeader {
+ char riff[4]; // "riff"
+ unsigned int size;
+ char wav[4]; // "WAVE"
+ char fmt[4]; // "fmt "
+ unsigned int fmt_size;
+ uint16_t format;
+ uint16_t channels;
+ unsigned int sample_rate;
+ unsigned int bytes_per_second;
+ uint16_t block_size;
+ uint16_t bit;
+ char data[4]; // "data"
+ unsigned int data_size;
+};
+
+class WavReader {
+ public:
+ WavReader() : data_(nullptr) {}
+ explicit WavReader(const std::string& filename) { Open(filename); }
+
+ bool Open(const std::string& filename) {
+ FILE* fp = fopen(filename.c_str(), "rb"); //文件读取
+ if (NULL == fp) {
+ std::cout << "Error in read " << filename;
+ return false;
+ }
+
+ WavHeader header;
+ fread(&header, 1, sizeof(header), fp);
+ if (header.fmt_size < 16) {
+ printf("WaveData: expect PCM format data "
+ "to have fmt chunk of at least size 16.\n");
+ return false;
+ } else if (header.fmt_size > 16) {
+ int offset = 44 - 8 + header.fmt_size - 16;
+ fseek(fp, offset, SEEK_SET);
+ fread(header.data, 8, sizeof(char), fp);
+ }
+ // check "riff" "WAVE" "fmt " "data"
+
+ // Skip any sub-chunks between "fmt" and "data". Usually there will
+ // be a single "fact" sub chunk, but on Windows there can also be a
+ // "list" sub chunk.
+ while (0 != strncmp(header.data, "data", 4)) {
+ // We will just ignore the data in these chunks.
+ fseek(fp, header.data_size, SEEK_CUR);
+ // read next sub chunk
+ fread(header.data, 8, sizeof(char), fp);
+ }
+
+ if (header.data_size == 0) {
+ int offset = ftell(fp);
+ fseek(fp, 0, SEEK_END);
+ header.data_size = ftell(fp) - offset;
+ fseek(fp, offset, SEEK_SET);
+ }
+
+ num_channel_ = header.channels;
+ sample_rate_ = header.sample_rate;
+ bits_per_sample_ = header.bit;
+ int num_data = header.data_size / (bits_per_sample_ / 8);
+ data_ = new float[num_data]; // Create 1-dim array
+ num_samples_ = num_data / num_channel_;
+
+ std::cout << "num_channel_ :" << num_channel_ << std::endl;
+ std::cout << "sample_rate_ :" << sample_rate_ << std::endl;
+ std::cout << "bits_per_sample_:" << bits_per_sample_ << std::endl;
+ std::cout << "num_samples :" << num_data << std::endl;
+ std::cout << "num_data_size :" << header.data_size << std::endl;
+
+ switch (bits_per_sample_) {
+ case 8: {
+ char sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(char), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ break;
+ }
+ case 16: {
+ int16_t sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(int16_t), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ break;
+ }
+ case 32:
+ {
+ if (header.format == 1) //S32
+ {
+ int sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(int), fp);
+ data_[i] = static_cast(sample) / 32768;
+ }
+ }
+ else if (header.format == 3) // IEEE-float
+ {
+ float sample;
+ for (int i = 0; i < num_data; ++i) {
+ fread(&sample, 1, sizeof(float), fp);
+ data_[i] = static_cast(sample);
+ }
+ }
+ else {
+ printf("unsupported quantization bits\n");
+ }
+ break;
+ }
+ default:
+ printf("unsupported quantization bits\n");
+ break;
+ }
+
+ fclose(fp);
+ return true;
+ }
+
+ int num_channel() const { return num_channel_; }
+ int sample_rate() const { return sample_rate_; }
+ int bits_per_sample() const { return bits_per_sample_; }
+ int num_samples() const { return num_samples_; }
+
+ ~WavReader() {
+ delete[] data_;
+ }
+
+ const float* data() const { return data_; }
+
+ private:
+ int num_channel_;
+ int sample_rate_;
+ int bits_per_sample_;
+ int num_samples_; // sample points per channel
+ float* data_;
+};
+
+class WavWriter {
+ public:
+ WavWriter(const float* data, int num_samples, int num_channel,
+ int sample_rate, int bits_per_sample)
+ : data_(data),
+ num_samples_(num_samples),
+ num_channel_(num_channel),
+ sample_rate_(sample_rate),
+ bits_per_sample_(bits_per_sample) {}
+
+ void Write(const std::string& filename) {
+ FILE* fp = fopen(filename.c_str(), "w");
+ // init char 'riff' 'WAVE' 'fmt ' 'data'
+ WavHeader header;
+ char wav_header[44] = {0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57,
+ 0x41, 0x56, 0x45, 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00,
+ 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x00};
+ memcpy(&header, wav_header, sizeof(header));
+ header.channels = num_channel_;
+ header.bit = bits_per_sample_;
+ header.sample_rate = sample_rate_;
+ header.data_size = num_samples_ * num_channel_ * (bits_per_sample_ / 8);
+ header.size = sizeof(header) - 8 + header.data_size;
+ header.bytes_per_second =
+ sample_rate_ * num_channel_ * (bits_per_sample_ / 8);
+ header.block_size = num_channel_ * (bits_per_sample_ / 8);
+
+ fwrite(&header, 1, sizeof(header), fp);
+
+ for (int i = 0; i < num_samples_; ++i) {
+ for (int j = 0; j < num_channel_; ++j) {
+ switch (bits_per_sample_) {
+ case 8: {
+ char sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ case 16: {
+ int16_t sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ case 32: {
+ int sample = static_cast(data_[i * num_channel_ + j]);
+ fwrite(&sample, 1, sizeof(sample), fp);
+ break;
+ }
+ }
+ }
+ }
+ fclose(fp);
+ }
+
+ private:
+ const float* data_;
+ int num_samples_; // total float points in data_
+ int num_channel_;
+ int sample_rate_;
+ int bits_per_sample_;
+};
+
+} // namespace wenet
+
+#endif // FRONTEND_WAV_H_
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/README.md b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/README.md
new file mode 100644
index 000000000..be18ceeb3
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/README.md
@@ -0,0 +1,45 @@
+# Silero-VAD V5 in C++ (based on LibTorch)
+
+This is the source code for Silero-VAD V5 in C++, utilizing LibTorch. The primary implementation is CPU-based, and you should compare its results with the Python version. Only results at 16kHz have been tested.
+
+Additionally, batch and CUDA inference options are available if you want to explore further. Note that when using batch inference, the speech probabilities may slightly differ from the standard version, likely due to differences in caching. Unlike individual input processing, batch inference may not use the cache from previous chunks. Despite this, batch inference offers significantly faster processing. For optimal performance, consider adjusting the threshold when using batch inference.
+
+## Requirements
+
+- GCC 11.4.0 (GCC >= 5.1)
+- LibTorch 1.13.0 (other versions are also acceptable)
+
+## Download LibTorch
+
+```bash
+-CPU Version
+wget https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-1.13.0%2Bcpu.zip
+unzip libtorch-shared-with-deps-1.13.0+cpu.zip'
+
+-CUDA Version
+wget https://download.pytorch.org/libtorch/cu116/libtorch-shared-with-deps-1.13.0%2Bcu116.zip
+unzip libtorch-shared-with-deps-1.13.0+cu116.zip
+```
+
+## Compilation
+
+```bash
+-CPU Version
+g++ main.cc silero_torch.cc -I ./libtorch/include/ -I ./libtorch/include/torch/csrc/api/include -L ./libtorch/lib/ -ltorch -ltorch_cpu -lc10 -Wl,-rpath,./libtorch/lib/ -o silero -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0
+
+-CUDA Version
+g++ main.cc silero_torch.cc -I ./libtorch/include/ -I ./libtorch/include/torch/csrc/api/include -L ./libtorch/lib/ -ltorch -ltorch_cuda -ltorch_cpu -lc10 -Wl,-rpath,./libtorch/lib/ -o silero -std=c++14 -D_GLIBCXX_USE_CXX11_ABI=0 -DUSE_GPU
+```
+
+
+## Optional Compilation Flags
+-DUSE_BATCH: Enable batch inference
+-DUSE_GPU: Use GPU for inference
+
+## Run the Program
+To run the program, use the following command:
+
+`./silero aepyx.wav 16000 0.5`
+
+The sample file aepyx.wav is part of the Voxconverse dataset.
+File details: aepyx.wav is a 16kHz, 16-bit audio file.
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/main.cc b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/main.cc
new file mode 100644
index 000000000..3f774e70b
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/main.cc
@@ -0,0 +1,54 @@
+#include
+#include "silero_torch.h"
+#include "wav.h"
+
+int main(int argc, char* argv[]) {
+
+ if(argc != 4){
+ std::cerr<<"Usage : "< "< input_wav(wav_reader.num_samples());
+
+ for (int i = 0; i < wav_reader.num_samples(); i++)
+ {
+ input_wav[i] = static_cast(*(wav_reader.data() + i));
+ }
+
+ vad.SpeechProbs(input_wav);
+
+ std::vector speeches = vad.GetSpeechTimestamps();
+ for(const auto& speech : speeches){
+ if(vad.print_as_samples){
+ std::cout<<"{'start': "<(speech.start)<<", 'end': "<(speech.end)<<"}"<& input_wav){
+ // Set the sample rate (must match the model's expected sample rate)
+ // Process the waveform in chunks of 512 samples
+ int num_samples = input_wav.size();
+ int num_chunks = num_samples / window_size_samples;
+ int remainder_samples = num_samples % window_size_samples;
+
+ total_sample_size += num_samples;
+
+ torch::Tensor output;
+ std::vector chunks;
+
+ for (int i = 0; i < num_chunks; i++) {
+
+ float* chunk_start = input_wav.data() + i *window_size_samples;
+ torch::Tensor chunk = torch::from_blob(chunk_start, {1,window_size_samples}, torch::kFloat32);
+ //std::cout<<"chunk size : "<0){//마지막 chunk && 나머지가 존재
+ int remaining_samples = num_samples - num_chunks * window_size_samples;
+ //std::cout<<"Remainder size : "< inputs;
+ inputs.push_back(batched_chunks); // Batch of chunks
+ inputs.push_back(sample_rate); // Assuming sample_rate is a valid input for the model
+
+ // Run inference on the batch
+ torch::NoGradGuard no_grad;
+ torch::Tensor output = model.forward(inputs).toTensor();
+#ifdef USE_GPU
+ output = output.to(at::kCPU); // Move the output back to CPU once
+#endif
+ // Collect output probabilities
+ for (int i = 0; i < chunks.size(); i++) {
+ float output_f = output[i].item();
+ outputs_prob.push_back(output_f);
+ //std::cout << "Chunk " << i << " prob: " << output_f<< "\n";
+ }
+#else
+
+ std::vector outputs;
+ torch::Tensor batched_chunks = torch::stack(chunks);
+#ifdef USE_GPU
+ batched_chunks = batched_chunks.to(at::kCUDA);
+#endif
+ for (int i = 0; i < chunks.size(); i++) {
+ torch::NoGradGuard no_grad;
+ std::vector inputs;
+ inputs.push_back(batched_chunks[i]);
+ inputs.push_back(sample_rate);
+
+ torch::Tensor output = model.forward(inputs).toTensor();
+ outputs.push_back(output);
+ }
+ torch::Tensor all_outputs = torch::stack(outputs);
+#ifdef USE_GPU
+ all_outputs = all_outputs.to(at::kCPU);
+#endif
+ for (int i = 0; i < chunks.size(); i++) {
+ float output_f = all_outputs[i].item();
+ outputs_prob.push_back(output_f);
+ }
+
+
+
+#endif
+
+ }
+
+
+ }
+
+
+ std::vector VadIterator::GetSpeechTimestamps() {
+ std::vector speeches = DoVad();
+
+#ifdef USE_BATCH
+ //When you use BATCH inference. You would better use 'mergeSpeeches' function to arrage time stamp.
+ //It could be better get reasonable output because of distorted probs.
+ duration_merge_samples = sample_rate * max_duration_merge_ms / 1000;
+ std::vector speeches_merge = mergeSpeeches(speeches, duration_merge_samples);
+ if(!print_as_samples){
+ for (auto& speech : speeches_merge) { //samples to second
+ speech.start /= sample_rate;
+ speech.end /= sample_rate;
+ }
+ }
+
+ return speeches_merge;
+#else
+
+ if(!print_as_samples){
+ for (auto& speech : speeches) { //samples to second
+ speech.start /= sample_rate;
+ speech.end /= sample_rate;
+ }
+ }
+
+ return speeches;
+
+#endif
+
+ }
+ void VadIterator::SetVariables(){
+ init_engine(window_size_ms);
+ }
+
+ void VadIterator::init_engine(int window_size_ms) {
+ min_silence_samples = sample_rate * min_silence_duration_ms / 1000;
+ speech_pad_samples = sample_rate * speech_pad_ms / 1000;
+ window_size_samples = sample_rate / 1000 * window_size_ms;
+ min_speech_samples = sample_rate * min_speech_duration_ms / 1000;
+ }
+
+ void VadIterator::init_torch_model(const std::string& model_path) {
+ at::set_num_threads(1);
+ model = torch::jit::load(model_path);
+
+#ifdef USE_GPU
+ if (!torch::cuda::is_available()) {
+ std::cout<<"CUDA is not available! Please check your GPU settings"< VadIterator::DoVad() {
+ std::vector speeches;
+
+ for (size_t i = 0; i < outputs_prob.size(); ++i) {
+ float speech_prob = outputs_prob[i];
+ //std::cout << speech_prob << std::endl;
+ //std::cout << "Chunk " << i << " Prob: " << speech_prob << "\n";
+ //std::cout << speech_prob << " ";
+ current_sample += window_size_samples;
+
+ if (speech_prob >= threshold && temp_end != 0) {
+ temp_end = 0;
+ }
+
+ if (speech_prob >= threshold && !triggered) {
+ triggered = true;
+ SpeechSegment segment;
+ segment.start = std::max(static_cast(0), current_sample - speech_pad_samples - window_size_samples);
+ speeches.push_back(segment);
+ continue;
+ }
+
+ if (speech_prob < threshold - 0.15f && triggered) {
+ if (temp_end == 0) {
+ temp_end = current_sample;
+ }
+
+ if (current_sample - temp_end < min_silence_samples) {
+ continue;
+ } else {
+ SpeechSegment& segment = speeches.back();
+ segment.end = temp_end + speech_pad_samples - window_size_samples;
+ temp_end = 0;
+ triggered = false;
+ }
+ }
+ }
+
+ if (triggered) { //만약 낮은 확률을 보이다가 마지막프레임 prbos만 딱 확률이 높게 나오면 위에서 triggerd = true 메핑과 동시에 segment start가 돼서 문제가 될것 같은데? start = end 같은값? 후처리가 있으니 문제가 없으려나?
+ std::cout<<"when last triggered is keep working until last Probs"<speech_pad_samples) - (speech.start + this->speech_pad_samples) < min_speech_samples);
+ //min_speech_samples is 4000samples(0.25sec)
+ //여기서 포인트!! 계산 할때는 start,end sample에'speech_pad_samples' 사이즈를 추가한후 길이를 측정함.
+ }
+ ),
+ speeches.end()
+ );
+
+
+ //std::cout< VadIterator::mergeSpeeches(const std::vector& speeches, int duration_merge_samples) {
+ std::vector mergedSpeeches;
+
+ if (speeches.empty()) {
+ return mergedSpeeches; // 빈 벡터 반환
+ }
+
+ // 첫 번째 구간으로 초기화
+ SpeechSegment currentSegment = speeches[0];
+
+ for (size_t i = 1; i < speeches.size(); ++i) { //첫번째 start,end 정보 건너뛰기. 그래서 i=1부터
+ // 두 구간의 차이가 threshold(duration_merge_samples)보다 작은 경우, 합침
+ if (speeches[i].start - currentSegment.end < duration_merge_samples) {
+ // 현재 구간의 끝점을 업데이트
+ currentSegment.end = speeches[i].end;
+ } else {
+ // 차이가 threshold(duration_merge_samples) 이상이면 현재 구간을 저장하고 새로운 구간 시작
+ mergedSpeeches.push_back(currentSegment);
+ currentSegment = speeches[i];
+ }
+ }
+
+ // 마지막 구간 추가
+ mergedSpeeches.push_back(currentSegment);
+
+ return mergedSpeeches;
+ }
+
+ }
diff --git a/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/silero_torch.h b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/silero_torch.h
new file mode 100644
index 000000000..d8d3bc72b
--- /dev/null
+++ b/main/xiaozhi-server/models/snakers4_silero-vad/examples/cpp_libtorch_deprecated/silero_torch.h
@@ -0,0 +1,75 @@
+//Author : Nathan Lee
+//Created On : 2024-11-18
+//Description : silero 5.1 system for torch-script(c++).
+//Version : 1.0
+
+#ifndef SILERO_TORCH_H
+#define SILERO_TORCH_H
+
+#include
+#include
+#include
+#include
+#include
+#include