Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

query.py 9.8KB

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