2024-05-31 09:53:04 +08:00
|
|
|
|
#
|
|
|
|
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
|
|
|
|
#
|
|
|
|
|
# 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.
|
|
|
|
|
#
|
2024-01-15 08:46:22 +08:00
|
|
|
|
|
2023-12-14 19:19:03 +08:00
|
|
|
|
import json
|
2024-03-29 10:48:29 +08:00
|
|
|
|
import math
|
2023-12-14 19:19:03 +08:00
|
|
|
|
import re
|
|
|
|
|
import logging
|
|
|
|
|
import copy
|
2024-03-20 16:56:16 +08:00
|
|
|
|
from elasticsearch_dsl import Q
|
|
|
|
|
|
2024-04-28 19:13:33 +08:00
|
|
|
|
from rag.nlp import rag_tokenizer, term_weight, synonym
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
class EsQueryer:
|
|
|
|
|
def __init__(self, es):
|
|
|
|
|
self.tw = term_weight.Dealer()
|
|
|
|
|
self.es = es
|
2024-05-07 11:43:33 +08:00
|
|
|
|
self.syn = synonym.Dealer()
|
2023-12-14 19:19:03 +08:00
|
|
|
|
self.flds = ["ask_tks^10", "ask_small_tks"]
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def subSpecialChar(line):
|
2024-08-22 10:02:04 +08:00
|
|
|
|
return re.sub(r"([:\{\}/\[\]\-\*\"\(\)\|\+~\^])", r"\\\1", line).strip()
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def isChinese(line):
|
|
|
|
|
arr = re.split(r"[ \t]+", line)
|
|
|
|
|
if len(arr) <= 3:
|
|
|
|
|
return True
|
|
|
|
|
e = 0
|
|
|
|
|
for t in arr:
|
|
|
|
|
if not re.match(r"[a-zA-Z]+$", t):
|
|
|
|
|
e += 1
|
2024-03-19 15:31:47 +08:00
|
|
|
|
return e * 1. / len(arr) >= 0.7
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def rmWWW(txt):
|
2024-03-20 16:56:16 +08:00
|
|
|
|
patts = [
|
2024-06-06 11:13:39 +08:00
|
|
|
|
(r"是*(什么样的|哪家|一下|那家|请问|啥样|咋样了|什么时候|何时|何地|何人|是否|是不是|多少|哪里|怎么|哪儿|怎么样|如何|哪些|是啥|啥是|啊|吗|呢|吧|咋|什么|有没有|呀)是*", ""),
|
2024-03-20 16:56:16 +08:00
|
|
|
|
(r"(^| )(what|who|how|which|where|why)('re|'s)? ", " "),
|
2024-05-20 12:23:51 +08:00
|
|
|
|
(r"(^| )('s|'re|is|are|were|was|do|does|did|don't|doesn't|didn't|has|have|be|there|you|me|your|my|mine|just|please|may|i|should|would|wouldn't|will|won't|done|go|for|with|so|the|a|an|by|i'm|it's|he's|she's|they|they're|you're|as|by|on|in|at|up|out|down) ", " ")
|
2024-03-20 16:56:16 +08:00
|
|
|
|
]
|
|
|
|
|
for r, p in patts:
|
|
|
|
|
txt = re.sub(r, p, txt, flags=re.IGNORECASE)
|
|
|
|
|
return txt
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
def question(self, txt, tbl="qa", min_match="60%"):
|
|
|
|
|
txt = re.sub(
|
2024-05-29 19:38:57 +08:00
|
|
|
|
r"[ :\r\n\t,,。??/`!!&\^%%]+",
|
2023-12-14 19:19:03 +08:00
|
|
|
|
" ",
|
2024-04-28 19:13:33 +08:00
|
|
|
|
rag_tokenizer.tradi2simp(
|
|
|
|
|
rag_tokenizer.strQ2B(
|
2023-12-14 19:19:03 +08:00
|
|
|
|
txt.lower()))).strip()
|
|
|
|
|
txt = EsQueryer.rmWWW(txt)
|
|
|
|
|
|
|
|
|
|
if not self.isChinese(txt):
|
2024-04-28 19:13:33 +08:00
|
|
|
|
tks = rag_tokenizer.tokenize(txt).split(" ")
|
2024-05-20 12:23:51 +08:00
|
|
|
|
tks_w = self.tw.weights(tks)
|
2024-06-06 11:13:39 +08:00
|
|
|
|
tks_w = [(re.sub(r"[ \\\"'^]", "", tk), w) for tk, w in tks_w]
|
|
|
|
|
tks_w = [(re.sub(r"^[a-z0-9]$", "", tk), w) for tk, w in tks_w if tk]
|
|
|
|
|
tks_w = [(re.sub(r"^[\+-]", "", tk), w) for tk, w in tks_w if tk]
|
2024-05-29 16:50:02 +08:00
|
|
|
|
q = ["{}^{:.4f}".format(tk, w) for tk, w in tks_w if tk]
|
2024-05-20 12:23:51 +08:00
|
|
|
|
for i in range(1, len(tks_w)):
|
|
|
|
|
q.append("\"%s %s\"^%.4f" % (tks_w[i - 1][0], tks_w[i][0], max(tks_w[i - 1][1], tks_w[i][1])*2))
|
2023-12-14 19:19:03 +08:00
|
|
|
|
if not q:
|
|
|
|
|
q.append(txt)
|
|
|
|
|
return Q("bool",
|
|
|
|
|
must=Q("query_string", fields=self.flds,
|
2024-03-20 16:56:16 +08:00
|
|
|
|
type="best_fields", query=" ".join(q),
|
2024-04-10 10:11:22 +08:00
|
|
|
|
boost=1)#, minimum_should_match=min_match)
|
2024-03-20 16:56:16 +08:00
|
|
|
|
), tks
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
2024-04-28 19:13:33 +08:00
|
|
|
|
def need_fine_grained_tokenize(tk):
|
2024-09-03 13:37:32 +08:00
|
|
|
|
if len(tk) < 3:
|
2023-12-14 19:19:03 +08:00
|
|
|
|
return False
|
|
|
|
|
if re.match(r"[0-9a-z\.\+#_\*-]+$", tk):
|
|
|
|
|
return False
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
|
|
qs, keywords = [], []
|
2024-04-03 11:00:50 +08:00
|
|
|
|
for tt in self.tw.split(txt)[:256]: # .split(" "):
|
2023-12-14 19:19:03 +08:00
|
|
|
|
if not tt:
|
|
|
|
|
continue
|
|
|
|
|
twts = self.tw.weights([tt])
|
|
|
|
|
syns = self.syn.lookup(tt)
|
|
|
|
|
logging.info(json.dumps(twts, ensure_ascii=False))
|
|
|
|
|
tms = []
|
|
|
|
|
for tk, w in sorted(twts, key=lambda x: x[1] * -1):
|
2024-04-28 19:13:33 +08:00
|
|
|
|
sm = rag_tokenizer.fine_grained_tokenize(tk).split(" ") if need_fine_grained_tokenize(tk) else []
|
2023-12-14 19:19:03 +08:00
|
|
|
|
sm = [
|
|
|
|
|
re.sub(
|
|
|
|
|
r"[ ,\./;'\[\]\\`~!@#$%\^&\*\(\)=\+_<>\?:\"\{\}\|,。;‘’【】、!¥……()——《》?:“”-]+",
|
|
|
|
|
"",
|
|
|
|
|
m) for m in sm]
|
|
|
|
|
sm = [EsQueryer.subSpecialChar(m) for m in sm if len(m) > 1]
|
|
|
|
|
sm = [m for m in sm if len(m) > 1]
|
|
|
|
|
|
|
|
|
|
keywords.append(re.sub(r"[ \\\"']+", "", tk))
|
2024-09-03 14:30:07 +08:00
|
|
|
|
keywords.extend(sm)
|
2024-06-18 09:50:59 +08:00
|
|
|
|
if len(keywords) >= 12: break
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
tk_syns = self.syn.lookup(tk)
|
|
|
|
|
tk = EsQueryer.subSpecialChar(tk)
|
|
|
|
|
if tk.find(" ") > 0:
|
|
|
|
|
tk = "\"%s\"" % tk
|
|
|
|
|
if tk_syns:
|
|
|
|
|
tk = f"({tk} %s)" % " ".join(tk_syns)
|
|
|
|
|
if sm:
|
|
|
|
|
tk = f"{tk} OR \"%s\" OR (\"%s\"~2)^0.5" % (
|
|
|
|
|
" ".join(sm), " ".join(sm))
|
2024-06-06 11:13:39 +08:00
|
|
|
|
if tk.strip():
|
|
|
|
|
tms.append((tk, w))
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
tms = " ".join([f"({t})^{w}" for t, w in tms])
|
|
|
|
|
|
|
|
|
|
if len(twts) > 1:
|
|
|
|
|
tms += f" (\"%s\"~4)^1.5" % (" ".join([t for t, _ in twts]))
|
|
|
|
|
if re.match(r"[0-9a-z ]+$", tt):
|
2024-04-28 19:13:33 +08:00
|
|
|
|
tms = f"(\"{tt}\" OR \"%s\")" % rag_tokenizer.tokenize(tt)
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
syns = " OR ".join(
|
2024-04-28 19:13:33 +08:00
|
|
|
|
["\"%s\"^0.7" % EsQueryer.subSpecialChar(rag_tokenizer.tokenize(s)) for s in syns])
|
2023-12-14 19:19:03 +08:00
|
|
|
|
if syns:
|
|
|
|
|
tms = f"({tms})^5 OR ({syns})^0.7"
|
|
|
|
|
|
|
|
|
|
qs.append(tms)
|
|
|
|
|
|
|
|
|
|
flds = copy.deepcopy(self.flds)
|
|
|
|
|
mst = []
|
|
|
|
|
if qs:
|
|
|
|
|
mst.append(
|
|
|
|
|
Q("query_string", fields=flds, type="best_fields",
|
|
|
|
|
query=" OR ".join([f"({t})" for t in qs if t]), boost=1, minimum_should_match=min_match)
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return Q("bool",
|
|
|
|
|
must=mst,
|
|
|
|
|
), keywords
|
|
|
|
|
|
|
|
|
|
def hybrid_similarity(self, avec, bvecs, atks, btkss, tkweight=0.3,
|
|
|
|
|
vtweight=0.7):
|
|
|
|
|
from sklearn.metrics.pairwise import cosine_similarity as CosineSimilarity
|
|
|
|
|
import numpy as np
|
|
|
|
|
sims = CosineSimilarity([avec], bvecs)
|
2024-05-29 16:50:02 +08:00
|
|
|
|
tksim = self.token_similarity(atks, btkss)
|
|
|
|
|
return np.array(sims[0]) * vtweight + \
|
|
|
|
|
np.array(tksim) * tkweight, tksim, sims[0]
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
2024-05-29 16:50:02 +08:00
|
|
|
|
def token_similarity(self, atks, btkss):
|
2023-12-14 19:19:03 +08:00
|
|
|
|
def toDict(tks):
|
|
|
|
|
d = {}
|
2024-03-26 15:11:07 +08:00
|
|
|
|
if isinstance(tks, str):
|
2023-12-14 19:19:03 +08:00
|
|
|
|
tks = tks.split(" ")
|
|
|
|
|
for t, c in self.tw.weights(tks):
|
|
|
|
|
if t not in d:
|
|
|
|
|
d[t] = 0
|
|
|
|
|
d[t] += c
|
|
|
|
|
return d
|
|
|
|
|
|
|
|
|
|
atks = toDict(atks)
|
|
|
|
|
btkss = [toDict(tks) for tks in btkss]
|
2024-05-29 16:50:02 +08:00
|
|
|
|
return [self.similarity(atks, btks) for btks in btkss]
|
2023-12-14 19:19:03 +08:00
|
|
|
|
|
|
|
|
|
def similarity(self, qtwt, dtwt):
|
|
|
|
|
if isinstance(dtwt, type("")):
|
|
|
|
|
dtwt = {t: w for t, w in self.tw.weights(self.tw.split(dtwt))}
|
|
|
|
|
if isinstance(qtwt, type("")):
|
|
|
|
|
qtwt = {t: w for t, w in self.tw.weights(self.tw.split(qtwt))}
|
|
|
|
|
s = 1e-9
|
|
|
|
|
for k, v in qtwt.items():
|
|
|
|
|
if k in dtwt:
|
2024-03-27 11:33:46 +08:00
|
|
|
|
s += v # * dtwt[k]
|
2023-12-14 19:19:03 +08:00
|
|
|
|
q = 1e-9
|
|
|
|
|
for k, v in qtwt.items():
|
2024-03-27 11:33:46 +08:00
|
|
|
|
q += v # * v
|
2024-03-20 16:56:16 +08:00
|
|
|
|
#d = 1e-9
|
2024-03-27 11:33:46 +08:00
|
|
|
|
# for k, v in dtwt.items():
|
2024-03-20 16:56:16 +08:00
|
|
|
|
# d += v * v
|
2024-03-29 10:48:29 +08:00
|
|
|
|
return s / q / max(1, math.sqrt(math.log10(max(len(qtwt.keys()), len(dtwt.keys())))))# math.sqrt(q) / math.sqrt(d)
|