feat(common problems fuzzy query): 增加常用问题模糊查询兜底
This commit is contained in:
1 parent
b69c725992
commit
5a269f940d
18 files changed
+411
-58
No files matched your search
@@ -1,11 +1,19 @@
|
||||
"""
|
||||
backend/app/services/faq_text_utils.py
|
||||
|
||||
用途:FAQ / 热点问句归一化等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:无外部业务模块。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则。
|
||||
用途:FAQ / 热点问句归一化、模糊相似度评分等纯文本工具,供 faq_cache 与 hot_faq_aggregator 共用。
|
||||
依赖:difflib(Python 标准库,无第三方依赖)。
|
||||
逻辑:保证离线聚合与在线命中使用同一 normalize 规则;模糊评分供 FAQ 兜底直答使用。
|
||||
"""
|
||||
import re
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
# 模糊兜底参与的最低归一化长度:过短问句(如「帮助」)误命中代价高,只走精确匹配。
|
||||
FUZZY_MIN_LENGTH = 4
|
||||
# 模糊阈值的安全钳制区间与默认值:下限防止管理员设得过低导致大面积误直答。
|
||||
FUZZY_THRESHOLD_MIN = 0.5
|
||||
FUZZY_THRESHOLD_MAX = 1.0
|
||||
FUZZY_THRESHOLD_DEFAULT = 0.8
|
||||
|
||||
|
||||
def normalize_faq_query(text: str) -> str:
|
||||
@@ -16,5 +24,38 @@ def normalize_faq_query(text: str) -> str:
|
||||
@returns 归一化后的字符串;空输入返回空串
|
||||
"""
|
||||
value = str(text or "").strip().lower()
|
||||
value = re.sub(r"[\s\u3000,。!?、;:""''()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
value = re.sub(r"[\s\u3000,。!?、;:“”‘’()()\[\]【】\-—·,.!?;:'\"]+", "", value)
|
||||
return value
|
||||
|
||||
|
||||
def clamp_fuzzy_threshold(value) -> float:
|
||||
"""
|
||||
将模糊匹配阈值钳制到安全区间 [0.5, 1.0]。
|
||||
核心逻辑:空值/非法值回退默认 0.8,越界值收敛到边界,保证在线匹配不会因配置异常失真。
|
||||
@param value - 数据库或请求体中的阈值原始值
|
||||
@returns 钳制后的浮点阈值
|
||||
"""
|
||||
try:
|
||||
threshold = float(value)
|
||||
except (TypeError, ValueError):
|
||||
return FUZZY_THRESHOLD_DEFAULT
|
||||
return min(FUZZY_THRESHOLD_MAX, max(FUZZY_THRESHOLD_MIN, threshold))
|
||||
|
||||
|
||||
def fuzzy_match_score(query: str, candidate: str) -> float:
|
||||
"""
|
||||
计算两段归一化问句的模糊相似度得分(0~1),供 FAQ 模糊兜底匹配使用。
|
||||
核心逻辑:取编辑距离类相似度(SequenceMatcher.ratio)与包含覆盖率的最大值——
|
||||
前者容忍换字/错字(能→可以),后者容忍加前后缀(我还能问什么 vs 还能问什么);
|
||||
真问题偶含候选短语时(如「怎么用你查MES服务器」vs「怎么用你」)覆盖率很低,不会误命中。
|
||||
@param query - 归一化后的用户问句
|
||||
@param candidate - 归一化后的候选问句(标题/标准问句/同义问法)
|
||||
@returns 0~1 之间的相似度得分
|
||||
"""
|
||||
if not query or not candidate:
|
||||
return 0.0
|
||||
score = SequenceMatcher(None, query, candidate).ratio()
|
||||
if query in candidate or candidate in query:
|
||||
coverage = min(len(query), len(candidate)) / max(len(query), len(candidate))
|
||||
score = max(score, coverage)
|
||||
return score
|
||||
Reference in new issue
Block a user