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

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