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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. #
  2. # Copyright 2019 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 hashlib
  17. import re
  18. import numpy as np
  19. from flask import request
  20. from flask_login import login_required, current_user
  21. from rag.nlp import search, huqie
  22. from rag.utils import ELASTICSEARCH, rmSpace
  23. from api.db import LLMType
  24. from api.db.services import duplicate_name
  25. from api.db.services.kb_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
  31. from api.utils.api_utils import get_json_result
  32. retrival = search.Dealer(ELASTICSEARCH)
  33. @manager.route('/list', methods=['POST'])
  34. @login_required
  35. @validate_request("doc_id")
  36. def list():
  37. req = request.json
  38. doc_id = req["doc_id"]
  39. page = int(req.get("page", 1))
  40. size = int(req.get("size", 30))
  41. question = req.get("keywords", "")
  42. try:
  43. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  44. if not tenant_id: return get_data_error_result(retmsg="Tenant not found!")
  45. query = {
  46. "doc_ids": [doc_id], "page": page, "size": size, "question": question
  47. }
  48. if "available_int" in req: query["available_int"] = int(req["available_int"])
  49. sres = retrival.search(query, search.index_name(tenant_id))
  50. res = {"total": sres.total, "chunks": []}
  51. for id in sres.ids:
  52. d = {
  53. "chunk_id": id,
  54. "content_ltks": rmSpace(sres.highlight[id]) if question else sres.field[id]["content_ltks"],
  55. "doc_id": sres.field[id]["doc_id"],
  56. "docnm_kwd": sres.field[id]["docnm_kwd"],
  57. "important_kwd": sres.field[id].get("important_kwd", []),
  58. "img_id": sres.field[id].get("img_id", ""),
  59. "available_int": sres.field[id].get("available_int", 1),
  60. }
  61. res["chunks"].append(d)
  62. return get_json_result(data=res)
  63. except Exception as e:
  64. if str(e).find("not_found") > 0:
  65. return get_json_result(data=False, retmsg=f'Index not found!',
  66. retcode=RetCode.DATA_ERROR)
  67. return server_error_response(e)
  68. @manager.route('/get', methods=['GET'])
  69. @login_required
  70. def get():
  71. chunk_id = request.args["chunk_id"]
  72. try:
  73. tenants = UserTenantService.query(user_id=current_user.id)
  74. if not tenants:
  75. return get_data_error_result(retmsg="Tenant not found!")
  76. res = ELASTICSEARCH.get(chunk_id, search.index_name(tenants[0].tenant_id))
  77. if not res.get("found"):return server_error_response("Chunk not found")
  78. id = res["_id"]
  79. res = res["_source"]
  80. res["chunk_id"] = id
  81. k = []
  82. for n in res.keys():
  83. if re.search(r"(_vec$|_sm_)", n):
  84. k.append(n)
  85. if re.search(r"(_tks|_ltks)", n):
  86. res[n] = rmSpace(res[n])
  87. for n in k: del res[n]
  88. return get_json_result(data=res)
  89. except Exception as e:
  90. if str(e).find("NotFoundError") >= 0:
  91. return get_json_result(data=False, retmsg=f'Chunk not found!',
  92. retcode=RetCode.DATA_ERROR)
  93. return server_error_response(e)
  94. @manager.route('/set', methods=['POST'])
  95. @login_required
  96. @validate_request("doc_id", "chunk_id", "content_ltks", "important_kwd", "docnm_kwd")
  97. def set():
  98. req = request.json
  99. d = {"id": req["chunk_id"]}
  100. d["content_ltks"] = huqie.qie(req["content_ltks"])
  101. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  102. d["important_kwd"] = req["important_kwd"]
  103. d["important_tks"] = huqie.qie(" ".join(req["important_kwd"]))
  104. if "available_int" in req: d["available_int"] = req["available_int"]
  105. try:
  106. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  107. if not tenant_id: return get_data_error_result(retmsg="Tenant not found!")
  108. embd_mdl = TenantLLMService.model_instance(tenant_id, LLMType.EMBEDDING.value)
  109. v, c = embd_mdl.encode([req["docnm_kwd"], req["content_ltks"]])
  110. v = 0.1 * v[0] + 0.9 * v[1]
  111. d["q_%d_vec"%len(v)] = v.tolist()
  112. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  113. return get_json_result(data=True)
  114. except Exception as e:
  115. return server_error_response(e)
  116. @manager.route('/switch', methods=['POST'])
  117. @login_required
  118. @validate_request("chunk_ids", "available_int", "doc_id")
  119. def switch():
  120. req = request.json
  121. try:
  122. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  123. if not tenant_id: return get_data_error_result(retmsg="Tenant not found!")
  124. if not ELASTICSEARCH.upsert([{"id": i, "available_int": int(req["available_int"])} for i in req["chunk_ids"]],
  125. search.index_name(tenant_id)):
  126. return get_data_error_result(retmsg="Index updating failure")
  127. return get_json_result(data=True)
  128. except Exception as e:
  129. return server_error_response(e)
  130. @manager.route('/create', methods=['POST'])
  131. @login_required
  132. @validate_request("doc_id", "content_ltks", "important_kwd")
  133. def create():
  134. req = request.json
  135. md5 = hashlib.md5()
  136. md5.update((req["content_ltks"] + req["doc_id"]).encode("utf-8"))
  137. chunck_id = md5.hexdigest()
  138. d = {"id": chunck_id, "content_ltks": huqie.qie(req["content_ltks"])}
  139. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  140. d["important_kwd"] = req["important_kwd"]
  141. d["important_tks"] = huqie.qie(" ".join(req["important_kwd"]))
  142. try:
  143. e, doc = DocumentService.get_by_id(req["doc_id"])
  144. if not e: return get_data_error_result(retmsg="Document not found!")
  145. d["kb_id"] = [doc.kb_id]
  146. d["docnm_kwd"] = doc.name
  147. d["doc_id"] = doc.id
  148. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  149. if not tenant_id: return get_data_error_result(retmsg="Tenant not found!")
  150. embd_mdl = TenantLLMService.model_instance(tenant_id, LLMType.EMBEDDING.value)
  151. v, c = embd_mdl.encode([doc.name, req["content_ltks"]])
  152. DocumentService.increment_chunk_num(req["doc_id"], doc.kb_id, c, 1, 0)
  153. v = 0.1 * v[0] + 0.9 * v[1]
  154. d["q_%d_vec"%len(v)] = v.tolist()
  155. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  156. return get_json_result(data={"chunk_id": chunck_id})
  157. except Exception as e:
  158. return server_error_response(e)
  159. @manager.route('/retrieval_test', methods=['POST'])
  160. @login_required
  161. @validate_request("kb_id", "question")
  162. def retrieval_test():
  163. req = request.json
  164. page = int(req.get("page", 1))
  165. size = int(req.get("size", 30))
  166. question = req["question"]
  167. kb_id = req["kb_id"]
  168. doc_ids = req.get("doc_ids", [])
  169. similarity_threshold = float(req.get("similarity_threshold", 0.4))
  170. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  171. top = int(req.get("top", 1024))
  172. try:
  173. e, kb = KnowledgebaseService.get_by_id(kb_id)
  174. if not e:
  175. return get_data_error_result(retmsg="Knowledgebase not found!")
  176. embd_mdl = TenantLLMService.model_instance(kb.tenant_id, LLMType.EMBEDDING.value)
  177. sres = retrival.search({"kb_ids": [kb_id], "doc_ids": doc_ids, "size": top,
  178. "question": question, "vector": True,
  179. "similarity": similarity_threshold},
  180. search.index_name(kb.tenant_id),
  181. embd_mdl)
  182. sim, tsim, vsim = retrival.rerank(sres, question, 1-vector_similarity_weight, vector_similarity_weight)
  183. idx = np.argsort(sim*-1)
  184. ranks = {"total": 0, "chunks": [], "doc_aggs": {}}
  185. start_idx = (page-1)*size
  186. for i in idx:
  187. ranks["total"] += 1
  188. if sim[i] < similarity_threshold: break
  189. start_idx -= 1
  190. if start_idx >= 0:continue
  191. if len(ranks["chunks"]) == size:continue
  192. id = sres.ids[i]
  193. dnm = sres.field[id]["docnm_kwd"]
  194. d = {
  195. "chunk_id": id,
  196. "content_ltks": sres.field[id]["content_ltks"],
  197. "doc_id": sres.field[id]["doc_id"],
  198. "docnm_kwd": dnm,
  199. "kb_id": sres.field[id]["kb_id"],
  200. "important_kwd": sres.field[id].get("important_kwd", []),
  201. "img_id": sres.field[id].get("img_id", ""),
  202. "similarity": sim[i],
  203. "vector_similarity": vsim[i],
  204. "term_similarity": tsim[i]
  205. }
  206. ranks["chunks"].append(d)
  207. if dnm not in ranks["doc_aggs"]:ranks["doc_aggs"][dnm] = 0
  208. ranks["doc_aggs"][dnm] += 1
  209. return get_json_result(data=ranks)
  210. except Exception as e:
  211. if str(e).find("not_found") > 0:
  212. return get_json_result(data=False, retmsg=f'Index not found!',
  213. retcode=RetCode.DATA_ERROR)
  214. return server_error_response(e)