Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

query.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 logging
  17. import json
  18. import math
  19. import re
  20. from collections import defaultdict
  21. from rag.utils.doc_store_conn import MatchTextExpr
  22. from rag.nlp import rag_tokenizer, term_weight, synonym
  23. class FulltextQueryer:
  24. def __init__(self):
  25. self.tw = term_weight.Dealer()
  26. self.syn = synonym.Dealer()
  27. self.query_fields = [
  28. "title_tks^10",
  29. "title_sm_tks^5",
  30. "important_kwd^30",
  31. "important_tks^20",
  32. "question_tks^20",
  33. "content_ltks^2",
  34. "content_sm_ltks",
  35. ]
  36. @staticmethod
  37. def subSpecialChar(line):
  38. return re.sub(r"([:\{\}/\[\]\-\*\"\(\)\|\+~\^])", r"\\\1", line).strip()
  39. @staticmethod
  40. def isChinese(line):
  41. arr = re.split(r"[ \t]+", line)
  42. if len(arr) <= 3:
  43. return True
  44. e = 0
  45. for t in arr:
  46. if not re.match(r"[a-zA-Z]+$", t):
  47. e += 1
  48. return e * 1.0 / len(arr) >= 0.7
  49. @staticmethod
  50. def rmWWW(txt):
  51. patts = [
  52. (
  53. r"是*(什么样的|哪家|一下|那家|请问|啥样|咋样了|什么时候|何时|何地|何人|是否|是不是|多少|哪里|怎么|哪儿|怎么样|如何|哪些|是啥|啥是|啊|吗|呢|吧|咋|什么|有没有|呀|谁|哪位|哪个)是*",
  54. "",
  55. ),
  56. (r"(^| )(what|who|how|which|where|why)('re|'s)? ", " "),
  57. (
  58. 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|to|or|and|if) ",
  59. " ")
  60. ]
  61. otxt = txt
  62. for r, p in patts:
  63. txt = re.sub(r, p, txt, flags=re.IGNORECASE)
  64. if not txt:
  65. txt = otxt
  66. return txt
  67. def question(self, txt, tbl="qa", min_match: float = 0.6):
  68. txt = re.sub(
  69. r"[ :|\r\n\t,,。??/`!!&^%%()\[\]{}<>]+",
  70. " ",
  71. rag_tokenizer.tradi2simp(rag_tokenizer.strQ2B(txt.lower())),
  72. ).strip()
  73. txt = FulltextQueryer.rmWWW(txt)
  74. if not self.isChinese(txt):
  75. txt = FulltextQueryer.rmWWW(txt)
  76. tks = rag_tokenizer.tokenize(txt).split()
  77. keywords = [t for t in tks if t]
  78. tks_w = self.tw.weights(tks, preprocess=False)
  79. tks_w = [(re.sub(r"[ \\\"'^]", "", tk), w) for tk, w in tks_w]
  80. tks_w = [(re.sub(r"^[a-z0-9]$", "", tk), w) for tk, w in tks_w if tk]
  81. tks_w = [(re.sub(r"^[\+-]", "", tk), w) for tk, w in tks_w if tk]
  82. tks_w = [(tk.strip(), w) for tk, w in tks_w if tk.strip()]
  83. syns = []
  84. for tk, w in tks_w[:256]:
  85. syn = self.syn.lookup(tk)
  86. syn = rag_tokenizer.tokenize(" ".join(syn)).split()
  87. keywords.extend(syn)
  88. syn = ["\"{}\"^{:.4f}".format(s, w / 4.) for s in syn if s.strip()]
  89. syns.append(" ".join(syn))
  90. q = ["({}^{:.4f}".format(tk, w) + " {})".format(syn) for (tk, w), syn in zip(tks_w, syns) if
  91. tk and not re.match(r"[.^+\(\)-]", tk)]
  92. for i in range(1, len(tks_w)):
  93. left, right = tks_w[i - 1][0].strip(), tks_w[i][0].strip()
  94. if not left or not right:
  95. continue
  96. q.append(
  97. '"%s %s"^%.4f'
  98. % (
  99. tks_w[i - 1][0],
  100. tks_w[i][0],
  101. max(tks_w[i - 1][1], tks_w[i][1]) * 2,
  102. )
  103. )
  104. if not q:
  105. q.append(txt)
  106. query = " ".join(q)
  107. return MatchTextExpr(
  108. self.query_fields, query, 100
  109. ), keywords
  110. def need_fine_grained_tokenize(tk):
  111. if len(tk) < 3:
  112. return False
  113. if re.match(r"[0-9a-z\.\+#_\*-]+$", tk):
  114. return False
  115. return True
  116. txt = FulltextQueryer.rmWWW(txt)
  117. qs, keywords = [], []
  118. for tt in self.tw.split(txt)[:256]: # .split():
  119. if not tt:
  120. continue
  121. keywords.append(tt)
  122. twts = self.tw.weights([tt])
  123. syns = self.syn.lookup(tt)
  124. if syns and len(keywords) < 32:
  125. keywords.extend(syns)
  126. logging.debug(json.dumps(twts, ensure_ascii=False))
  127. tms = []
  128. for tk, w in sorted(twts, key=lambda x: x[1] * -1):
  129. sm = (
  130. rag_tokenizer.fine_grained_tokenize(tk).split()
  131. if need_fine_grained_tokenize(tk)
  132. else []
  133. )
  134. sm = [
  135. re.sub(
  136. r"[ ,\./;'\[\]\\`~!@#$%\^&\*\(\)=\+_<>\?:\"\{\}\|,。;‘’【】、!¥……()——《》?:“”-]+",
  137. "",
  138. m,
  139. )
  140. for m in sm
  141. ]
  142. sm = [FulltextQueryer.subSpecialChar(m) for m in sm if len(m) > 1]
  143. sm = [m for m in sm if len(m) > 1]
  144. if len(keywords) < 32:
  145. keywords.append(re.sub(r"[ \\\"']+", "", tk))
  146. keywords.extend(sm)
  147. tk_syns = self.syn.lookup(tk)
  148. tk_syns = [FulltextQueryer.subSpecialChar(s) for s in tk_syns]
  149. if len(keywords) < 32:
  150. keywords.extend([s for s in tk_syns if s])
  151. tk_syns = [rag_tokenizer.fine_grained_tokenize(s) for s in tk_syns if s]
  152. tk_syns = [f"\"{s}\"" if s.find(" ") > 0 else s for s in tk_syns]
  153. if len(keywords) >= 32:
  154. break
  155. tk = FulltextQueryer.subSpecialChar(tk)
  156. if tk.find(" ") > 0:
  157. tk = '"%s"' % tk
  158. if tk_syns:
  159. tk = f"({tk} OR (%s)^0.2)" % " ".join(tk_syns)
  160. if sm:
  161. tk = f'{tk} OR "%s" OR ("%s"~2)^0.5' % (" ".join(sm), " ".join(sm))
  162. if tk.strip():
  163. tms.append((tk, w))
  164. tms = " ".join([f"({t})^{w}" for t, w in tms])
  165. if len(twts) > 1:
  166. tms += ' ("%s"~2)^1.5' % rag_tokenizer.tokenize(tt)
  167. syns = " OR ".join(
  168. [
  169. '"%s"'
  170. % rag_tokenizer.tokenize(FulltextQueryer.subSpecialChar(s))
  171. for s in syns
  172. ]
  173. )
  174. if syns and tms:
  175. tms = f"({tms})^5 OR ({syns})^0.7"
  176. qs.append(tms)
  177. if qs:
  178. query = " OR ".join([f"({t})" for t in qs if t])
  179. return MatchTextExpr(
  180. self.query_fields, query, 100, {"minimum_should_match": min_match}
  181. ), keywords
  182. return None, keywords
  183. def hybrid_similarity(self, avec, bvecs, atks, btkss, tkweight=0.3, vtweight=0.7):
  184. from sklearn.metrics.pairwise import cosine_similarity as CosineSimilarity
  185. import numpy as np
  186. sims = CosineSimilarity([avec], bvecs)
  187. tksim = self.token_similarity(atks, btkss)
  188. if np.sum(sims[0]) == 0:
  189. return np.array(tksim), tksim, sims[0]
  190. return np.array(sims[0]) * vtweight + np.array(tksim) * tkweight, tksim, sims[0]
  191. def token_similarity(self, atks, btkss):
  192. def toDict(tks):
  193. if isinstance(tks, str):
  194. tks = tks.split()
  195. d = defaultdict(int)
  196. wts = self.tw.weights(tks, preprocess=False)
  197. for i, (t, c) in enumerate(wts):
  198. d[t] += c
  199. return d
  200. atks = toDict(atks)
  201. btkss = [toDict(tks) for tks in btkss]
  202. return [self.similarity(atks, btks) for btks in btkss]
  203. def similarity(self, qtwt, dtwt):
  204. if isinstance(dtwt, type("")):
  205. dtwt = {t: w for t, w in self.tw.weights(self.tw.split(dtwt), preprocess=False)}
  206. if isinstance(qtwt, type("")):
  207. qtwt = {t: w for t, w in self.tw.weights(self.tw.split(qtwt), preprocess=False)}
  208. s = 1e-9
  209. for k, v in qtwt.items():
  210. if k in dtwt:
  211. s += v * dtwt[k]
  212. q = 1e-9
  213. for k, v in qtwt.items():
  214. q += v * v
  215. return math.sqrt(3. * (s / q / math.log10( len(dtwt.keys()) + 512 )))
  216. def paragraph(self, content_tks: str, keywords: list = [], keywords_topn=30):
  217. if isinstance(content_tks, str):
  218. content_tks = [c.strip() for c in content_tks.strip() if c.strip()]
  219. tks_w = self.tw.weights(content_tks, preprocess=False)
  220. keywords = [f'"{k.strip()}"' for k in keywords]
  221. for tk, w in sorted(tks_w, key=lambda x: x[1] * -1)[:keywords_topn]:
  222. tk_syns = self.syn.lookup(tk)
  223. tk_syns = [FulltextQueryer.subSpecialChar(s) for s in tk_syns]
  224. tk_syns = [rag_tokenizer.fine_grained_tokenize(s) for s in tk_syns if s]
  225. tk_syns = [f"\"{s}\"" if s.find(" ") > 0 else s for s in tk_syns]
  226. tk = FulltextQueryer.subSpecialChar(tk)
  227. if tk.find(" ") > 0:
  228. tk = '"%s"' % tk
  229. if tk_syns:
  230. tk = f"({tk} OR (%s)^0.2)" % " ".join(tk_syns)
  231. if tk:
  232. keywords.append(f"{tk}^{w}")
  233. return MatchTextExpr(self.query_fields, " ".join(keywords), 100,
  234. {"minimum_should_match": min(3, len(keywords) / 10)})