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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. from flask import request
  18. from flask_login import login_required, current_user
  19. from elasticsearch_dsl import Q
  20. from rag.app.qa import rmPrefix, beAdoc
  21. from rag.nlp import search, rag_tokenizer
  22. from rag.utils.es_conn import ELASTICSEARCH
  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 TenantLLMService
  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.settings import RetCode, retrievaler
  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():
  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(retmsg="Tenant not found!")
  47. e, doc = DocumentService.get_by_id(doc_id)
  48. if not e:
  49. return get_data_error_result(retmsg="Document not found!")
  50. query = {
  51. "doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
  52. }
  53. if "available_int" in req:
  54. query["available_int"] = int(req["available_int"])
  55. sres = retrievaler.search(query, search.index_name(tenant_id))
  56. res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
  57. for id in sres.ids:
  58. d = {
  59. "chunk_id": id,
  60. "content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[id].get(
  61. "content_with_weight", ""),
  62. "doc_id": sres.field[id]["doc_id"],
  63. "docnm_kwd": sres.field[id]["docnm_kwd"],
  64. "important_kwd": sres.field[id].get("important_kwd", []),
  65. "img_id": sres.field[id].get("img_id", ""),
  66. "available_int": sres.field[id].get("available_int", 1),
  67. "positions": sres.field[id].get("position_int", "").split("\t")
  68. }
  69. if len(d["positions"]) % 5 == 0:
  70. poss = []
  71. for i in range(0, len(d["positions"]), 5):
  72. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  73. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  74. d["positions"] = poss
  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, retmsg=f'No chunk found!',
  80. retcode=RetCode.DATA_ERROR)
  81. return server_error_response(e)
  82. @manager.route('/get', methods=['GET'])
  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(retmsg="Tenant not found!")
  90. res = ELASTICSEARCH.get(
  91. chunk_id, search.index_name(
  92. tenants[0].tenant_id))
  93. if not res.get("found"):
  94. return server_error_response("Chunk not found")
  95. id = res["_id"]
  96. res = res["_source"]
  97. res["chunk_id"] = id
  98. k = []
  99. for n in res.keys():
  100. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  101. k.append(n)
  102. for n in k:
  103. del res[n]
  104. return get_json_result(data=res)
  105. except Exception as e:
  106. if str(e).find("NotFoundError") >= 0:
  107. return get_json_result(data=False, retmsg=f'Chunk not found!',
  108. retcode=RetCode.DATA_ERROR)
  109. return server_error_response(e)
  110. @manager.route('/set', methods=['POST'])
  111. @login_required
  112. @validate_request("doc_id", "chunk_id", "content_with_weight",
  113. "important_kwd")
  114. def set():
  115. req = request.json
  116. d = {
  117. "id": req["chunk_id"],
  118. "content_with_weight": req["content_with_weight"]}
  119. d["content_ltks"] = rag_tokenizer.tokenize(req["content_with_weight"])
  120. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  121. d["important_kwd"] = req["important_kwd"]
  122. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_kwd"]))
  123. if "available_int" in req:
  124. d["available_int"] = req["available_int"]
  125. try:
  126. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  127. if not tenant_id:
  128. return get_data_error_result(retmsg="Tenant not found!")
  129. embd_mdl = TenantLLMService.model_instance(
  130. tenant_id, LLMType.EMBEDDING.value)
  131. e, doc = DocumentService.get_by_id(req["doc_id"])
  132. if not e:
  133. return get_data_error_result(retmsg="Document not found!")
  134. if doc.parser_id == ParserType.QA:
  135. arr = [
  136. t for t in re.split(
  137. r"[\n\t]",
  138. req["content_with_weight"]) if len(t) > 1]
  139. if len(arr) != 2:
  140. return get_data_error_result(
  141. retmsg="Q&A must be separated by TAB/ENTER key.")
  142. q, a = rmPrefix(arr[0]), rmPrefix[arr[1]]
  143. d = beAdoc(d, arr[0], arr[1], not any(
  144. [rag_tokenizer.is_chinese(t) for t in q + a]))
  145. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  146. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  147. d["q_%d_vec" % len(v)] = v.tolist()
  148. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  149. return get_json_result(data=True)
  150. except Exception as e:
  151. return server_error_response(e)
  152. @manager.route('/switch', methods=['POST'])
  153. @login_required
  154. @validate_request("chunk_ids", "available_int", "doc_id")
  155. def switch():
  156. req = request.json
  157. try:
  158. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  159. if not tenant_id:
  160. return get_data_error_result(retmsg="Tenant not found!")
  161. if not ELASTICSEARCH.upsert([{"id": i, "available_int": int(req["available_int"])} for i in req["chunk_ids"]],
  162. search.index_name(tenant_id)):
  163. return get_data_error_result(retmsg="Index updating failure")
  164. return get_json_result(data=True)
  165. except Exception as e:
  166. return server_error_response(e)
  167. @manager.route('/rm', methods=['POST'])
  168. @login_required
  169. @validate_request("chunk_ids")
  170. def rm():
  171. req = request.json
  172. try:
  173. if not ELASTICSEARCH.deleteByQuery(
  174. Q("ids", values=req["chunk_ids"]), search.index_name(current_user.id)):
  175. return get_data_error_result(retmsg="Index updating failure")
  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(retmsg="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(retmsg="Tenant not found!")
  204. embd_mdl = TenantLLMService.model_instance(
  205. tenant_id, LLMType.EMBEDDING.value)
  206. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  207. DocumentService.increment_chunk_num(req["doc_id"], doc.kb_id, c, 1, 0)
  208. v = 0.1 * v[0] + 0.9 * v[1]
  209. d["q_%d_vec" % len(v)] = v.tolist()
  210. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  211. return get_json_result(data={"chunk_id": chunck_id})
  212. except Exception as e:
  213. return server_error_response(e)
  214. @manager.route('/retrieval_test', methods=['POST'])
  215. @login_required
  216. @validate_request("kb_id", "question")
  217. def retrieval_test():
  218. req = request.json
  219. page = int(req.get("page", 1))
  220. size = int(req.get("size", 30))
  221. question = req["question"]
  222. kb_id = req["kb_id"]
  223. doc_ids = req.get("doc_ids", [])
  224. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  225. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  226. top = int(req.get("top_k", 1024))
  227. try:
  228. e, kb = KnowledgebaseService.get_by_id(kb_id)
  229. if not e:
  230. return get_data_error_result(retmsg="Knowledgebase not found!")
  231. embd_mdl = TenantLLMService.model_instance(
  232. kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  233. ranks = retrievaler.retrieval(question, embd_mdl, kb.tenant_id, [kb_id], page, size, similarity_threshold,
  234. vector_similarity_weight, top, doc_ids)
  235. for c in ranks["chunks"]:
  236. if "vector" in c:
  237. del c["vector"]
  238. return get_json_result(data=ranks)
  239. except Exception as e:
  240. if str(e).find("not_found") > 0:
  241. return get_json_result(data=False, retmsg=f'No chunk found! Check the chunk status please!',
  242. retcode=RetCode.DATA_ERROR)
  243. return server_error_response(e)