Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

chunk_app.py 15KB

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