mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-24 04:19:48 +01:00
SenseVoice 识别日语时偶尔按词输出空格(如「今日 の こと を 少し 長め に」), 这些空格会原样进入对话历史并交给 LLM。lang_tag_filter 现在去掉两个 中日文字符之间的空格,韩文、英文的词间空格保持不变。
86 lines
2.9 KiB
Python
86 lines
2.9 KiB
Python
import re
|
|
from config.logger import setup_logging
|
|
|
|
TAG = __name__
|
|
logger = setup_logging()
|
|
|
|
EMOTION_EMOJI_MAP = {
|
|
"HAPPY": "🙂",
|
|
"SAD": "😔",
|
|
"ANGRY": "😡",
|
|
"NEUTRAL": "😶",
|
|
"FEARFUL": "😰",
|
|
"DISGUSTED": "🤢",
|
|
"SURPRISED": "😲",
|
|
"EMO_UNKNOWN": "😶", # 未知情绪默认用中性表情
|
|
}
|
|
# EVENT_EMOJI_MAP = {
|
|
# "<|BGM|>": "🎼",
|
|
# "<|Speech|>": "",
|
|
# "<|Applause|>": "👏",
|
|
# "<|Laughter|>": "😀",
|
|
# "<|Cry|>": "😭",
|
|
# "<|Sneeze|>": "🤧",
|
|
# "<|Breath|>": "",
|
|
# "<|Cough|>": "🤧",
|
|
# }
|
|
|
|
def lang_tag_filter(text: str) -> dict:
|
|
"""
|
|
解析 FunASR 识别结果,按顺序提取标签和纯文本内容
|
|
|
|
Args:
|
|
text: ASR 识别的原始文本,可能包含多种标签
|
|
|
|
Returns:
|
|
dict: {"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好"} 如果有标签,
|
|
{"content": "纯文本"} 如果没有标签
|
|
|
|
Examples:
|
|
FunASR 输出格式:<|语种|><|情绪|><|事件|><|其他选项|>原文
|
|
>>> lang_tag_filter("<|zh|><|SAD|><|Speech|><|withitn|>你好啊,测试测试。")
|
|
{"language": "zh", "emotion": "SAD", "emoji": "😔", "content": "你好啊,测试测试。"}
|
|
>>> lang_tag_filter("<|en|><|HAPPY|><|Speech|><|withitn|>Hello hello.")
|
|
{"language": "en", "emotion": "HAPPY", "emoji": "🙂", "content": "Hello hello."}
|
|
>>> lang_tag_filter("plain text")
|
|
{"content": "plain text"}
|
|
"""
|
|
# 提取所有标签(按顺序)
|
|
tag_pattern = r"<\|([^|]+)\|>"
|
|
all_tags = re.findall(tag_pattern, text)
|
|
|
|
# 移除所有 <|...|> 格式的标签,获取纯文本
|
|
clean_text = re.sub(tag_pattern, "", text).strip()
|
|
# SenseVoice 对日语等偶尔按词输出空格(如「今日 の こと を」),去掉中日文字符之间的空格;
|
|
# 韩文、英文的词间空格不受影响
|
|
clean_text = re.sub(
|
|
r"(?<=[\u3000-\u303f\u3040-\u30ff\u4e00-\u9fff\uff01-\uff60])\s+"
|
|
r"(?=[\u3000-\u303f\u3040-\u30ff\u4e00-\u9fff\uff01-\uff60])",
|
|
"",
|
|
clean_text,
|
|
)
|
|
|
|
# 保持返回结构一致,避免调用方把纯文本误当成字典访问。
|
|
if not all_tags:
|
|
return {"content": clean_text}
|
|
|
|
# 按照 FunASR 的固定顺序提取标签,返回 dict
|
|
language = all_tags[0] if len(all_tags) > 0 else "zh"
|
|
emotion = all_tags[1] if len(all_tags) > 1 else "NEUTRAL"
|
|
# event = all_tags[2] if len(all_tags) > 2 else "Speech" # 事件标签暂不使用
|
|
|
|
result = {
|
|
"content": clean_text,
|
|
"language": language,
|
|
"emotion": emotion,
|
|
# "event": event,
|
|
}
|
|
|
|
# 添加 emoji 映射
|
|
if emotion in EMOTION_EMOJI_MAP:
|
|
result["emotion"] = EMOTION_EMOJI_MAP[emotion]
|
|
# 事件标签暂不使用
|
|
# if event in EVENT_EMOJI_MAP:
|
|
# result["event"] = EVENT_EMOJI_MAP[event]
|
|
|
|
return result
|