Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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