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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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):
  72. qst = req.get("question", "")
  73. bqry, keywords = self.qryr.question(qst)
  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 "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. bqry = self._add_filters(bqry)
  128. s["query"] = bqry.to_dict()
  129. s["knn"]["filter"] = bqry.to_dict()
  130. s["knn"]["similarity"] = 0.17
  131. res = self.es.search(s, idxnm=idxnm, timeout="600s", src=src)
  132. es_logger.info("【Q】: {}".format(json.dumps(s)))
  133. kwds = set([])
  134. for k in keywords:
  135. kwds.add(k)
  136. for kk in rag_tokenizer.fine_grained_tokenize(k).split(" "):
  137. if len(kk) < 2:
  138. continue
  139. if kk in kwds:
  140. continue
  141. kwds.add(kk)
  142. aggs = self.getAggregation(res, "docnm_kwd")
  143. return self.SearchResult(
  144. total=self.es.getTotal(res),
  145. ids=self.es.getDocIds(res),
  146. query_vector=q_vec,
  147. aggregation=aggs,
  148. highlight=self.getHighlight(res),
  149. field=self.getFields(res, src),
  150. keywords=list(kwds)
  151. )
  152. def getAggregation(self, res, g):
  153. if not "aggregations" in res or "aggs_" + g not in res["aggregations"]:
  154. return
  155. bkts = res["aggregations"]["aggs_" + g]["buckets"]
  156. return [(b["key"], b["doc_count"]) for b in bkts]
  157. def getHighlight(self, res):
  158. def rmspace(line):
  159. eng = set(list("qwertyuioplkjhgfdsazxcvbnm"))
  160. r = []
  161. for t in line.split(" "):
  162. if not t:
  163. continue
  164. if len(r) > 0 and len(
  165. t) > 0 and r[-1][-1] in eng and t[0] in eng:
  166. r.append(" ")
  167. r.append(t)
  168. r = "".join(r)
  169. return r
  170. ans = {}
  171. for d in res["hits"]["hits"]:
  172. hlts = d.get("highlight")
  173. if not hlts:
  174. continue
  175. ans[d["_id"]] = "".join([a for a in list(hlts.items())[0][1]])
  176. return ans
  177. def getFields(self, sres, flds):
  178. res = {}
  179. if not flds:
  180. return {}
  181. for d in self.es.getSource(sres):
  182. m = {n: d.get(n) for n in flds if d.get(n) is not None}
  183. for n, v in m.items():
  184. if isinstance(v, type([])):
  185. m[n] = "\t".join([str(vv) if not isinstance(
  186. vv, list) else "\t".join([str(vvv) for vvv in vv]) for vv in v])
  187. continue
  188. if not isinstance(v, type("")):
  189. m[n] = str(m[n])
  190. if n.find("tks") > 0:
  191. m[n] = rmSpace(m[n])
  192. if m:
  193. res[d["id"]] = m
  194. return res
  195. @staticmethod
  196. def trans2floats(txt):
  197. return [float(t) for t in txt.split("\t")]
  198. def insert_citations(self, answer, chunks, chunk_v,
  199. embd_mdl, tkweight=0.1, vtweight=0.9):
  200. assert len(chunks) == len(chunk_v)
  201. pieces = re.split(r"(```)", answer)
  202. if len(pieces) >= 3:
  203. i = 0
  204. pieces_ = []
  205. while i < len(pieces):
  206. if pieces[i] == "```":
  207. st = i
  208. i += 1
  209. while i < len(pieces) and pieces[i] != "```":
  210. i += 1
  211. if i < len(pieces):
  212. i += 1
  213. pieces_.append("".join(pieces[st: i]) + "\n")
  214. else:
  215. pieces_.extend(
  216. re.split(
  217. r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])",
  218. pieces[i]))
  219. i += 1
  220. pieces = pieces_
  221. else:
  222. pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
  223. for i in range(1, len(pieces)):
  224. if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
  225. pieces[i - 1] += pieces[i][0]
  226. pieces[i] = pieces[i][1:]
  227. idx = []
  228. pieces_ = []
  229. for i, t in enumerate(pieces):
  230. if len(t) < 5:
  231. continue
  232. idx.append(i)
  233. pieces_.append(t)
  234. es_logger.info("{} => {}".format(answer, pieces_))
  235. if not pieces_:
  236. return answer, set([])
  237. ans_v, _ = embd_mdl.encode(pieces_)
  238. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  239. len(ans_v[0]), len(chunk_v[0]))
  240. chunks_tks = [rag_tokenizer.tokenize(self.qryr.rmWWW(ck)).split(" ")
  241. for ck in chunks]
  242. cites = {}
  243. thr = 0.63
  244. while thr>0.3 and len(cites.keys()) == 0 and pieces_ and chunks_tks:
  245. for i, a in enumerate(pieces_):
  246. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  247. chunk_v,
  248. rag_tokenizer.tokenize(
  249. self.qryr.rmWWW(pieces_[i])).split(" "),
  250. chunks_tks,
  251. tkweight, vtweight)
  252. mx = np.max(sim) * 0.99
  253. es_logger.info("{} SIM: {}".format(pieces_[i], mx))
  254. if mx < thr:
  255. continue
  256. cites[idx[i]] = list(
  257. set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
  258. thr *= 0.8
  259. res = ""
  260. seted = set([])
  261. for i, p in enumerate(pieces):
  262. res += p
  263. if i not in idx:
  264. continue
  265. if i not in cites:
  266. continue
  267. for c in cites[i]:
  268. assert int(c) < len(chunk_v)
  269. for c in cites[i]:
  270. if c in seted:
  271. continue
  272. res += f" ##{c}$$"
  273. seted.add(c)
  274. return res, seted
  275. def rerank(self, sres, query, tkweight=0.3,
  276. vtweight=0.7, cfield="content_ltks"):
  277. _, keywords = self.qryr.question(query)
  278. ins_embd = [
  279. Dealer.trans2floats(
  280. sres.field[i].get("q_%d_vec" % len(sres.query_vector), "\t".join(["0"] * len(sres.query_vector)))) for i in sres.ids]
  281. if not ins_embd:
  282. return [], [], []
  283. for i in sres.ids:
  284. if isinstance(sres.field[i].get("important_kwd", []), str):
  285. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  286. ins_tw = []
  287. for i in sres.ids:
  288. content_ltks = sres.field[i][cfield].split(" ")
  289. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  290. important_kwd = sres.field[i].get("important_kwd", [])
  291. tks = content_ltks + title_tks + important_kwd
  292. ins_tw.append(tks)
  293. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  294. ins_embd,
  295. keywords,
  296. ins_tw, tkweight, vtweight)
  297. return sim, tksim, vtsim
  298. def rerank_by_model(self, rerank_mdl, sres, query, tkweight=0.3,
  299. vtweight=0.7, cfield="content_ltks"):
  300. _, keywords = self.qryr.question(query)
  301. for i in sres.ids:
  302. if isinstance(sres.field[i].get("important_kwd", []), str):
  303. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  304. ins_tw = []
  305. for i in sres.ids:
  306. content_ltks = sres.field[i][cfield].split(" ")
  307. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  308. important_kwd = sres.field[i].get("important_kwd", [])
  309. tks = content_ltks + title_tks + important_kwd
  310. ins_tw.append(tks)
  311. tksim = self.qryr.token_similarity(keywords, ins_tw)
  312. vtsim,_ = rerank_mdl.similarity(" ".join(keywords), [rmSpace(" ".join(tks)) for tks in ins_tw])
  313. return tkweight*np.array(tksim) + vtweight*vtsim, tksim, vtsim
  314. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  315. return self.qryr.hybrid_similarity(ans_embd,
  316. ins_embd,
  317. rag_tokenizer.tokenize(ans).split(" "),
  318. rag_tokenizer.tokenize(inst).split(" "))
  319. def retrieval(self, question, embd_mdl, tenant_id, kb_ids, page, page_size, similarity_threshold=0.2,
  320. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True, rerank_mdl=None):
  321. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  322. if not question:
  323. return ranks
  324. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "size": page_size,
  325. "question": question, "vector": True, "topk": top,
  326. "similarity": similarity_threshold,
  327. "available_int": 1}
  328. sres = self.search(req, index_name(tenant_id), embd_mdl)
  329. if rerank_mdl:
  330. sim, tsim, vsim = self.rerank_by_model(rerank_mdl,
  331. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  332. else:
  333. sim, tsim, vsim = self.rerank(
  334. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  335. idx = np.argsort(sim * -1)
  336. dim = len(sres.query_vector)
  337. start_idx = (page - 1) * page_size
  338. for i in idx:
  339. if sim[i] < similarity_threshold:
  340. break
  341. ranks["total"] += 1
  342. start_idx -= 1
  343. if start_idx >= 0:
  344. continue
  345. if len(ranks["chunks"]) >= page_size:
  346. if aggs:
  347. continue
  348. break
  349. id = sres.ids[i]
  350. dnm = sres.field[id]["docnm_kwd"]
  351. did = sres.field[id]["doc_id"]
  352. d = {
  353. "chunk_id": id,
  354. "content_ltks": sres.field[id]["content_ltks"],
  355. "content_with_weight": sres.field[id]["content_with_weight"],
  356. "doc_id": sres.field[id]["doc_id"],
  357. "docnm_kwd": dnm,
  358. "kb_id": sres.field[id]["kb_id"],
  359. "important_kwd": sres.field[id].get("important_kwd", []),
  360. "img_id": sres.field[id].get("img_id", ""),
  361. "similarity": sim[i],
  362. "vector_similarity": vsim[i],
  363. "term_similarity": tsim[i],
  364. "vector": self.trans2floats(sres.field[id].get("q_%d_vec" % dim, "\t".join(["0"] * dim))),
  365. "positions": sres.field[id].get("position_int", "").split("\t")
  366. }
  367. if len(d["positions"]) % 5 == 0:
  368. poss = []
  369. for i in range(0, len(d["positions"]), 5):
  370. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  371. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  372. d["positions"] = poss
  373. ranks["chunks"].append(d)
  374. if dnm not in ranks["doc_aggs"]:
  375. ranks["doc_aggs"][dnm] = {"doc_id": did, "count": 0}
  376. ranks["doc_aggs"][dnm]["count"] += 1
  377. ranks["doc_aggs"] = [{"doc_name": k,
  378. "doc_id": v["doc_id"],
  379. "count": v["count"]} for k,
  380. v in sorted(ranks["doc_aggs"].items(),
  381. key=lambda x:x[1]["count"] * -1)]
  382. return ranks
  383. def sql_retrieval(self, sql, fetch_size=128, format="json"):
  384. from api.settings import chat_logger
  385. sql = re.sub(r"[ `]+", " ", sql)
  386. sql = sql.replace("%", "")
  387. es_logger.info(f"Get es sql: {sql}")
  388. replaces = []
  389. for r in re.finditer(r" ([a-z_]+_l?tks)( like | ?= ?)'([^']+)'", sql):
  390. fld, v = r.group(1), r.group(3)
  391. match = " MATCH({}, '{}', 'operator=OR;minimum_should_match=30%') ".format(
  392. fld, rag_tokenizer.fine_grained_tokenize(rag_tokenizer.tokenize(v)))
  393. replaces.append(
  394. ("{}{}'{}'".format(
  395. r.group(1),
  396. r.group(2),
  397. r.group(3)),
  398. match))
  399. for p, r in replaces:
  400. sql = sql.replace(p, r, 1)
  401. chat_logger.info(f"To es: {sql}")
  402. try:
  403. tbl = self.es.sql(sql, fetch_size, format)
  404. return tbl
  405. except Exception as e:
  406. chat_logger.error(f"SQL failure: {sql} =>" + str(e))
  407. return {"error": str(e)}
  408. def chunk_list(self, doc_id, tenant_id, max_count=1024, fields=["docnm_kwd", "content_with_weight", "img_id"]):
  409. s = Search()
  410. s = s.query(Q("match", doc_id=doc_id))[0:max_count]
  411. s = s.to_dict()
  412. es_res = self.es.search(s, idxnm=index_name(tenant_id), timeout="600s", src=fields)
  413. res = []
  414. for index, chunk in enumerate(es_res['hits']['hits']):
  415. res.append({fld: chunk['_source'].get(fld) for fld in fields})
  416. return res