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.

chunk_app.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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 datetime
  17. import json
  18. from flask import request
  19. from flask_login import login_required, current_user
  20. from api.db.services.dialog_service import keyword_extraction
  21. from rag.app.qa import rmPrefix, beAdoc
  22. from rag.nlp import search, rag_tokenizer
  23. from rag.utils import rmSpace
  24. from api.db import LLMType, ParserType
  25. from api.db.services.knowledgebase_service import KnowledgebaseService
  26. from api.db.services.llm_service import LLMBundle
  27. from api.db.services.user_service import UserTenantService
  28. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  29. from api.db.services.document_service import DocumentService
  30. from api import settings
  31. from api.utils.api_utils import get_json_result
  32. import hashlib
  33. import re
  34. @manager.route('/list', methods=['POST'])
  35. @login_required
  36. @validate_request("doc_id")
  37. def list_chunk():
  38. req = request.json
  39. doc_id = req["doc_id"]
  40. page = int(req.get("page", 1))
  41. size = int(req.get("size", 30))
  42. question = req.get("keywords", "")
  43. try:
  44. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  45. if not tenant_id:
  46. return get_data_error_result(message="Tenant not found!")
  47. e, doc = DocumentService.get_by_id(doc_id)
  48. if not e:
  49. return get_data_error_result(message="Document not found!")
  50. kb_ids = KnowledgebaseService.get_kb_ids(tenant_id)
  51. query = {
  52. "doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
  53. }
  54. if "available_int" in req:
  55. query["available_int"] = int(req["available_int"])
  56. sres = settings.retrievaler.search(query, search.index_name(tenant_id), kb_ids, highlight=True)
  57. res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
  58. for id in sres.ids:
  59. d = {
  60. "chunk_id": id,
  61. "content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[
  62. id].get(
  63. "content_with_weight", ""),
  64. "doc_id": sres.field[id]["doc_id"],
  65. "docnm_kwd": sres.field[id]["docnm_kwd"],
  66. "important_kwd": sres.field[id].get("important_kwd", []),
  67. "image_id": sres.field[id].get("img_id", ""),
  68. "available_int": sres.field[id].get("available_int", 1),
  69. "positions": json.loads(sres.field[id].get("position_list", "[]")),
  70. }
  71. assert isinstance(d["positions"], list)
  72. assert len(d["positions"]) == 0 or (isinstance(d["positions"][0], list) and len(d["positions"][0]) == 5)
  73. res["chunks"].append(d)
  74. return get_json_result(data=res)
  75. except Exception as e:
  76. if str(e).find("not_found") > 0:
  77. return get_json_result(data=False, message='No chunk found!',
  78. code=settings.RetCode.DATA_ERROR)
  79. return server_error_response(e)
  80. @manager.route('/get', methods=['GET'])
  81. @login_required
  82. def get():
  83. chunk_id = request.args["chunk_id"]
  84. try:
  85. tenants = UserTenantService.query(user_id=current_user.id)
  86. if not tenants:
  87. return get_data_error_result(message="Tenant not found!")
  88. tenant_id = tenants[0].tenant_id
  89. kb_ids = KnowledgebaseService.get_kb_ids(tenant_id)
  90. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), kb_ids)
  91. if chunk is None:
  92. return server_error_response("Chunk not found")
  93. k = []
  94. for n in chunk.keys():
  95. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  96. k.append(n)
  97. for n in k:
  98. del chunk[n]
  99. return get_json_result(data=chunk)
  100. except Exception as e:
  101. if str(e).find("NotFoundError") >= 0:
  102. return get_json_result(data=False, message='Chunk not found!',
  103. code=settings.RetCode.DATA_ERROR)
  104. return server_error_response(e)
  105. @manager.route('/set', methods=['POST'])
  106. @login_required
  107. @validate_request("doc_id", "chunk_id", "content_with_weight",
  108. "important_kwd")
  109. def set():
  110. req = request.json
  111. d = {
  112. "id": req["chunk_id"],
  113. "content_with_weight": req["content_with_weight"]}
  114. d["content_ltks"] = rag_tokenizer.tokenize(req["content_with_weight"])
  115. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  116. d["important_kwd"] = req["important_kwd"]
  117. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_kwd"]))
  118. if "available_int" in req:
  119. d["available_int"] = req["available_int"]
  120. try:
  121. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  122. if not tenant_id:
  123. return get_data_error_result(message="Tenant not found!")
  124. embd_id = DocumentService.get_embd_id(req["doc_id"])
  125. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embd_id)
  126. e, doc = DocumentService.get_by_id(req["doc_id"])
  127. if not e:
  128. return get_data_error_result(message="Document not found!")
  129. if doc.parser_id == ParserType.QA:
  130. arr = [
  131. t for t in re.split(
  132. r"[\n\t]",
  133. req["content_with_weight"]) if len(t) > 1]
  134. if len(arr) != 2:
  135. return get_data_error_result(
  136. message="Q&A must be separated by TAB/ENTER key.")
  137. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  138. d = beAdoc(d, arr[0], arr[1], not any(
  139. [rag_tokenizer.is_chinese(t) for t in q + a]))
  140. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  141. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  142. d["q_%d_vec" % len(v)] = v.tolist()
  143. settings.docStoreConn.insert([d], search.index_name(tenant_id), doc.kb_id)
  144. return get_json_result(data=True)
  145. except Exception as e:
  146. return server_error_response(e)
  147. @manager.route('/switch', methods=['POST'])
  148. @login_required
  149. @validate_request("chunk_ids", "available_int", "doc_id")
  150. def switch():
  151. req = request.json
  152. try:
  153. e, doc = DocumentService.get_by_id(req["doc_id"])
  154. if not e:
  155. return get_data_error_result(message="Document not found!")
  156. if not settings.docStoreConn.update({"id": req["chunk_ids"]}, {"available_int": int(req["available_int"])},
  157. search.index_name(doc.tenant_id), doc.kb_id):
  158. return get_data_error_result(message="Index updating failure")
  159. return get_json_result(data=True)
  160. except Exception as e:
  161. return server_error_response(e)
  162. @manager.route('/rm', methods=['POST'])
  163. @login_required
  164. @validate_request("chunk_ids", "doc_id")
  165. def rm():
  166. req = request.json
  167. try:
  168. e, doc = DocumentService.get_by_id(req["doc_id"])
  169. if not e:
  170. return get_data_error_result(message="Document not found!")
  171. if not settings.docStoreConn.delete({"id": req["chunk_ids"]}, search.index_name(current_user.id), doc.kb_id):
  172. return get_data_error_result(message="Index updating failure")
  173. deleted_chunk_ids = req["chunk_ids"]
  174. chunk_number = len(deleted_chunk_ids)
  175. DocumentService.decrement_chunk_num(doc.id, doc.kb_id, 1, chunk_number, 0)
  176. return get_json_result(data=True)
  177. except Exception as e:
  178. return server_error_response(e)
  179. @manager.route('/create', methods=['POST'])
  180. @login_required
  181. @validate_request("doc_id", "content_with_weight")
  182. def create():
  183. req = request.json
  184. md5 = hashlib.md5()
  185. md5.update((req["content_with_weight"] + req["doc_id"]).encode("utf-8"))
  186. chunck_id = md5.hexdigest()
  187. d = {"id": chunck_id, "content_ltks": rag_tokenizer.tokenize(req["content_with_weight"]),
  188. "content_with_weight": req["content_with_weight"]}
  189. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  190. d["important_kwd"] = req.get("important_kwd", [])
  191. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req.get("important_kwd", [])))
  192. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  193. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  194. try:
  195. e, doc = DocumentService.get_by_id(req["doc_id"])
  196. if not e:
  197. return get_data_error_result(message="Document not found!")
  198. d["kb_id"] = [doc.kb_id]
  199. d["docnm_kwd"] = doc.name
  200. d["doc_id"] = doc.id
  201. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  202. if not tenant_id:
  203. return get_data_error_result(message="Tenant not found!")
  204. embd_id = DocumentService.get_embd_id(req["doc_id"])
  205. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING.value, embd_id)
  206. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  207. v = 0.1 * v[0] + 0.9 * v[1]
  208. d["q_%d_vec" % len(v)] = v.tolist()
  209. settings.docStoreConn.insert([d], search.index_name(tenant_id), doc.kb_id)
  210. DocumentService.increment_chunk_num(
  211. doc.id, doc.kb_id, c, 1, 0)
  212. return get_json_result(data={"chunk_id": chunck_id})
  213. except Exception as e:
  214. return server_error_response(e)
  215. @manager.route('/retrieval_test', methods=['POST'])
  216. @login_required
  217. @validate_request("kb_id", "question")
  218. def retrieval_test():
  219. req = request.json
  220. page = int(req.get("page", 1))
  221. size = int(req.get("size", 30))
  222. question = req["question"]
  223. kb_ids = req["kb_id"]
  224. if isinstance(kb_ids, str):
  225. kb_ids = [kb_ids]
  226. doc_ids = req.get("doc_ids", [])
  227. similarity_threshold = float(req.get("similarity_threshold", 0.0))
  228. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  229. top = int(req.get("top_k", 1024))
  230. try:
  231. tenants = UserTenantService.query(user_id=current_user.id)
  232. for kb_id in kb_ids:
  233. for tenant in tenants:
  234. if KnowledgebaseService.query(
  235. tenant_id=tenant.tenant_id, id=kb_id):
  236. break
  237. else:
  238. return get_json_result(
  239. data=False, message='Only owner of knowledgebase authorized for this operation.',
  240. code=settings.RetCode.OPERATING_ERROR)
  241. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  242. if not e:
  243. return get_data_error_result(message="Knowledgebase not found!")
  244. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  245. rerank_mdl = None
  246. if req.get("rerank_id"):
  247. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
  248. if req.get("keyword", False):
  249. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  250. question += keyword_extraction(chat_mdl, question)
  251. retr = settings.retrievaler if kb.parser_id != ParserType.KG else settings.kg_retrievaler
  252. ranks = retr.retrieval(question, embd_mdl, kb.tenant_id, kb_ids, page, size,
  253. similarity_threshold, vector_similarity_weight, top,
  254. doc_ids, rerank_mdl=rerank_mdl, highlight=req.get("highlight"))
  255. for c in ranks["chunks"]:
  256. if "vector" in c:
  257. del c["vector"]
  258. return get_json_result(data=ranks)
  259. except Exception as e:
  260. if str(e).find("not_found") > 0:
  261. return get_json_result(data=False, message='No chunk found! Check the chunk status please!',
  262. code=settings.RetCode.DATA_ERROR)
  263. return server_error_response(e)
  264. @manager.route('/knowledge_graph', methods=['GET'])
  265. @login_required
  266. def knowledge_graph():
  267. doc_id = request.args["doc_id"]
  268. tenant_id = DocumentService.get_tenant_id(doc_id)
  269. kb_ids = KnowledgebaseService.get_kb_ids(tenant_id)
  270. req = {
  271. "doc_ids": [doc_id],
  272. "knowledge_graph_kwd": ["graph", "mind_map"]
  273. }
  274. sres = settings.retrievaler.search(req, search.index_name(tenant_id), kb_ids)
  275. obj = {"graph": {}, "mind_map": {}}
  276. for id in sres.ids[:2]:
  277. ty = sres.field[id]["knowledge_graph_kwd"]
  278. try:
  279. content_json = json.loads(sres.field[id]["content_with_weight"])
  280. except Exception:
  281. continue
  282. if ty == 'mind_map':
  283. node_dict = {}
  284. def repeat_deal(content_json, node_dict):
  285. if 'id' in content_json:
  286. if content_json['id'] in node_dict:
  287. node_name = content_json['id']
  288. content_json['id'] += f"({node_dict[content_json['id']]})"
  289. node_dict[node_name] += 1
  290. else:
  291. node_dict[content_json['id']] = 1
  292. if 'children' in content_json and content_json['children']:
  293. for item in content_json['children']:
  294. repeat_deal(item, node_dict)
  295. repeat_deal(content_json, node_dict)
  296. obj[ty] = content_json
  297. return get_json_result(data=obj)