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

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