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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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, is_english
  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, idxnms, 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), idxnms=idxnms, 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, idxnms=idxnms, 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, keywords, "content_with_weight"),
  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, keywords, fieldnm):
  160. ans = {}
  161. for d in res["hits"]["hits"]:
  162. hlts = d.get("highlight")
  163. if not hlts:
  164. continue
  165. txt = "...".join([a for a in list(hlts.items())[0][1]])
  166. if not is_english(txt.split(" ")):
  167. ans[d["_id"]] = txt
  168. continue
  169. txt = d["_source"][fieldnm]
  170. txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE|re.MULTILINE)
  171. txts = []
  172. for t in re.split(r"[.?!;\n]", txt):
  173. for w in keywords:
  174. t = re.sub(r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])"%re.escape(w), r"\1<em>\2</em>\3", t, flags=re.IGNORECASE|re.MULTILINE)
  175. if not re.search(r"<em>[^<>]+</em>", t, flags=re.IGNORECASE|re.MULTILINE): continue
  176. txts.append(t)
  177. ans[d["_id"]] = "...".join(txts) if txts else "...".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. if not chunks:
  204. return answer, set([])
  205. pieces = re.split(r"(```)", answer)
  206. if len(pieces) >= 3:
  207. i = 0
  208. pieces_ = []
  209. while i < len(pieces):
  210. if pieces[i] == "```":
  211. st = i
  212. i += 1
  213. while i < len(pieces) and pieces[i] != "```":
  214. i += 1
  215. if i < len(pieces):
  216. i += 1
  217. pieces_.append("".join(pieces[st: i]) + "\n")
  218. else:
  219. pieces_.extend(
  220. re.split(
  221. r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])",
  222. pieces[i]))
  223. i += 1
  224. pieces = pieces_
  225. else:
  226. pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
  227. for i in range(1, len(pieces)):
  228. if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
  229. pieces[i - 1] += pieces[i][0]
  230. pieces[i] = pieces[i][1:]
  231. idx = []
  232. pieces_ = []
  233. for i, t in enumerate(pieces):
  234. if len(t) < 5:
  235. continue
  236. idx.append(i)
  237. pieces_.append(t)
  238. es_logger.info("{} => {}".format(answer, pieces_))
  239. if not pieces_:
  240. return answer, set([])
  241. ans_v, _ = embd_mdl.encode(pieces_)
  242. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  243. len(ans_v[0]), len(chunk_v[0]))
  244. chunks_tks = [rag_tokenizer.tokenize(self.qryr.rmWWW(ck)).split(" ")
  245. for ck in chunks]
  246. cites = {}
  247. thr = 0.63
  248. while thr>0.3 and len(cites.keys()) == 0 and pieces_ and chunks_tks:
  249. for i, a in enumerate(pieces_):
  250. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  251. chunk_v,
  252. rag_tokenizer.tokenize(
  253. self.qryr.rmWWW(pieces_[i])).split(" "),
  254. chunks_tks,
  255. tkweight, vtweight)
  256. mx = np.max(sim) * 0.99
  257. es_logger.info("{} SIM: {}".format(pieces_[i], mx))
  258. if mx < thr:
  259. continue
  260. cites[idx[i]] = list(
  261. set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
  262. thr *= 0.8
  263. res = ""
  264. seted = set([])
  265. for i, p in enumerate(pieces):
  266. res += p
  267. if i not in idx:
  268. continue
  269. if i not in cites:
  270. continue
  271. for c in cites[i]:
  272. assert int(c) < len(chunk_v)
  273. for c in cites[i]:
  274. if c in seted:
  275. continue
  276. res += f" ##{c}$$"
  277. seted.add(c)
  278. return res, seted
  279. def rerank(self, sres, query, tkweight=0.3,
  280. vtweight=0.7, cfield="content_ltks"):
  281. _, keywords = self.qryr.question(query)
  282. ins_embd = [
  283. Dealer.trans2floats(
  284. sres.field[i].get("q_%d_vec" % len(sres.query_vector), "\t".join(["0"] * len(sres.query_vector)))) for i in sres.ids]
  285. if not ins_embd:
  286. return [], [], []
  287. for i in sres.ids:
  288. if isinstance(sres.field[i].get("important_kwd", []), str):
  289. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  290. ins_tw = []
  291. for i in sres.ids:
  292. content_ltks = sres.field[i][cfield].split(" ")
  293. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  294. important_kwd = sres.field[i].get("important_kwd", [])
  295. tks = content_ltks + title_tks + important_kwd
  296. ins_tw.append(tks)
  297. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  298. ins_embd,
  299. keywords,
  300. ins_tw, tkweight, vtweight)
  301. return sim, tksim, vtsim
  302. def rerank_by_model(self, rerank_mdl, sres, query, tkweight=0.3,
  303. vtweight=0.7, cfield="content_ltks"):
  304. _, keywords = self.qryr.question(query)
  305. for i in sres.ids:
  306. if isinstance(sres.field[i].get("important_kwd", []), str):
  307. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  308. ins_tw = []
  309. for i in sres.ids:
  310. content_ltks = sres.field[i][cfield].split(" ")
  311. title_tks = [t for t in sres.field[i].get("title_tks", "").split(" ") if t]
  312. important_kwd = sres.field[i].get("important_kwd", [])
  313. tks = content_ltks + title_tks + important_kwd
  314. ins_tw.append(tks)
  315. tksim = self.qryr.token_similarity(keywords, ins_tw)
  316. vtsim,_ = rerank_mdl.similarity(query, [rmSpace(" ".join(tks)) for tks in ins_tw])
  317. return tkweight*np.array(tksim) + vtweight*vtsim, tksim, vtsim
  318. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  319. return self.qryr.hybrid_similarity(ans_embd,
  320. ins_embd,
  321. rag_tokenizer.tokenize(ans).split(" "),
  322. rag_tokenizer.tokenize(inst).split(" "))
  323. def retrieval(self, question, embd_mdl, tenant_ids, kb_ids, page, page_size, similarity_threshold=0.2,
  324. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True, rerank_mdl=None, highlight=False):
  325. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  326. if not question:
  327. return ranks
  328. RERANK_PAGE_LIMIT = 3
  329. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "size": max(page_size*RERANK_PAGE_LIMIT, 128),
  330. "question": question, "vector": True, "topk": top,
  331. "similarity": similarity_threshold,
  332. "available_int": 1}
  333. if page > RERANK_PAGE_LIMIT:
  334. req["page"] = page
  335. req["size"] = page_size
  336. if isinstance(tenant_ids, str):
  337. tenant_ids = tenant_ids.split(",")
  338. sres = self.search(req, [index_name(tid) for tid in tenant_ids], embd_mdl, highlight)
  339. ranks["total"] = sres.total
  340. if page <= RERANK_PAGE_LIMIT:
  341. if rerank_mdl:
  342. sim, tsim, vsim = self.rerank_by_model(rerank_mdl,
  343. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  344. else:
  345. sim, tsim, vsim = self.rerank(
  346. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  347. idx = np.argsort(sim * -1)[(page-1)*page_size:page*page_size]
  348. else:
  349. sim = tsim = vsim = [1]*len(sres.ids)
  350. idx = list(range(len(sres.ids)))
  351. dim = len(sres.query_vector)
  352. for i in idx:
  353. if sim[i] < similarity_threshold:
  354. break
  355. if len(ranks["chunks"]) >= page_size:
  356. if aggs:
  357. continue
  358. break
  359. id = sres.ids[i]
  360. dnm = sres.field[id]["docnm_kwd"]
  361. did = sres.field[id]["doc_id"]
  362. d = {
  363. "chunk_id": id,
  364. "content_ltks": sres.field[id]["content_ltks"],
  365. "content_with_weight": sres.field[id]["content_with_weight"],
  366. "doc_id": sres.field[id]["doc_id"],
  367. "docnm_kwd": dnm,
  368. "kb_id": sres.field[id]["kb_id"],
  369. "important_kwd": sres.field[id].get("important_kwd", []),
  370. "img_id": sres.field[id].get("img_id", ""),
  371. "similarity": sim[i],
  372. "vector_similarity": vsim[i],
  373. "term_similarity": tsim[i],
  374. "vector": self.trans2floats(sres.field[id].get("q_%d_vec" % dim, "\t".join(["0"] * dim))),
  375. "positions": sres.field[id].get("position_int", "").split("\t")
  376. }
  377. if highlight:
  378. if id in sres.highlight:
  379. d["highlight"] = rmSpace(sres.highlight[id])
  380. else:
  381. d["highlight"] = d["content_with_weight"]
  382. if len(d["positions"]) % 5 == 0:
  383. poss = []
  384. for i in range(0, len(d["positions"]), 5):
  385. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  386. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  387. d["positions"] = poss
  388. ranks["chunks"].append(d)
  389. if dnm not in ranks["doc_aggs"]:
  390. ranks["doc_aggs"][dnm] = {"doc_id": did, "count": 0}
  391. ranks["doc_aggs"][dnm]["count"] += 1
  392. ranks["doc_aggs"] = [{"doc_name": k,
  393. "doc_id": v["doc_id"],
  394. "count": v["count"]} for k,
  395. v in sorted(ranks["doc_aggs"].items(),
  396. key=lambda x:x[1]["count"] * -1)]
  397. return ranks
  398. def sql_retrieval(self, sql, fetch_size=128, format="json"):
  399. from api.settings import chat_logger
  400. sql = re.sub(r"[ `]+", " ", sql)
  401. sql = sql.replace("%", "")
  402. es_logger.info(f"Get es sql: {sql}")
  403. replaces = []
  404. for r in re.finditer(r" ([a-z_]+_l?tks)( like | ?= ?)'([^']+)'", sql):
  405. fld, v = r.group(1), r.group(3)
  406. match = " MATCH({}, '{}', 'operator=OR;minimum_should_match=30%') ".format(
  407. fld, rag_tokenizer.fine_grained_tokenize(rag_tokenizer.tokenize(v)))
  408. replaces.append(
  409. ("{}{}'{}'".format(
  410. r.group(1),
  411. r.group(2),
  412. r.group(3)),
  413. match))
  414. for p, r in replaces:
  415. sql = sql.replace(p, r, 1)
  416. chat_logger.info(f"To es: {sql}")
  417. try:
  418. tbl = self.es.sql(sql, fetch_size, format)
  419. return tbl
  420. except Exception as e:
  421. chat_logger.error(f"SQL failure: {sql} =>" + str(e))
  422. return {"error": str(e)}
  423. def chunk_list(self, doc_id, tenant_id, max_count=1024, fields=["docnm_kwd", "content_with_weight", "img_id"]):
  424. s = Search()
  425. s = s.query(Q("match", doc_id=doc_id))[0:max_count]
  426. s = s.to_dict()
  427. es_res = self.es.search(s, idxnms=index_name(tenant_id), timeout="600s", src=fields)
  428. res = []
  429. for index, chunk in enumerate(es_res['hits']['hits']):
  430. res.append({fld: chunk['_source'].get(fld) for fld in fields})
  431. return res