You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import json
  17. import math
  18. import re
  19. import logging
  20. import copy
  21. from elasticsearch_dsl import Q
  22. from rag.nlp import rag_tokenizer, term_weight, synonym
  23. class EsQueryer:
  24. def __init__(self, es):
  25. self.tw = term_weight.Dealer()
  26. self.es = es
  27. self.syn = synonym.Dealer()
  28. self.flds = ["ask_tks^10", "ask_small_tks"]
  29. @staticmethod
  30. def subSpecialChar(line):
  31. return re.sub(r"([:\{\}/\[\]\-\*\"\(\)\|\+~\^])", r"\\\1", line).strip()
  32. @staticmethod
  33. def isChinese(line):
  34. arr = re.split(r"[ \t]+", line)
  35. if len(arr) <= 3:
  36. return True
  37. e = 0
  38. for t in arr:
  39. if not re.match(r"[a-zA-Z]+$", t):
  40. e += 1
  41. return e * 1. / len(arr) >= 0.7
  42. @staticmethod
  43. def rmWWW(txt):
  44. patts = [
  45. (r"是*(什么样的|哪家|一下|那家|请问|啥样|咋样了|什么时候|何时|何地|何人|是否|是不是|多少|哪里|怎么|哪儿|怎么样|如何|哪些|是啥|啥是|啊|吗|呢|吧|咋|什么|有没有|呀)是*", ""),
  46. (r"(^| )(what|who|how|which|where|why)('re|'s)? ", " "),
  47. (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|of) ", " ")
  48. ]
  49. for r, p in patts:
  50. txt = re.sub(r, p, txt, flags=re.IGNORECASE)
  51. return txt
  52. def question(self, txt, tbl="qa", min_match="60%"):
  53. txt = re.sub(
  54. r"[ :\r\n\t,,。??/`!!&\^%%]+",
  55. " ",
  56. rag_tokenizer.tradi2simp(
  57. rag_tokenizer.strQ2B(
  58. txt.lower()))).strip()
  59. txt = EsQueryer.rmWWW(txt)
  60. if not self.isChinese(txt):
  61. tks = rag_tokenizer.tokenize(txt).split(" ")
  62. tks_w = self.tw.weights(tks)
  63. tks_w = [(re.sub(r"[ \\\"'^]", "", tk), w) for tk, w in tks_w]
  64. tks_w = [(re.sub(r"^[a-z0-9]$", "", tk), w) for tk, w in tks_w if tk]
  65. tks_w = [(re.sub(r"^[\+-]", "", tk), w) for tk, w in tks_w if tk]
  66. q = ["{}^{:.4f}".format(tk, w) for tk, w in tks_w if tk]
  67. for i in range(1, len(tks_w)):
  68. 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))
  69. if not q:
  70. q.append(txt)
  71. return Q("bool",
  72. must=Q("query_string", fields=self.flds,
  73. type="best_fields", query=" ".join(q),
  74. boost=1)#, minimum_should_match=min_match)
  75. ), list(set([t for t in txt.split(" ") if t]))
  76. def need_fine_grained_tokenize(tk):
  77. if len(tk) < 3:
  78. return False
  79. if re.match(r"[0-9a-z\.\+#_\*-]+$", tk):
  80. return False
  81. return True
  82. qs, keywords = [], []
  83. for tt in self.tw.split(txt)[:256]: # .split(" "):
  84. if not tt:
  85. continue
  86. keywords.append(tt)
  87. twts = self.tw.weights([tt])
  88. syns = self.syn.lookup(tt)
  89. if syns: keywords.extend(syns)
  90. logging.info(json.dumps(twts, ensure_ascii=False))
  91. tms = []
  92. for tk, w in sorted(twts, key=lambda x: x[1] * -1):
  93. sm = rag_tokenizer.fine_grained_tokenize(tk).split(" ") if need_fine_grained_tokenize(tk) else []
  94. sm = [
  95. re.sub(
  96. r"[ ,\./;'\[\]\\`~!@#$%\^&\*\(\)=\+_<>\?:\"\{\}\|,。;‘’【】、!¥……()——《》?:“”-]+",
  97. "",
  98. m) for m in sm]
  99. sm = [EsQueryer.subSpecialChar(m) for m in sm if len(m) > 1]
  100. sm = [m for m in sm if len(m) > 1]
  101. keywords.append(re.sub(r"[ \\\"']+", "", tk))
  102. keywords.extend(sm)
  103. if len(keywords) >= 12: break
  104. tk_syns = self.syn.lookup(tk)
  105. tk = EsQueryer.subSpecialChar(tk)
  106. if tk.find(" ") > 0:
  107. tk = "\"%s\"" % tk
  108. if tk_syns:
  109. tk = f"({tk} %s)" % " ".join(tk_syns)
  110. if sm:
  111. tk = f"{tk} OR \"%s\" OR (\"%s\"~2)^0.5" % (
  112. " ".join(sm), " ".join(sm))
  113. if tk.strip():
  114. tms.append((tk, w))
  115. tms = " ".join([f"({t})^{w}" for t, w in tms])
  116. if len(twts) > 1:
  117. tms += f" (\"%s\"~4)^1.5" % (" ".join([t for t, _ in twts]))
  118. if re.match(r"[0-9a-z ]+$", tt):
  119. tms = f"(\"{tt}\" OR \"%s\")" % rag_tokenizer.tokenize(tt)
  120. syns = " OR ".join(
  121. ["\"%s\"^0.7" % EsQueryer.subSpecialChar(rag_tokenizer.tokenize(s)) for s in syns])
  122. if syns:
  123. tms = f"({tms})^5 OR ({syns})^0.7"
  124. qs.append(tms)
  125. flds = copy.deepcopy(self.flds)
  126. mst = []
  127. if qs:
  128. mst.append(
  129. Q("query_string", fields=flds, type="best_fields",
  130. query=" OR ".join([f"({t})" for t in qs if t]), boost=1, minimum_should_match=min_match)
  131. )
  132. return Q("bool",
  133. must=mst,
  134. ), list(set(keywords))
  135. def hybrid_similarity(self, avec, bvecs, atks, btkss, tkweight=0.3,
  136. vtweight=0.7):
  137. from sklearn.metrics.pairwise import cosine_similarity as CosineSimilarity
  138. import numpy as np
  139. sims = CosineSimilarity([avec], bvecs)
  140. tksim = self.token_similarity(atks, btkss)
  141. return np.array(sims[0]) * vtweight + \
  142. np.array(tksim) * tkweight, tksim, sims[0]
  143. def token_similarity(self, atks, btkss):
  144. def toDict(tks):
  145. d = {}
  146. if isinstance(tks, str):
  147. tks = tks.split(" ")
  148. for t, c in self.tw.weights(tks):
  149. if t not in d:
  150. d[t] = 0
  151. d[t] += c
  152. return d
  153. atks = toDict(atks)
  154. btkss = [toDict(tks) for tks in btkss]
  155. return [self.similarity(atks, btks) for btks in btkss]
  156. def similarity(self, qtwt, dtwt):
  157. if isinstance(dtwt, type("")):
  158. dtwt = {t: w for t, w in self.tw.weights(self.tw.split(dtwt))}
  159. if isinstance(qtwt, type("")):
  160. qtwt = {t: w for t, w in self.tw.weights(self.tw.split(qtwt))}
  161. s = 1e-9
  162. for k, v in qtwt.items():
  163. if k in dtwt:
  164. s += v # * dtwt[k]
  165. q = 1e-9
  166. for k, v in qtwt.items():
  167. q += v
  168. return s / q