You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. # -*- coding: utf-8 -*-
  2. import json
  3. import re
  4. from elasticsearch_dsl import Q, Search, A
  5. from typing import List, Optional, Dict, Union
  6. from dataclasses import dataclass
  7. from rag.settings import es_logger
  8. from rag.utils import rmSpace
  9. from rag.nlp import huqie, query
  10. import numpy as np
  11. def index_name(uid): return f"ragflow_{uid}"
  12. class Dealer:
  13. def __init__(self, es):
  14. self.qryr = query.EsQueryer(es)
  15. self.qryr.flds = [
  16. "title_tks^10",
  17. "title_sm_tks^5",
  18. "important_kwd^30",
  19. "important_tks^20",
  20. "content_ltks^2",
  21. "content_sm_ltks"]
  22. self.es = es
  23. @dataclass
  24. class SearchResult:
  25. total: int
  26. ids: List[str]
  27. query_vector: List[float] = None
  28. field: Optional[Dict] = None
  29. highlight: Optional[Dict] = None
  30. aggregation: Union[List, Dict, None] = None
  31. keywords: Optional[List[str]] = None
  32. group_docs: List[List] = None
  33. def _vector(self, txt, emb_mdl, sim=0.8, topk=10):
  34. qv, c = emb_mdl.encode_queries(txt)
  35. return {
  36. "field": "q_%d_vec" % len(qv),
  37. "k": topk,
  38. "similarity": sim,
  39. "num_candidates": topk * 2,
  40. "query_vector": qv
  41. }
  42. def search(self, req, idxnm, emb_mdl=None):
  43. qst = req.get("question", "")
  44. bqry, keywords = self.qryr.question(qst)
  45. if req.get("kb_ids"):
  46. bqry.filter.append(Q("terms", kb_id=req["kb_ids"]))
  47. if req.get("doc_ids"):
  48. bqry.filter.append(Q("terms", doc_id=req["doc_ids"]))
  49. if "available_int" in req:
  50. if req["available_int"] == 0:
  51. bqry.filter.append(Q("range", available_int={"lt": 1}))
  52. else:
  53. bqry.filter.append(
  54. Q("bool", must_not=Q("range", available_int={"lt": 1})))
  55. bqry.boost = 0.05
  56. s = Search()
  57. pg = int(req.get("page", 1)) - 1
  58. ps = int(req.get("size", 1000))
  59. src = req.get("fields", ["docnm_kwd", "content_ltks", "kb_id", "img_id",
  60. "image_id", "doc_id", "q_512_vec", "q_768_vec",
  61. "q_1024_vec", "q_1536_vec", "available_int", "content_with_weight"])
  62. s = s.query(bqry)[pg * ps:(pg + 1) * ps]
  63. s = s.highlight("content_ltks")
  64. s = s.highlight("title_ltks")
  65. if not qst:
  66. s = s.sort(
  67. {"create_time": {"order": "desc", "unmapped_type": "date"}})
  68. if qst:
  69. s = s.highlight_options(
  70. fragment_size=120,
  71. number_of_fragments=5,
  72. boundary_scanner_locale="zh-CN",
  73. boundary_scanner="SENTENCE",
  74. boundary_chars=",./;:\\!(),。?:!……()——、"
  75. )
  76. s = s.to_dict()
  77. q_vec = []
  78. if req.get("vector"):
  79. assert emb_mdl, "No embedding model selected"
  80. s["knn"] = self._vector(
  81. qst, emb_mdl, req.get(
  82. "similarity", 0.4), ps)
  83. s["knn"]["filter"] = bqry.to_dict()
  84. if "highlight" in s:
  85. del s["highlight"]
  86. q_vec = s["knn"]["query_vector"]
  87. es_logger.info("【Q】: {}".format(json.dumps(s)))
  88. res = self.es.search(s, idxnm=idxnm, timeout="600s", src=src)
  89. es_logger.info("TOTAL: {}".format(self.es.getTotal(res)))
  90. if self.es.getTotal(res) == 0 and "knn" in s:
  91. bqry, _ = self.qryr.question(qst, min_match="10%")
  92. if req.get("kb_ids"):
  93. bqry.filter.append(Q("terms", kb_id=req["kb_ids"]))
  94. s["query"] = bqry.to_dict()
  95. s["knn"]["filter"] = bqry.to_dict()
  96. s["knn"]["similarity"] = 0.7
  97. res = self.es.search(s, idxnm=idxnm, timeout="600s", src=src)
  98. kwds = set([])
  99. for k in keywords:
  100. kwds.add(k)
  101. for kk in huqie.qieqie(k).split(" "):
  102. if len(kk) < 2:
  103. continue
  104. if kk in kwds:
  105. continue
  106. kwds.add(kk)
  107. aggs = self.getAggregation(res, "docnm_kwd")
  108. return self.SearchResult(
  109. total=self.es.getTotal(res),
  110. ids=self.es.getDocIds(res),
  111. query_vector=q_vec,
  112. aggregation=aggs,
  113. highlight=self.getHighlight(res),
  114. field=self.getFields(res, src),
  115. keywords=list(kwds)
  116. )
  117. def getAggregation(self, res, g):
  118. if not "aggregations" in res or "aggs_" + g not in res["aggregations"]:
  119. return
  120. bkts = res["aggregations"]["aggs_" + g]["buckets"]
  121. return [(b["key"], b["doc_count"]) for b in bkts]
  122. def getHighlight(self, res):
  123. def rmspace(line):
  124. eng = set(list("qwertyuioplkjhgfdsazxcvbnm"))
  125. r = []
  126. for t in line.split(" "):
  127. if not t:
  128. continue
  129. if len(r) > 0 and len(
  130. t) > 0 and r[-1][-1] in eng and t[0] in eng:
  131. r.append(" ")
  132. r.append(t)
  133. r = "".join(r)
  134. return r
  135. ans = {}
  136. for d in res["hits"]["hits"]:
  137. hlts = d.get("highlight")
  138. if not hlts:
  139. continue
  140. ans[d["_id"]] = "".join([a for a in list(hlts.items())[0][1]])
  141. return ans
  142. def getFields(self, sres, flds):
  143. res = {}
  144. if not flds:
  145. return {}
  146. for d in self.es.getSource(sres):
  147. m = {n: d.get(n) for n in flds if d.get(n) is not None}
  148. for n, v in m.items():
  149. if isinstance(v, type([])):
  150. m[n] = "\t".join([str(vv) for vv in v])
  151. continue
  152. if not isinstance(v, type("")):
  153. m[n] = str(m[n])
  154. m[n] = rmSpace(m[n])
  155. if m:
  156. res[d["id"]] = m
  157. return res
  158. @staticmethod
  159. def trans2floats(txt):
  160. return [float(t) for t in txt.split("\t")]
  161. def insert_citations(self, answer, chunks, chunk_v,
  162. embd_mdl, tkweight=0.3, vtweight=0.7):
  163. pieces = re.split(r"([;。?!!\n]|[a-z][.?;!][ \n])", answer)
  164. for i in range(1, len(pieces)):
  165. if re.match(r"[a-z][.?;!][ \n]", pieces[i]):
  166. pieces[i - 1] += pieces[i][0]
  167. pieces[i] = pieces[i][1:]
  168. idx = []
  169. pieces_ = []
  170. for i, t in enumerate(pieces):
  171. if len(t) < 5:
  172. continue
  173. idx.append(i)
  174. pieces_.append(t)
  175. es_logger.info("{} => {}".format(answer, pieces_))
  176. if not pieces_:
  177. return answer
  178. ans_v, _ = embd_mdl.encode(pieces_)
  179. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  180. len(ans_v[0]), len(chunk_v[0]))
  181. chunks_tks = [huqie.qie(ck).split(" ") for ck in chunks]
  182. cites = {}
  183. for i, a in enumerate(pieces_):
  184. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  185. chunk_v,
  186. huqie.qie(
  187. pieces_[i]).split(" "),
  188. chunks_tks,
  189. tkweight, vtweight)
  190. mx = np.max(sim) * 0.99
  191. if mx < 0.55:
  192. continue
  193. cites[idx[i]] = list(
  194. set([str(i) for i in range(len(chunk_v)) if sim[i] > mx]))[:4]
  195. res = ""
  196. for i, p in enumerate(pieces):
  197. res += p
  198. if i not in idx:
  199. continue
  200. if i not in cites:
  201. continue
  202. res += "##%s$$" % "$".join(cites[i])
  203. return res
  204. def rerank(self, sres, query, tkweight=0.3,
  205. vtweight=0.7, cfield="content_ltks"):
  206. ins_embd = [
  207. Dealer.trans2floats(
  208. sres.field[i].get("q_%d_vec" % len(sres.query_vector), "\t".join(["0"] * len(sres.query_vector)))) for i in sres.ids]
  209. if not ins_embd:
  210. return [], [], []
  211. ins_tw = [sres.field[i][cfield].split(" ")
  212. for i in sres.ids]
  213. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  214. ins_embd,
  215. huqie.qie(
  216. query).split(" "),
  217. ins_tw, tkweight, vtweight)
  218. return sim, tksim, vtsim
  219. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  220. return self.qryr.hybrid_similarity(ans_embd,
  221. ins_embd,
  222. huqie.qie(ans).split(" "),
  223. huqie.qie(inst).split(" "))
  224. def retrieval(self, question, embd_mdl, tenant_id, kb_ids, page, page_size, similarity_threshold=0.2,
  225. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True):
  226. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  227. if not question:
  228. return ranks
  229. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "size": top,
  230. "question": question, "vector": True,
  231. "similarity": similarity_threshold}
  232. sres = self.search(req, index_name(tenant_id), embd_mdl)
  233. sim, tsim, vsim = self.rerank(
  234. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  235. idx = np.argsort(sim * -1)
  236. dim = len(sres.query_vector)
  237. start_idx = (page - 1) * page_size
  238. for i in idx:
  239. ranks["total"] += 1
  240. if sim[i] < similarity_threshold:
  241. break
  242. start_idx -= 1
  243. if start_idx >= 0:
  244. continue
  245. if len(ranks["chunks"]) == page_size:
  246. if aggs:
  247. continue
  248. break
  249. id = sres.ids[i]
  250. dnm = sres.field[id]["docnm_kwd"]
  251. d = {
  252. "chunk_id": id,
  253. "content_ltks": sres.field[id]["content_ltks"],
  254. "content_with_weight": sres.field[id]["content_with_weight"],
  255. "doc_id": sres.field[id]["doc_id"],
  256. "docnm_kwd": dnm,
  257. "kb_id": sres.field[id]["kb_id"],
  258. "important_kwd": sres.field[id].get("important_kwd", []),
  259. "img_id": sres.field[id].get("img_id", ""),
  260. "similarity": sim[i],
  261. "vector_similarity": vsim[i],
  262. "term_similarity": tsim[i],
  263. "vector": self.trans2floats(sres.field[id].get("q_%d_vec" % dim, "\t".join(["0"] * dim)))
  264. }
  265. ranks["chunks"].append(d)
  266. if dnm not in ranks["doc_aggs"]:
  267. ranks["doc_aggs"][dnm] = 0
  268. ranks["doc_aggs"][dnm] += 1
  269. return ranks