xiaozhi-esp32-server/main/xiaozhi-server/xiaozhi-memory/utils/tokenizer.py
SerenNoble c9c8324cc8 feat: 自构建部署可移植化 + aipet/缓存注册 + 记忆系统定制
可移植性(换机 git clone + docker compose -f docker-compose-selfbuild.yml up --build 即用):
- Dockerfile-server: server-base 改 ARG 引用(默认 NJU 镜像,国内自包含;海外可 --build-arg 覆盖)
- docker-compose-selfbuild.yml: 新增自构建 compose(server/web build:,mysql/redis image:)
- .dockerignore: 排除运行时数据目录(**/mysql/、*.db、**/data/),修复 build context 权限错误
- Dockerfile-web: start.sh CRLF→LF(修 exec "no such file or directory")

智控台 provider 注册(纯数据库驱动,前端无白名单):
- 202606191200.sql: 注册 SYSTEM_Memory_aipet 记忆 provider
- 202606120930.sql: 修列名 bug(is_custom→creator/updater)+ cache 改 boolean 开关
- db.changelog-master.yaml: 注册 202606191200
- AddModelDialog.vue: boolean 字段渲染为 el-switch 开关

server 端核心定制入库(此前未提交,换机会缺失):
- core/connection.py: 当天日程注入半稳定系统提示词
- core/providers/memory/aipet/aipet.py: FTS5 检索增强
- xiaozhi-memory/*: memory_manager / fts / sqlite_store / tokenizer / time_parser 检索修复

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-20 23:25:43 +08:00

96 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
中文分词工具
"""
from typing import List
import re
class Tokenizer:
"""分词器基类"""
def tokenize(self, text: str) -> List[str]:
"""分词"""
pass
class JiebaTokenizer(Tokenizer):
"""jieba分词器"""
def __init__(self):
try:
import jieba
self.jieba = jieba
self.available = True
except ImportError:
self.available = False
def tokenize(self, text: str) -> List[str]:
"""使用jieba分词(搜索引擎模式,切出更多子词,提升检索召回)"""
if not self.available:
# 降级到简单分词
return SimpleTokenizer().tokenize(text)
return list(self.jieba.cut_for_search(text))
class SimpleTokenizer(Tokenizer):
"""简单分词器(按字符和空格)"""
def tokenize(self, text: str) -> List[str]:
"""简单分词:按空格分割,并对中文按字符分割"""
# 先按空格分割
parts = text.split()
tokens = []
for part in parts:
# 检查是否包含中文
if re.search(r'[一-鿿]', part):
# 中文按字符分割
tokens.extend(list(part))
else:
# 英文按空格分割
tokens.append(part)
return tokens
class Unicode61Tokenizer(Tokenizer):
"""SQLite FTS5 unicode61分词器模拟"""
def tokenize(self, text: str) -> List[str]:
"""类似unicode61的分词:按空格和标点分割"""
# 按非字母数字字符分割
tokens = re.findall(r'\w+', text)
return tokens
# 默认分词器
_default_tokenizer = None
def get_tokenizer() -> Tokenizer:
"""获取默认分词器"""
global _default_tokenizer
if _default_tokenizer is None:
# 优先使用jieba
_default_tokenizer = JiebaTokenizer()
return _default_tokenizer
def tokenize(text: str) -> List[str]:
"""分词便捷函数"""
return get_tokenizer().tokenize(text)
def tokenize_to_string(text: str) -> str:
"""分词并返回字符串(用于FTS5)"""
tokens = tokenize(text)
safe_tokens = []
for t in tokens:
t = t.strip()
if not t:
continue
# 只保留字母、数字、中文字符、下划线,去掉所有FTS5特殊字符和标点
t = re.sub(r'[^\w一-鿿]', '', t)
if t:
safe_tokens.append(t)
return " ".join(safe_tokens)