您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import re
  4. import logging
  5. import copy
  6. from elasticsearch_dsl import Q
  7. from rag.nlp import huqie, term_weight, synonym
  8. class EsQueryer:
  9. def __init__(self, es):
  10. self.tw = term_weight.Dealer()
  11. self.es = es
  12. self.syn = synonym.Dealer(None)
  13. self.flds = ["ask_tks^10", "ask_small_tks"]
  14. @staticmethod
  15. def subSpecialChar(line):
  16. return re.sub(r"([:\{\}/\[\]\-\*\"\(\)\|~\^])", r"\\\1", line).strip()
  17. @staticmethod
  18. def isChinese(line):
  19. arr = re.split(r"[ \t]+", line)
  20. if len(arr) <= 3:
  21. return True
  22. e = 0
  23. for t in arr:
  24. if not re.match(r"[a-zA-Z]+$", t):
  25. e += 1
  26. return e * 1. / len(arr) >= 0.7
  27. @staticmethod
  28. def rmWWW(txt):
  29. patts = [
  30. (r"是*(什么样的|哪家|那家|啥样|咋样了|什么时候|何时|何地|何人|是否|是不是|多少|哪里|怎么|哪儿|怎么样|如何|哪些|是啥|啥是|啊|吗|呢|吧|咋|什么|有没有|呀)是*", ""),
  31. (r"(^| )(what|who|how|which|where|why)('re|'s)? ", " "),
  32. (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)", " ")
  33. ]
  34. for r, p in patts:
  35. txt = re.sub(r, p, txt, flags=re.IGNORECASE)
  36. return txt
  37. def question(self, txt, tbl="qa", min_match="60%"):
  38. txt = re.sub(
  39. r"[ \r\n\t,,。??/`!!&]+",
  40. " ",
  41. huqie.tradi2simp(
  42. huqie.strQ2B(
  43. txt.lower()))).strip()
  44. txt = EsQueryer.rmWWW(txt)
  45. if not self.isChinese(txt):
  46. tks = huqie.qie(txt).split(" ")
  47. q = tks
  48. for i in range(1, len(tks)):
  49. q.append("\"%s %s\"^2" % (tks[i - 1], tks[i]))
  50. if not q:
  51. q.append(txt)
  52. return Q("bool",
  53. must=Q("query_string", fields=self.flds,
  54. type="best_fields", query=" ".join(q),
  55. boost=1, minimum_should_match=min_match)
  56. ), tks
  57. def needQieqie(tk):
  58. if len(tk) < 4:
  59. return False
  60. if re.match(r"[0-9a-z\.\+#_\*-]+$", tk):
  61. return False
  62. return True
  63. qs, keywords = [], []
  64. for tt in self.tw.split(txt): # .split(" "):
  65. if not tt:
  66. continue
  67. twts = self.tw.weights([tt])
  68. syns = self.syn.lookup(tt)
  69. logging.info(json.dumps(twts, ensure_ascii=False))
  70. tms = []
  71. for tk, w in sorted(twts, key=lambda x: x[1] * -1):
  72. sm = huqie.qieqie(tk).split(" ") if needQieqie(tk) else []
  73. sm = [
  74. re.sub(
  75. r"[ ,\./;'\[\]\\`~!@#$%\^&\*\(\)=\+_<>\?:\"\{\}\|,。;‘’【】、!¥……()——《》?:“”-]+",
  76. "",
  77. m) for m in sm]
  78. sm = [EsQueryer.subSpecialChar(m) for m in sm if len(m) > 1]
  79. sm = [m for m in sm if len(m) > 1]
  80. if len(sm) < 2:
  81. sm = []
  82. keywords.append(re.sub(r"[ \\\"']+", "", tk))
  83. tk_syns = self.syn.lookup(tk)
  84. tk = EsQueryer.subSpecialChar(tk)
  85. if tk.find(" ") > 0:
  86. tk = "\"%s\"" % tk
  87. if tk_syns:
  88. tk = f"({tk} %s)" % " ".join(tk_syns)
  89. if sm:
  90. tk = f"{tk} OR \"%s\" OR (\"%s\"~2)^0.5" % (
  91. " ".join(sm), " ".join(sm))
  92. tms.append((tk, w))
  93. tms = " ".join([f"({t})^{w}" for t, w in tms])
  94. if len(twts) > 1:
  95. tms += f" (\"%s\"~4)^1.5" % (" ".join([t for t, _ in twts]))
  96. if re.match(r"[0-9a-z ]+$", tt):
  97. tms = f"(\"{tt}\" OR \"%s\")" % huqie.qie(tt)
  98. syns = " OR ".join(
  99. ["\"%s\"^0.7" % EsQueryer.subSpecialChar(huqie.qie(s)) for s in syns])
  100. if syns:
  101. tms = f"({tms})^5 OR ({syns})^0.7"
  102. qs.append(tms)
  103. flds = copy.deepcopy(self.flds)
  104. mst = []
  105. if qs:
  106. mst.append(
  107. Q("query_string", fields=flds, type="best_fields",
  108. query=" OR ".join([f"({t})" for t in qs if t]), boost=1, minimum_should_match=min_match)
  109. )
  110. return Q("bool",
  111. must=mst,
  112. ), keywords
  113. def hybrid_similarity(self, avec, bvecs, atks, btkss, tkweight=0.3,
  114. vtweight=0.7):
  115. from sklearn.metrics.pairwise import cosine_similarity as CosineSimilarity
  116. import numpy as np
  117. sims = CosineSimilarity([avec], bvecs)
  118. def toDict(tks):
  119. d = {}
  120. if isinstance(tks, type("")):
  121. tks = tks.split(" ")
  122. for t, c in self.tw.weights(tks):
  123. if t not in d:
  124. d[t] = 0
  125. d[t] += c
  126. return d
  127. atks = toDict(atks)
  128. btkss = [toDict(tks) for tks in btkss]
  129. tksim = [self.similarity(atks, btks) for btks in btkss]
  130. return np.array(sims[0]) * vtweight + np.array(tksim) * tkweight, tksim, sims[0]
  131. def similarity(self, qtwt, dtwt):
  132. if isinstance(dtwt, type("")):
  133. dtwt = {t: w for t, w in self.tw.weights(self.tw.split(dtwt))}
  134. if isinstance(qtwt, type("")):
  135. qtwt = {t: w for t, w in self.tw.weights(self.tw.split(qtwt))}
  136. s = 1e-9
  137. for k, v in qtwt.items():
  138. if k in dtwt:
  139. s += v# * dtwt[k]
  140. q = 1e-9
  141. for k, v in qtwt.items():
  142. q += v #* v
  143. #d = 1e-9
  144. #for k, v in dtwt.items():
  145. # d += v * v
  146. return s / q #math.sqrt(q) / math.sqrt(d)