Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

chunk_app.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 api.db.services.dialog_service import keyword_extraction
  23. from rag.app.qa import rmPrefix, beAdoc
  24. from rag.nlp import search, rag_tokenizer
  25. from rag.utils.es_conn import ELASTICSEARCH
  26. from rag.utils import rmSpace
  27. from api.db import LLMType, ParserType
  28. from api.db.services.knowledgebase_service import KnowledgebaseService
  29. from api.db.services.llm_service import LLMBundle
  30. from api.db.services.user_service import UserTenantService
  31. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  32. from api.db.services.document_service import DocumentService
  33. from api.settings import RetCode, retrievaler, kg_retrievaler
  34. from api.utils.api_utils import get_json_result
  35. import hashlib
  36. import re
  37. @manager.route('/list', methods=['POST'])
  38. @login_required
  39. @validate_request("doc_id")
  40. def list_chunk():
  41. req = request.json
  42. doc_id = req["doc_id"]
  43. page = int(req.get("page", 1))
  44. size = int(req.get("size", 30))
  45. question = req.get("keywords", "")
  46. try:
  47. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  48. if not tenant_id:
  49. return get_data_error_result(retmsg="Tenant not found!")
  50. e, doc = DocumentService.get_by_id(doc_id)
  51. if not e:
  52. return get_data_error_result(retmsg="Document not found!")
  53. query = {
  54. "doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
  55. }
  56. if "available_int" in req:
  57. query["available_int"] = int(req["available_int"])
  58. sres = retrievaler.search(query, search.index_name(tenant_id), highlight=True)
  59. res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
  60. for id in sres.ids:
  61. d = {
  62. "chunk_id": id,
  63. "content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[
  64. id].get(
  65. "content_with_weight", ""),
  66. "doc_id": sres.field[id]["doc_id"],
  67. "docnm_kwd": sres.field[id]["docnm_kwd"],
  68. "important_kwd": sres.field[id].get("important_kwd", []),
  69. "img_id": sres.field[id].get("img_id", ""),
  70. "available_int": sres.field[id].get("available_int", 1),
  71. "positions": sres.field[id].get("position_int", "").split("\t")
  72. }
  73. if len(d["positions"]) % 5 == 0:
  74. poss = []
  75. for i in range(0, len(d["positions"]), 5):
  76. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  77. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  78. d["positions"] = poss
  79. res["chunks"].append(d)
  80. return get_json_result(data=res)
  81. except Exception as e:
  82. if str(e).find("not_found") > 0:
  83. return get_json_result(data=False, retmsg=f'No chunk found!',
  84. retcode=RetCode.DATA_ERROR)
  85. return server_error_response(e)
  86. @manager.route('/get', methods=['GET'])
  87. @login_required
  88. def get():
  89. chunk_id = request.args["chunk_id"]
  90. try:
  91. tenants = UserTenantService.query(user_id=current_user.id)
  92. if not tenants:
  93. return get_data_error_result(retmsg="Tenant not found!")
  94. res = ELASTICSEARCH.get(
  95. chunk_id, search.index_name(
  96. tenants[0].tenant_id))
  97. if not res.get("found"):
  98. return server_error_response("Chunk not found")
  99. id = res["_id"]
  100. res = res["_source"]
  101. res["chunk_id"] = id
  102. k = []
  103. for n in res.keys():
  104. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  105. k.append(n)
  106. for n in k:
  107. del res[n]
  108. return get_json_result(data=res)
  109. except Exception as e:
  110. if str(e).find("NotFoundError") >= 0:
  111. return get_json_result(data=False, retmsg=f'Chunk not found!',
  112. retcode=RetCode.DATA_ERROR)
  113. return server_error_response(e)
  114. @manager.route('/set', methods=['POST'])
  115. @login_required
  116. @validate_request("doc_id", "chunk_id", "content_with_weight",
  117. "important_kwd")
  118. def set():
  119. req = request.json
  120. d = {
  121. "id": req["chunk_id"],
  122. "content_with_weight": req["content_with_weight"]}
  123. d["content_ltks"] = rag_tokenizer.tokenize(req["content_with_weight"])
  124. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  125. d["important_kwd"] = req["important_kwd"]
  126. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_kwd"]))
  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(retmsg="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(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 = LLMBundle(tenant_id, LLMType.EMBEDDING.value, embd_id)
  216. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  217. v = 0.1 * v[0] + 0.9 * v[1]
  218. d["q_%d_vec" % len(v)] = v.tolist()
  219. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  220. DocumentService.increment_chunk_num(
  221. doc.id, doc.kb_id, c, 1, 0)
  222. return get_json_result(data={"chunk_id": chunck_id})
  223. except Exception as e:
  224. return server_error_response(e)
  225. @manager.route('/retrieval_test', methods=['POST'])
  226. @login_required
  227. @validate_request("kb_id", "question")
  228. def retrieval_test():
  229. req = request.json
  230. page = int(req.get("page", 1))
  231. size = int(req.get("size", 30))
  232. question = req["question"]
  233. kb_id = req["kb_id"]
  234. if isinstance(kb_id, str): kb_id = [kb_id]
  235. doc_ids = req.get("doc_ids", [])
  236. similarity_threshold = float(req.get("similarity_threshold", 0.0))
  237. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  238. top = int(req.get("top_k", 1024))
  239. try:
  240. tenants = UserTenantService.query(user_id=current_user.id)
  241. for kid in kb_id:
  242. for tenant in tenants:
  243. if KnowledgebaseService.query(
  244. tenant_id=tenant.tenant_id, id=kid):
  245. break
  246. else:
  247. return get_json_result(
  248. data=False, retmsg=f'Only owner of knowledgebase authorized for this operation.',
  249. retcode=RetCode.OPERATING_ERROR)
  250. e, kb = KnowledgebaseService.get_by_id(kb_id[0])
  251. if not e:
  252. return get_data_error_result(retmsg="Knowledgebase not found!")
  253. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  254. rerank_mdl = None
  255. if req.get("rerank_id"):
  256. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
  257. if req.get("keyword", False):
  258. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  259. question += keyword_extraction(chat_mdl, question)
  260. retr = retrievaler if kb.parser_id != ParserType.KG else kg_retrievaler
  261. ranks = retr.retrieval(question, embd_mdl, kb.tenant_id, kb_id, page, size,
  262. similarity_threshold, vector_similarity_weight, top,
  263. doc_ids, rerank_mdl=rerank_mdl, highlight=req.get("highlight"))
  264. for c in ranks["chunks"]:
  265. if "vector" in c:
  266. del c["vector"]
  267. return get_json_result(data=ranks)
  268. except Exception as e:
  269. if str(e).find("not_found") > 0:
  270. return get_json_result(data=False, retmsg=f'No chunk found! Check the chunk status please!',
  271. retcode=RetCode.DATA_ERROR)
  272. return server_error_response(e)
  273. @manager.route('/knowledge_graph', methods=['GET'])
  274. @login_required
  275. def knowledge_graph():
  276. doc_id = request.args["doc_id"]
  277. req = {
  278. "doc_ids":[doc_id],
  279. "knowledge_graph_kwd": ["graph", "mind_map"]
  280. }
  281. tenant_id = DocumentService.get_tenant_id(doc_id)
  282. sres = retrievaler.search(req, search.index_name(tenant_id))
  283. obj = {"graph": {}, "mind_map": {}}
  284. for id in sres.ids[:2]:
  285. ty = sres.field[id]["knowledge_graph_kwd"]
  286. try:
  287. content_json = json.loads(sres.field[id]["content_with_weight"])
  288. except Exception as e:
  289. continue
  290. if ty == 'mind_map':
  291. node_dict = {}
  292. def repeat_deal(content_json, node_dict):
  293. if 'id' in content_json:
  294. if content_json['id'] in node_dict:
  295. node_name = content_json['id']
  296. content_json['id'] += f"({node_dict[content_json['id']]})"
  297. node_dict[node_name] += 1
  298. else:
  299. node_dict[content_json['id']] = 1
  300. if 'children' in content_json and content_json['children']:
  301. for item in content_json['children']:
  302. repeat_deal(item, node_dict)
  303. repeat_deal(content_json, node_dict)
  304. obj[ty] = content_json
  305. return get_json_result(data=obj)