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.

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