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.

search.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. from copy import deepcopy
  19. from elasticsearch_dsl import Q, Search
  20. from typing import List, Optional, Dict, Union
  21. from dataclasses import dataclass
  22. from rag.settings import es_logger
  23. from rag.utils import rmSpace
  24. from rag.nlp import rag_tokenizer, query
  25. import numpy as np
  26. def index_name(uid): return f"ragflow_{uid}"
  27. class Dealer:
  28. def __init__(self, es):
  29. self.qryr = query.EsQueryer(es)
  30. self.qryr.flds = [
  31. "title_tks^10",
  32. "title_sm_tks^5",
  33. "important_kwd^30",
  34. "important_tks^20",
  35. "content_ltks^2",
  36. "content_sm_ltks"]
  37. self.es = es
  38. @dataclass
  39. class SearchResult:
  40. total: int
  41. ids: List[str]
  42. query_vector: List[float] = None
  43. field: Optional[Dict] = None
  44. highlight: Optional[Dict] = None
  45. aggregation: Union[List, Dict, None] = None
  46. keywords: Optional[List[str]] = None
  47. group_docs: List[List] = None
  48. def _vector(self, txt, emb_mdl, sim=0.8, topk=10):
  49. qv, c = emb_mdl.encode_queries(txt)
  50. return {
  51. "field": "q_%d_vec" % len(qv),
  52. "k": topk,
  53. "similarity": sim,
  54. "num_candidates": topk * 2,
  55. "query_vector": [float(v) for v in qv]
  56. }
  57. def _add_filters(self, bqry, req):
  58. if req.get("kb_ids"):
  59. bqry.filter.append(Q("terms", kb_id=req["kb_ids"]))
  60. if req.get("doc_ids"):
  61. bqry.filter.append(Q("terms", doc_id=req["doc_ids"]))
  62. if req.get("knowledge_graph_kwd"):
  63. bqry.filter.append(Q("terms", knowledge_graph_kwd=req["knowledge_graph_kwd"]))
  64. if "available_int" in req:
  65. if req["available_int"] == 0:
  66. bqry.filter.append(Q("range", available_int={"lt": 1}))
  67. else:
  68. bqry.filter.append(
  69. Q("bool", must_not=Q("range", available_int={"lt": 1})))
  70. return bqry
  71. def search(self, req, idxnm, emb_mdl=None, highlight=False):
  72. qst = req.get("question", "")
  73. bqry, keywords = self.qryr.question(qst, min_match="30%")
  74. bqry = self._add_filters(bqry, req)
  75. bqry.boost = 0.05
  76. s = Search()
  77. pg = int(req.get("page", 1)) - 1
  78. topk = int(req.get("topk", 1024))
  79. ps = int(req.get("size", topk))
  80. src = req.get("fields", ["docnm_kwd", "content_ltks", "kb_id", "img_id", "title_tks", "important_kwd",
  81. "image_id", "doc_id", "q_512_vec", "q_768_vec", "position_int", "knowledge_graph_kwd",
  82. "q_1024_vec", "q_1536_vec", "available_int", "content_with_weight"])
  83. s = s.query(bqry)[pg * ps:(pg + 1) * ps]
  84. s = s.highlight("content_ltks")
  85. s = s.highlight("title_ltks")
  86. if not qst:
  87. if not req.get("sort"):
  88. s = s.sort(
  89. #{"create_time": {"order": "desc", "unmapped_type": "date"}},
  90. {"create_timestamp_flt": {
  91. "order": "desc", "unmapped_type": "float"}}
  92. )
  93. else:
  94. s = s.sort(
  95. {"page_num_int": {"order": "asc", "unmapped_type": "float",
  96. "mode": "avg", "numeric_type": "double"}},
  97. {"top_int": {"order": "asc", "unmapped_type": "float",
  98. "mode": "avg", "numeric_type": "double"}},
  99. #{"create_time": {"order": "desc", "unmapped_type": "date"}},
  100. {"create_timestamp_flt": {
  101. "order": "desc", "unmapped_type": "float"}}
  102. )
  103. if qst:
  104. s = s.highlight_options(
  105. fragment_size=120,
  106. number_of_fragments=5,
  107. boundary_scanner_locale="zh-CN",
  108. boundary_scanner="SENTENCE",
  109. boundary_chars=",./;:\\!(),。?:!……()——、"
  110. )
  111. s = s.to_dict()
  112. q_vec = []
  113. if req.get("vector"):
  114. assert emb_mdl, "No embedding model selected"
  115. s["knn"] = self._vector(
  116. qst, emb_mdl, req.get(
  117. "similarity", 0.1), topk)
  118. s["knn"]["filter"] = bqry.to_dict()
  119. if not highlight and "highlight" in s:
  120. del s["highlight"]
  121. q_vec = s["knn"]["query_vector"]
  122. es_logger.info("【Q】: {}".format(json.dumps(s)))
  123. res = self.es.search(deepcopy(s), idxnm=idxnm, timeout="600s", src=src)
  124. es_logger.info("TOTAL: {}".format(self.es.getTotal(res)))
  125. if self.es.getTotal(res) == 0 and "knn" in s:
  126. bqry, _ = self.qryr.question(qst, min_match="10%")
  127. if req.get("doc_ids"):
  128. bqry = Q("bool", must=[])
  129. bqry = self._add_filters(bqry, req)
  130. s["query"] = bqry.to_dict()
  131. s["knn"]["filter"] = bqry.to_dict()
  132. s["knn"]["similarity"] = 0.17
  133. res = self.es.search(s, idxnm=idxnm, timeout="600s", src=src)
  134. es_logger.info("【Q】: {}".format(json.dumps(s)))
  135. kwds = set([])
  136. for k in keywords:
  137. kwds.add(k)
  138. for kk in rag_tokenizer.fine_grained_tokenize(k).split(" "):
  139. if len(kk) < 2:
  140. continue
  141. if kk in kwds:
  142. continue
  143. kwds.add(kk)
  144. aggs = self.getAggregation(res, "docnm_kwd")
  145. return self.SearchResult(
  146. total=self.es.getTotal(res),
  147. ids=self.es.getDocIds(res),
  148. query_vector=q_vec,
  149. aggregation=aggs,
  150. highlight=self.getHighlight(res),
  151. field=self.getFields(res, src),
  152. keywords=list(kwds)
  153. )
  154. def getAggregation(self, res, g):
  155. if not "aggregations" in res or "aggs_" + g not in res["aggregations"]:
  156. return
  157. bkts = res["aggregations"]["aggs_" + g]["buckets"]
  158. return [(b["key"], b["doc_count"]) for b in bkts]
  159. def getHighlight(self, res):
  160. def rmspace(line):
  161. eng = set(list("qwertyuioplkjhgfdsazxcvbnm"))
  162. r = []
  163. for t in line.split(" "):
  164. if not t:
  165. continue
  166. if len(r) > 0 and len(
  167. t) > 0 and r[-1][-1] in eng and t[0] in eng:
  168. r.append(" ")
  169. r.append(t)
  170. r = "".join(r)
  171. return r
  172. ans = {}
  173. for d in res["hits"]["hits"]:
  174. hlts = d.get("highlight")
  175. if not hlts:
  176. continue
  177. ans[d["_id"]] = "".join([a for a in list(hlts.items())[0][1]])
  178. return ans
  179. def getFields(self, sres, flds):
  180. res = {}
  181. if not flds:
  182. return {}
  183. for d in self.es.getSource(sres):
  184. m = {n: d.get(n) for n in flds if d.get(n) is not None}
  185. for n, v in m.items():
  186. if isinstance(v, type([])):
  187. m[n] = "\t".join([str(vv) if not isinstance(
  188. vv, list) else "\t".join([str(vvv) for vvv in vv]) for vv in v])
  189. continue
  190. if not isinstance(v, type("")):
  191. m[n] = str(m[n])
  192. if n.find("tks") > 0:
  193. m[n] = rmSpace(m[n])
  194. if m:
  195. res[d["id"]] = m
  196. return res
  197. @staticmethod
  198. def trans2floats(txt):
  199. return [float(t) for t in txt.split("\t")]
  200. def insert_citations(self, answer, chunks, chunk_v,
  201. embd_mdl, tkweight=0.1, vtweight=0.9):
  202. assert len(chunks) == len(chunk_v)
  203. pieces = re.split(r"(```)", answer)
  204. if len(pieces) >= 3:
  205. i = 0
  206. pieces_ = []
  207. while i < len(pieces):
  208. if pieces[i] == "```":
  209. st = i
  210. i += 1
  211. while i < len(pieces) and pieces[i] != "```":
  212. i += 1
  213. if i < len(pieces):
  214. i += 1
  215. pieces_.append("".join(pieces[st: i]) + "\n")
  216. else:
  217. pieces_.extend(
  218. re.split(
  219. r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])",
  220. pieces[i]))
  221. i += 1
  222. pieces = pieces_
  223. else:
  224. pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
  225. for i in range(1, len(pieces)):
  226. if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
  227. pieces[i - 1] += pieces[i][0]
  228. pieces[i] = pieces[i][1:]
  229. idx = []
  230. pieces_ = []
  231. for i, t in enumerate(pieces):
  232. if len(t) < 5:
  233. continue
  234. idx.append(i)
  235. pieces_.append(t)
  236. es_logger.info("{} => {}".format(answer, pieces_))
  237. if not pieces_:
  238. return answer, set([])
  239. ans_v, _ = embd_mdl.encode(pieces_)
  240. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  241. len(ans_v[0]), len(chunk_v[0]))
  242. chunks_tks = [rag_tokenizer.tokenize(self.qryr.rmWWW(ck)).split(" ")
  243. for ck in chunks]
  244. cites = {}
  245. thr = 0.63
  246. while thr>0.3 and len(cites.keys()) == 0 and pieces_ and chunks_tks:
  247. for i, a in enumerate(pieces_):
  248. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  249. chunk_v,
  250. rag_tokenizer.tokenize(
  251. self.qryr.rmWWW(pieces_[i])).split(" "),
  252. chunks_tks,
  253. tkweight, vtweight)
  254. mx = np.max(sim) * 0.99
  255. es_logger.info("{} SIM: {}".format(pieces_[i], mx))
  256. if mx < thr:
  257. continue
  258. cites[idx[i]] = list(
  259. set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
  260. thr *= 0.8
  261. res = ""
  262. seted = set([])
  263. for i, p in enumerate(pieces):
  264. res += p
  265. if i not in idx:
  266. continue
  267. if i not in cites:
  268. continue
  269. for c in cites[i]:
  270. assert int(c) < len(chunk_v)
  271. for c in cites[i]:
  272. if c in seted:
  273. continue
  274. res += f" ##{c}$$"
  275. seted.add(c)
  276. return res, seted
  277. def rerank(self, sres, query, tkweight=0.3,
  278. vtweight=0.7, cfield="content_ltks"):
  279. _, keywords = self.qryr.question(query)
  280. ins_embd = [
  281. Dealer.trans2floats(
  282. sres.field[i].get("q_%d_vec" % len(sres.query_vector), "\t".join(["0"] * len(sres.query_vector)))) for i in sres.ids]
  283. if not ins_embd:
  284. return [], [], []
  285. for i in sres.ids:
  286. if isinstance(sres.field[i].get("important_kwd", []), str):
  287. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  288. ins_tw = []
  289. for i in sres.ids:
  290. content_ltks = sres.field[i][cfield].split(" ")
  291. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  292. important_kwd = sres.field[i].get("important_kwd", [])
  293. tks = content_ltks + title_tks + important_kwd
  294. ins_tw.append(tks)
  295. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  296. ins_embd,
  297. keywords,
  298. ins_tw, tkweight, vtweight)
  299. return sim, tksim, vtsim
  300. def rerank_by_model(self, rerank_mdl, sres, query, tkweight=0.3,
  301. vtweight=0.7, cfield="content_ltks"):
  302. _, keywords = self.qryr.question(query)
  303. for i in sres.ids:
  304. if isinstance(sres.field[i].get("important_kwd", []), str):
  305. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  306. ins_tw = []
  307. for i in sres.ids:
  308. content_ltks = sres.field[i][cfield].split(" ")
  309. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  310. important_kwd = sres.field[i].get("important_kwd", [])
  311. tks = content_ltks + title_tks + important_kwd
  312. ins_tw.append(tks)
  313. tksim = self.qryr.token_similarity(keywords, ins_tw)
  314. vtsim,_ = rerank_mdl.similarity(" ".join(keywords), [rmSpace(" ".join(tks)) for tks in ins_tw])
  315. return tkweight*np.array(tksim) + vtweight*vtsim, tksim, vtsim
  316. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  317. return self.qryr.hybrid_similarity(ans_embd,
  318. ins_embd,
  319. rag_tokenizer.tokenize(ans).split(" "),
  320. rag_tokenizer.tokenize(inst).split(" "))
  321. def retrieval(self, question, embd_mdl, tenant_id, kb_ids, page, page_size, similarity_threshold=0.2,
  322. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True, rerank_mdl=None, highlight=False):
  323. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  324. if not question:
  325. return ranks
  326. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "size": page_size,
  327. "question": question, "vector": True, "topk": top,
  328. "similarity": similarity_threshold,
  329. "available_int": 1}
  330. sres = self.search(req, index_name(tenant_id), embd_mdl, highlight)
  331. if rerank_mdl:
  332. sim, tsim, vsim = self.rerank_by_model(rerank_mdl,
  333. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  334. else:
  335. sim, tsim, vsim = self.rerank(
  336. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  337. idx = np.argsort(sim * -1)
  338. dim = len(sres.query_vector)
  339. start_idx = (page - 1) * page_size
  340. for i in idx:
  341. if sim[i] < similarity_threshold:
  342. break
  343. ranks["total"] += 1
  344. start_idx -= 1
  345. if start_idx >= 0:
  346. continue
  347. if len(ranks["chunks"]) >= page_size:
  348. if aggs:
  349. continue
  350. break
  351. id = sres.ids[i]
  352. dnm = sres.field[id]["docnm_kwd"]
  353. did = sres.field[id]["doc_id"]
  354. d = {
  355. "chunk_id": id,
  356. "content_ltks": sres.field[id]["content_ltks"],
  357. "content_with_weight": sres.field[id]["content_with_weight"],
  358. "doc_id": sres.field[id]["doc_id"],
  359. "docnm_kwd": dnm,
  360. "kb_id": sres.field[id]["kb_id"],
  361. "important_kwd": sres.field[id].get("important_kwd", []),
  362. "img_id": sres.field[id].get("img_id", ""),
  363. "similarity": sim[i],
  364. "vector_similarity": vsim[i],
  365. "term_similarity": tsim[i],
  366. "vector": self.trans2floats(sres.field[id].get("q_%d_vec" % dim, "\t".join(["0"] * dim))),
  367. "positions": sres.field[id].get("position_int", "").split("\t")
  368. }
  369. if highlight:
  370. d["highlight"] = rmSpace(sres.highlight[id])
  371. if len(d["positions"]) % 5 == 0:
  372. poss = []
  373. for i in range(0, len(d["positions"]), 5):
  374. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  375. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  376. d["positions"] = poss
  377. ranks["chunks"].append(d)
  378. if dnm not in ranks["doc_aggs"]:
  379. ranks["doc_aggs"][dnm] = {"doc_id": did, "count": 0}
  380. ranks["doc_aggs"][dnm]["count"] += 1
  381. ranks["doc_aggs"] = [{"doc_name": k,
  382. "doc_id": v["doc_id"],
  383. "count": v["count"]} for k,
  384. v in sorted(ranks["doc_aggs"].items(),
  385. key=lambda x:x[1]["count"] * -1)]
  386. return ranks
  387. def sql_retrieval(self, sql, fetch_size=128, format="json"):
  388. from api.settings import chat_logger
  389. sql = re.sub(r"[ `]+", " ", sql)
  390. sql = sql.replace("%", "")
  391. es_logger.info(f"Get es sql: {sql}")
  392. replaces = []
  393. for r in re.finditer(r" ([a-z_]+_l?tks)( like | ?= ?)'([^']+)'", sql):
  394. fld, v = r.group(1), r.group(3)
  395. match = " MATCH({}, '{}', 'operator=OR;minimum_should_match=30%') ".format(
  396. fld, rag_tokenizer.fine_grained_tokenize(rag_tokenizer.tokenize(v)))
  397. replaces.append(
  398. ("{}{}'{}'".format(
  399. r.group(1),
  400. r.group(2),
  401. r.group(3)),
  402. match))
  403. for p, r in replaces:
  404. sql = sql.replace(p, r, 1)
  405. chat_logger.info(f"To es: {sql}")
  406. try:
  407. tbl = self.es.sql(sql, fetch_size, format)
  408. return tbl
  409. except Exception as e:
  410. chat_logger.error(f"SQL failure: {sql} =>" + str(e))
  411. return {"error": str(e)}
  412. def chunk_list(self, doc_id, tenant_id, max_count=1024, fields=["docnm_kwd", "content_with_weight", "img_id"]):
  413. s = Search()
  414. s = s.query(Q("match", doc_id=doc_id))[0:max_count]
  415. s = s.to_dict()
  416. es_res = self.es.search(s, idxnm=index_name(tenant_id), timeout="600s", src=fields)
  417. res = []
  418. for index, chunk in enumerate(es_res['hits']['hits']):
  419. res.append({fld: chunk['_source'].get(fld) for fld in fields})
  420. return res