Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 logging
  17. import re
  18. import json
  19. from dataclasses import dataclass
  20. from rag.utils import rmSpace
  21. from rag.nlp import rag_tokenizer, query
  22. import numpy as np
  23. from rag.utils.doc_store_conn import DocStoreConnection, MatchDenseExpr, FusionExpr, OrderByExpr
  24. def index_name(uid): return f"ragflow_{uid}"
  25. class Dealer:
  26. def __init__(self, dataStore: DocStoreConnection):
  27. self.qryr = query.FulltextQueryer()
  28. self.dataStore = dataStore
  29. @dataclass
  30. class SearchResult:
  31. total: int
  32. ids: list[str]
  33. query_vector: list[float] | None = None
  34. field: dict | None = None
  35. highlight: dict | None = None
  36. aggregation: list | dict | None = None
  37. keywords: list[str] | None = None
  38. group_docs: list[list] | None = None
  39. def get_vector(self, txt, emb_mdl, topk=10, similarity=0.1):
  40. qv, _ = emb_mdl.encode_queries(txt)
  41. shape = np.array(qv).shape
  42. if len(shape) > 1:
  43. raise Exception(f"Dealer.get_vector returned array's shape {shape} doesn't match expectation(exact one dimension).")
  44. embedding_data = [float(v) for v in qv]
  45. vector_column_name = f"q_{len(embedding_data)}_vec"
  46. return MatchDenseExpr(vector_column_name, embedding_data, 'float', 'cosine', topk, {"similarity": similarity})
  47. def get_filters(self, req):
  48. condition = dict()
  49. for key, field in {"kb_ids": "kb_id", "doc_ids": "doc_id"}.items():
  50. if key in req and req[key] is not None:
  51. condition[field] = req[key]
  52. # TODO(yzc): `available_int` is nullable however infinity doesn't support nullable columns.
  53. for key in ["knowledge_graph_kwd", "available_int"]:
  54. if key in req and req[key] is not None:
  55. condition[key] = req[key]
  56. return condition
  57. def search(self, req, idx_names: str | list[str], kb_ids: list[str], emb_mdl=None, highlight = False):
  58. filters = self.get_filters(req)
  59. orderBy = OrderByExpr()
  60. pg = int(req.get("page", 1)) - 1
  61. topk = int(req.get("topk", 1024))
  62. ps = int(req.get("size", topk))
  63. offset, limit = pg * ps, (pg + 1) * ps
  64. src = req.get("fields", ["docnm_kwd", "content_ltks", "kb_id", "img_id", "title_tks", "important_kwd",
  65. "doc_id", "position_list", "knowledge_graph_kwd",
  66. "available_int", "content_with_weight"])
  67. kwds = set([])
  68. qst = req.get("question", "")
  69. q_vec = []
  70. if not qst:
  71. if req.get("sort"):
  72. orderBy.desc("create_timestamp_flt")
  73. res = self.dataStore.search(src, [], filters, [], orderBy, offset, limit, idx_names, kb_ids)
  74. total=self.dataStore.getTotal(res)
  75. logging.debug("Dealer.search TOTAL: {}".format(total))
  76. else:
  77. highlightFields = ["content_ltks", "title_tks"] if highlight else []
  78. matchText, keywords = self.qryr.question(qst, min_match=0.3)
  79. if emb_mdl is None:
  80. matchExprs = [matchText]
  81. res = self.dataStore.search(src, highlightFields, filters, matchExprs, orderBy, offset, limit, idx_names, kb_ids)
  82. total=self.dataStore.getTotal(res)
  83. logging.debug("Dealer.search TOTAL: {}".format(total))
  84. else:
  85. matchDense = self.get_vector(qst, emb_mdl, topk, req.get("similarity", 0.1))
  86. q_vec = matchDense.embedding_data
  87. src.append(f"q_{len(q_vec)}_vec")
  88. fusionExpr = FusionExpr("weighted_sum", topk, {"weights": "0.05, 0.95"})
  89. matchExprs = [matchText, matchDense, fusionExpr]
  90. res = self.dataStore.search(src, highlightFields, filters, matchExprs, orderBy, offset, limit, idx_names, kb_ids)
  91. total=self.dataStore.getTotal(res)
  92. logging.debug("Dealer.search TOTAL: {}".format(total))
  93. # If result is empty, try again with lower min_match
  94. if total == 0:
  95. matchText, _ = self.qryr.question(qst, min_match=0.1)
  96. filters.pop("doc_ids", None)
  97. matchDense.extra_options["similarity"] = 0.17
  98. res = self.dataStore.search(src, highlightFields, filters, [matchText, matchDense, fusionExpr], orderBy, offset, limit, idx_names, kb_ids)
  99. total=self.dataStore.getTotal(res)
  100. logging.debug("Dealer.search 2 TOTAL: {}".format(total))
  101. for k in keywords:
  102. kwds.add(k)
  103. for kk in rag_tokenizer.fine_grained_tokenize(k).split():
  104. if len(kk) < 2:
  105. continue
  106. if kk in kwds:
  107. continue
  108. kwds.add(kk)
  109. logging.debug(f"TOTAL: {total}")
  110. ids=self.dataStore.getChunkIds(res)
  111. keywords=list(kwds)
  112. highlight = self.dataStore.getHighlight(res, keywords, "content_with_weight")
  113. aggs = self.dataStore.getAggregation(res, "docnm_kwd")
  114. return self.SearchResult(
  115. total=total,
  116. ids=ids,
  117. query_vector=q_vec,
  118. aggregation=aggs,
  119. highlight=highlight,
  120. field=self.dataStore.getFields(res, src),
  121. keywords=keywords
  122. )
  123. @staticmethod
  124. def trans2floats(txt):
  125. return [float(t) for t in txt.split("\t")]
  126. def insert_citations(self, answer, chunks, chunk_v,
  127. embd_mdl, tkweight=0.1, vtweight=0.9):
  128. assert len(chunks) == len(chunk_v)
  129. if not chunks:
  130. return answer, set([])
  131. pieces = re.split(r"(```)", answer)
  132. if len(pieces) >= 3:
  133. i = 0
  134. pieces_ = []
  135. while i < len(pieces):
  136. if pieces[i] == "```":
  137. st = i
  138. i += 1
  139. while i < len(pieces) and pieces[i] != "```":
  140. i += 1
  141. if i < len(pieces):
  142. i += 1
  143. pieces_.append("".join(pieces[st: i]) + "\n")
  144. else:
  145. pieces_.extend(
  146. re.split(
  147. r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])",
  148. pieces[i]))
  149. i += 1
  150. pieces = pieces_
  151. else:
  152. pieces = re.split(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", answer)
  153. for i in range(1, len(pieces)):
  154. if re.match(r"([^\|][;。?!!\n]|[a-z][.?;!][ \n])", pieces[i]):
  155. pieces[i - 1] += pieces[i][0]
  156. pieces[i] = pieces[i][1:]
  157. idx = []
  158. pieces_ = []
  159. for i, t in enumerate(pieces):
  160. if len(t) < 5:
  161. continue
  162. idx.append(i)
  163. pieces_.append(t)
  164. logging.debug("{} => {}".format(answer, pieces_))
  165. if not pieces_:
  166. return answer, set([])
  167. ans_v, _ = embd_mdl.encode(pieces_)
  168. assert len(ans_v[0]) == len(chunk_v[0]), "The dimension of query and chunk do not match: {} vs. {}".format(
  169. len(ans_v[0]), len(chunk_v[0]))
  170. chunks_tks = [rag_tokenizer.tokenize(self.qryr.rmWWW(ck)).split()
  171. for ck in chunks]
  172. cites = {}
  173. thr = 0.63
  174. while thr>0.3 and len(cites.keys()) == 0 and pieces_ and chunks_tks:
  175. for i, a in enumerate(pieces_):
  176. sim, tksim, vtsim = self.qryr.hybrid_similarity(ans_v[i],
  177. chunk_v,
  178. rag_tokenizer.tokenize(
  179. self.qryr.rmWWW(pieces_[i])).split(),
  180. chunks_tks,
  181. tkweight, vtweight)
  182. mx = np.max(sim) * 0.99
  183. logging.debug("{} SIM: {}".format(pieces_[i], mx))
  184. if mx < thr:
  185. continue
  186. cites[idx[i]] = list(
  187. set([str(ii) for ii in range(len(chunk_v)) if sim[ii] > mx]))[:4]
  188. thr *= 0.8
  189. res = ""
  190. seted = set([])
  191. for i, p in enumerate(pieces):
  192. res += p
  193. if i not in idx:
  194. continue
  195. if i not in cites:
  196. continue
  197. for c in cites[i]:
  198. assert int(c) < len(chunk_v)
  199. for c in cites[i]:
  200. if c in seted:
  201. continue
  202. res += f" ##{c}$$"
  203. seted.add(c)
  204. return res, seted
  205. def rerank(self, sres, query, tkweight=0.3,
  206. vtweight=0.7, cfield="content_ltks"):
  207. _, keywords = self.qryr.question(query)
  208. vector_size = len(sres.query_vector)
  209. vector_column = f"q_{vector_size}_vec"
  210. zero_vector = [0.0] * vector_size
  211. ins_embd = []
  212. for chunk_id in sres.ids:
  213. vector = sres.field[chunk_id].get(vector_column, zero_vector)
  214. if isinstance(vector, str):
  215. vector = [float(v) for v in vector.split("\t")]
  216. ins_embd.append(vector)
  217. if not ins_embd:
  218. return [], [], []
  219. for i in sres.ids:
  220. if isinstance(sres.field[i].get("important_kwd", []), str):
  221. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  222. ins_tw = []
  223. for i in sres.ids:
  224. content_ltks = sres.field[i][cfield].split()
  225. title_tks = [t for t in sres.field[i].get("title_tks", "").split() if t]
  226. important_kwd = sres.field[i].get("important_kwd", [])
  227. tks = content_ltks + title_tks + important_kwd
  228. ins_tw.append(tks)
  229. sim, tksim, vtsim = self.qryr.hybrid_similarity(sres.query_vector,
  230. ins_embd,
  231. keywords,
  232. ins_tw, tkweight, vtweight)
  233. return sim, tksim, vtsim
  234. def rerank_by_model(self, rerank_mdl, sres, query, tkweight=0.3,
  235. vtweight=0.7, cfield="content_ltks"):
  236. _, keywords = self.qryr.question(query)
  237. for i in sres.ids:
  238. if isinstance(sres.field[i].get("important_kwd", []), str):
  239. sres.field[i]["important_kwd"] = [sres.field[i]["important_kwd"]]
  240. ins_tw = []
  241. for i in sres.ids:
  242. content_ltks = sres.field[i][cfield].split()
  243. title_tks = [t for t in sres.field[i].get("title_tks", "").split() if t]
  244. important_kwd = sres.field[i].get("important_kwd", [])
  245. tks = content_ltks + title_tks + important_kwd
  246. ins_tw.append(tks)
  247. tksim = self.qryr.token_similarity(keywords, ins_tw)
  248. vtsim,_ = rerank_mdl.similarity(query, [rmSpace(" ".join(tks)) for tks in ins_tw])
  249. return tkweight*np.array(tksim) + vtweight*vtsim, tksim, vtsim
  250. def hybrid_similarity(self, ans_embd, ins_embd, ans, inst):
  251. return self.qryr.hybrid_similarity(ans_embd,
  252. ins_embd,
  253. rag_tokenizer.tokenize(ans).split(),
  254. rag_tokenizer.tokenize(inst).split())
  255. def retrieval(self, question, embd_mdl, tenant_ids, kb_ids, page, page_size, similarity_threshold=0.2,
  256. vector_similarity_weight=0.3, top=1024, doc_ids=None, aggs=True, rerank_mdl=None, highlight=False):
  257. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  258. if not question:
  259. return ranks
  260. RERANK_PAGE_LIMIT = 3
  261. req = {"kb_ids": kb_ids, "doc_ids": doc_ids, "size": max(page_size*RERANK_PAGE_LIMIT, 128),
  262. "question": question, "vector": True, "topk": top,
  263. "similarity": similarity_threshold,
  264. "available_int": 1}
  265. if page > RERANK_PAGE_LIMIT:
  266. req["page"] = page
  267. req["size"] = page_size
  268. if isinstance(tenant_ids, str):
  269. tenant_ids = tenant_ids.split(",")
  270. sres = self.search(req, [index_name(tid) for tid in tenant_ids], kb_ids, embd_mdl, highlight)
  271. ranks["total"] = sres.total
  272. if page <= RERANK_PAGE_LIMIT:
  273. if rerank_mdl:
  274. sim, tsim, vsim = self.rerank_by_model(rerank_mdl,
  275. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  276. else:
  277. sim, tsim, vsim = self.rerank(
  278. sres, question, 1 - vector_similarity_weight, vector_similarity_weight)
  279. idx = np.argsort(sim * -1)[(page-1)*page_size:page*page_size]
  280. else:
  281. sim = tsim = vsim = [1]*len(sres.ids)
  282. idx = list(range(len(sres.ids)))
  283. dim = len(sres.query_vector)
  284. vector_column = f"q_{dim}_vec"
  285. zero_vector = [0.0] * dim
  286. for i in idx:
  287. if sim[i] < similarity_threshold:
  288. break
  289. if len(ranks["chunks"]) >= page_size:
  290. if aggs:
  291. continue
  292. break
  293. id = sres.ids[i]
  294. chunk = sres.field[id]
  295. dnm = chunk["docnm_kwd"]
  296. did = chunk["doc_id"]
  297. position_list = chunk.get("position_list", "[]")
  298. if not position_list:
  299. position_list = "[]"
  300. d = {
  301. "chunk_id": id,
  302. "content_ltks": chunk["content_ltks"],
  303. "content_with_weight": chunk["content_with_weight"],
  304. "doc_id": chunk["doc_id"],
  305. "docnm_kwd": dnm,
  306. "kb_id": chunk["kb_id"],
  307. "important_kwd": chunk.get("important_kwd", []),
  308. "image_id": chunk.get("img_id", ""),
  309. "similarity": sim[i],
  310. "vector_similarity": vsim[i],
  311. "term_similarity": tsim[i],
  312. "vector": chunk.get(vector_column, zero_vector),
  313. "positions": json.loads(position_list)
  314. }
  315. if highlight:
  316. if id in sres.highlight:
  317. d["highlight"] = rmSpace(sres.highlight[id])
  318. else:
  319. d["highlight"] = d["content_with_weight"]
  320. ranks["chunks"].append(d)
  321. if dnm not in ranks["doc_aggs"]:
  322. ranks["doc_aggs"][dnm] = {"doc_id": did, "count": 0}
  323. ranks["doc_aggs"][dnm]["count"] += 1
  324. ranks["doc_aggs"] = [{"doc_name": k,
  325. "doc_id": v["doc_id"],
  326. "count": v["count"]} for k,
  327. v in sorted(ranks["doc_aggs"].items(),
  328. key=lambda x:x[1]["count"] * -1)]
  329. return ranks
  330. def sql_retrieval(self, sql, fetch_size=128, format="json"):
  331. tbl = self.dataStore.sql(sql, fetch_size, format)
  332. return tbl
  333. def chunk_list(self, doc_id: str, tenant_id: str, kb_ids: list[str], max_count=1024, fields=["docnm_kwd", "content_with_weight", "img_id"]):
  334. condition = {"doc_id": doc_id}
  335. res = self.dataStore.search(fields, [], condition, [], OrderByExpr(), 0, max_count, index_name(tenant_id), kb_ids)
  336. dict_chunks = self.dataStore.getFields(res, fields)
  337. return dict_chunks.values()