選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

query.py 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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) ", " ")
  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. ), tks
  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. twts = self.tw.weights([tt])
  87. syns = self.syn.lookup(tt)
  88. logging.info(json.dumps(twts, ensure_ascii=False))
  89. tms = []
  90. for tk, w in sorted(twts, key=lambda x: x[1] * -1):
  91. sm = rag_tokenizer.fine_grained_tokenize(tk).split(" ") if need_fine_grained_tokenize(tk) else []
  92. sm = [
  93. re.sub(
  94. r"[ ,\./;'\[\]\\`~!@#$%\^&\*\(\)=\+_<>\?:\"\{\}\|,。;‘’【】、!¥……()——《》?:“”-]+",
  95. "",
  96. m) for m in sm]
  97. sm = [EsQueryer.subSpecialChar(m) for m in sm if len(m) > 1]
  98. sm = [m for m in sm if len(m) > 1]
  99. if len(sm) < 2:
  100. sm = []
  101. keywords.append(re.sub(r"[ \\\"']+", "", tk))
  102. if len(keywords) >= 12: break
  103. tk_syns = self.syn.lookup(tk)
  104. tk = EsQueryer.subSpecialChar(tk)
  105. if tk.find(" ") > 0:
  106. tk = "\"%s\"" % tk
  107. if tk_syns:
  108. tk = f"({tk} %s)" % " ".join(tk_syns)
  109. if sm:
  110. tk = f"{tk} OR \"%s\" OR (\"%s\"~2)^0.5" % (
  111. " ".join(sm), " ".join(sm))
  112. if tk.strip():
  113. tms.append((tk, w))
  114. tms = " ".join([f"({t})^{w}" for t, w in tms])
  115. if len(twts) > 1:
  116. tms += f" (\"%s\"~4)^1.5" % (" ".join([t for t, _ in twts]))
  117. if re.match(r"[0-9a-z ]+$", tt):
  118. tms = f"(\"{tt}\" OR \"%s\")" % rag_tokenizer.tokenize(tt)
  119. syns = " OR ".join(
  120. ["\"%s\"^0.7" % EsQueryer.subSpecialChar(rag_tokenizer.tokenize(s)) for s in syns])
  121. if syns:
  122. tms = f"({tms})^5 OR ({syns})^0.7"
  123. qs.append(tms)
  124. flds = copy.deepcopy(self.flds)
  125. mst = []
  126. if qs:
  127. mst.append(
  128. Q("query_string", fields=flds, type="best_fields",
  129. query=" OR ".join([f"({t})" for t in qs if t]), boost=1, minimum_should_match=min_match)
  130. )
  131. return Q("bool",
  132. must=mst,
  133. ), keywords
  134. def hybrid_similarity(self, avec, bvecs, atks, btkss, tkweight=0.3,
  135. vtweight=0.7):
  136. from sklearn.metrics.pairwise import cosine_similarity as CosineSimilarity
  137. import numpy as np
  138. sims = CosineSimilarity([avec], bvecs)
  139. tksim = self.token_similarity(atks, btkss)
  140. return np.array(sims[0]) * vtweight + \
  141. np.array(tksim) * tkweight, tksim, sims[0]
  142. def token_similarity(self, atks, btkss):
  143. def toDict(tks):
  144. d = {}
  145. if isinstance(tks, str):
  146. tks = tks.split(" ")
  147. for t, c in self.tw.weights(tks):
  148. if t not in d:
  149. d[t] = 0
  150. d[t] += c
  151. return d
  152. atks = toDict(atks)
  153. btkss = [toDict(tks) for tks in btkss]
  154. return [self.similarity(atks, btks) for btks in btkss]
  155. def similarity(self, qtwt, dtwt):
  156. if isinstance(dtwt, type("")):
  157. dtwt = {t: w for t, w in self.tw.weights(self.tw.split(dtwt))}
  158. if isinstance(qtwt, type("")):
  159. qtwt = {t: w for t, w in self.tw.weights(self.tw.split(qtwt))}
  160. s = 1e-9
  161. for k, v in qtwt.items():
  162. if k in dtwt:
  163. s += v # * dtwt[k]
  164. q = 1e-9
  165. for k, v in qtwt.items():
  166. q += v # * v
  167. #d = 1e-9
  168. # for k, v in dtwt.items():
  169. # d += v * v
  170. return s / q / max(1, math.sqrt(math.log10(max(len(qtwt.keys()), len(dtwt.keys())))))# math.sqrt(q) / math.sqrt(d)