Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

doc.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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 pathlib
  17. import datetime
  18. from api.db.services.dialog_service import keyword_extraction
  19. from rag.app.qa import rmPrefix, beAdoc
  20. from rag.nlp import rag_tokenizer
  21. from api.db import LLMType, ParserType
  22. from api.db.services.llm_service import TenantLLMService
  23. from api.settings import kg_retrievaler
  24. import hashlib
  25. import re
  26. from api.utils.api_utils import token_required
  27. from api.db.db_models import Task
  28. from api.db.services.task_service import TaskService, queue_tasks
  29. from api.utils.api_utils import server_error_response
  30. from api.utils.api_utils import get_result, get_error_data_result
  31. from io import BytesIO
  32. from elasticsearch_dsl import Q
  33. from flask import request, send_file
  34. from api.db import FileSource, TaskStatus, FileType
  35. from api.db.db_models import File
  36. from api.db.services.document_service import DocumentService
  37. from api.db.services.file2document_service import File2DocumentService
  38. from api.db.services.file_service import FileService
  39. from api.db.services.knowledgebase_service import KnowledgebaseService
  40. from api.settings import RetCode, retrievaler
  41. from api.utils.api_utils import construct_json_result,get_parser_config
  42. from rag.nlp import search
  43. from rag.utils import rmSpace
  44. from rag.utils.es_conn import ELASTICSEARCH
  45. from rag.utils.storage_factory import STORAGE_IMPL
  46. import os
  47. @manager.route('/datasets/<dataset_id>/documents', methods=['POST'])
  48. @token_required
  49. def upload(dataset_id, tenant_id):
  50. if 'file' not in request.files:
  51. return get_error_data_result(
  52. retmsg='No file part!', retcode=RetCode.ARGUMENT_ERROR)
  53. file_objs = request.files.getlist('file')
  54. for file_obj in file_objs:
  55. if file_obj.filename == '':
  56. return get_result(
  57. retmsg='No file selected!', retcode=RetCode.ARGUMENT_ERROR)
  58. e, kb = KnowledgebaseService.get_by_id(dataset_id)
  59. if not e:
  60. raise LookupError(f"Can't find the dataset with ID {dataset_id}!")
  61. err, files = FileService.upload_document(kb, file_objs, tenant_id)
  62. if err:
  63. return get_result(
  64. retmsg="\n".join(err), retcode=RetCode.SERVER_ERROR)
  65. # rename key's name
  66. renamed_doc_list = []
  67. for file in files:
  68. doc = file[0]
  69. key_mapping = {
  70. "chunk_num": "chunk_count",
  71. "kb_id": "dataset_id",
  72. "token_num": "token_count",
  73. "parser_id": "chunk_method"
  74. }
  75. renamed_doc = {}
  76. for key, value in doc.items():
  77. new_key = key_mapping.get(key, key)
  78. renamed_doc[new_key] = value
  79. renamed_doc["run"] = "UNSTART"
  80. renamed_doc_list.append(renamed_doc)
  81. return get_result(data=renamed_doc_list)
  82. @manager.route('/datasets/<dataset_id>/documents/<document_id>', methods=['PUT'])
  83. @token_required
  84. def update_doc(tenant_id, dataset_id, document_id):
  85. req = request.json
  86. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  87. return get_error_data_result(retmsg="You don't own the dataset.")
  88. doc = DocumentService.query(kb_id=dataset_id, id=document_id)
  89. if not doc:
  90. return get_error_data_result(retmsg="The dataset doesn't own the document.")
  91. doc = doc[0]
  92. if "chunk_count" in req:
  93. if req["chunk_count"] != doc.chunk_num:
  94. return get_error_data_result(retmsg="Can't change `chunk_count`.")
  95. if "token_count" in req:
  96. if req["token_count"] != doc.token_num:
  97. return get_error_data_result(retmsg="Can't change `token_count`.")
  98. if "progress" in req:
  99. if req['progress'] != doc.progress:
  100. return get_error_data_result(retmsg="Can't change `progress`.")
  101. if "name" in req and req["name"] != doc.name:
  102. if pathlib.Path(req["name"].lower()).suffix != pathlib.Path(doc.name.lower()).suffix:
  103. return get_result(retmsg="The extension of file can't be changed", retcode=RetCode.ARGUMENT_ERROR)
  104. for d in DocumentService.query(name=req["name"], kb_id=doc.kb_id):
  105. if d.name == req["name"]:
  106. return get_error_data_result(
  107. retmsg="Duplicated document name in the same dataset.")
  108. if not DocumentService.update_by_id(
  109. document_id, {"name": req["name"]}):
  110. return get_error_data_result(
  111. retmsg="Database error (Document rename)!")
  112. informs = File2DocumentService.get_by_document_id(document_id)
  113. if informs:
  114. e, file = FileService.get_by_id(informs[0].file_id)
  115. FileService.update_by_id(file.id, {"name": req["name"]})
  116. if "parser_config" in req:
  117. DocumentService.update_parser_config(doc.id, req["parser_config"])
  118. if "chunk_method" in req:
  119. valid_chunk_method = {"naive","manual","qa","table","paper","book","laws","presentation","picture","one","knowledge_graph","email"}
  120. if req.get("chunk_method") not in valid_chunk_method:
  121. return get_error_data_result(f"`chunk_method` {req['chunk_method']} doesn't exist")
  122. if doc.parser_id.lower() == req["chunk_method"].lower():
  123. return get_result()
  124. if doc.type == FileType.VISUAL or re.search(
  125. r"\.(ppt|pptx|pages)$", doc.name):
  126. return get_error_data_result(retmsg="Not supported yet!")
  127. e = DocumentService.update_by_id(doc.id,
  128. {"parser_id": req["chunk_method"], "progress": 0, "progress_msg": "",
  129. "run": TaskStatus.UNSTART.value})
  130. if not e:
  131. return get_error_data_result(retmsg="Document not found!")
  132. req["parser_config"] = get_parser_config(req["chunk_method"], req.get("parser_config"))
  133. if doc.token_num > 0:
  134. e = DocumentService.increment_chunk_num(doc.id, doc.kb_id, doc.token_num * -1, doc.chunk_num * -1,
  135. doc.process_duation * -1)
  136. if not e:
  137. return get_error_data_result(retmsg="Document not found!")
  138. ELASTICSEARCH.deleteByQuery(
  139. Q("match", doc_id=doc.id), idxnm=search.index_name(tenant_id))
  140. return get_result()
  141. @manager.route('/datasets/<dataset_id>/documents/<document_id>', methods=['GET'])
  142. @token_required
  143. def download(tenant_id, dataset_id, document_id):
  144. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  145. return get_error_data_result(retmsg=f'You do not own the dataset {dataset_id}.')
  146. doc = DocumentService.query(kb_id=dataset_id, id=document_id)
  147. if not doc:
  148. return get_error_data_result(retmsg=f'The dataset not own the document {document_id}.')
  149. # The process of downloading
  150. doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
  151. file_stream = STORAGE_IMPL.get(doc_id, doc_location)
  152. if not file_stream:
  153. return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
  154. file = BytesIO(file_stream)
  155. # Use send_file with a proper filename and MIME type
  156. return send_file(
  157. file,
  158. as_attachment=True,
  159. download_name=doc[0].name,
  160. mimetype='application/octet-stream' # Set a default MIME type
  161. )
  162. @manager.route('/datasets/<dataset_id>/documents', methods=['GET'])
  163. @token_required
  164. def list_docs(dataset_id, tenant_id):
  165. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  166. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}. ")
  167. id = request.args.get("id")
  168. if not DocumentService.query(id=id,kb_id=dataset_id):
  169. return get_error_data_result(retmsg=f"You don't own the document {id}.")
  170. offset = int(request.args.get("offset", 1))
  171. keywords = request.args.get("keywords","")
  172. limit = int(request.args.get("limit", 1024))
  173. orderby = request.args.get("orderby", "create_time")
  174. if request.args.get("desc") == "False":
  175. desc = False
  176. else:
  177. desc = True
  178. docs, tol = DocumentService.get_list(dataset_id, offset, limit, orderby, desc, keywords, id)
  179. # rename key's name
  180. renamed_doc_list = []
  181. for doc in docs:
  182. key_mapping = {
  183. "chunk_num": "chunk_count",
  184. "kb_id": "dataset_id",
  185. "token_num": "token_count",
  186. "parser_id": "chunk_method"
  187. }
  188. run_mapping = {
  189. "0" :"UNSTART",
  190. "1":"RUNNING",
  191. "2":"CANCEL",
  192. "3":"DONE",
  193. "4":"FAIL"
  194. }
  195. renamed_doc = {}
  196. for key, value in doc.items():
  197. if key =="run":
  198. renamed_doc["run"]=run_mapping.get(str(value))
  199. new_key = key_mapping.get(key, key)
  200. renamed_doc[new_key] = value
  201. renamed_doc_list.append(renamed_doc)
  202. return get_result(data={"total": tol, "docs": renamed_doc_list})
  203. @manager.route('/datasets/<dataset_id>/documents', methods=['DELETE'])
  204. @token_required
  205. def delete(tenant_id,dataset_id):
  206. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  207. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}. ")
  208. req = request.json
  209. if not req:
  210. doc_ids=None
  211. else:
  212. doc_ids=req.get("ids")
  213. if not doc_ids:
  214. doc_list = []
  215. docs=DocumentService.query(kb_id=dataset_id)
  216. for doc in docs:
  217. doc_list.append(doc.id)
  218. else:
  219. doc_list=doc_ids
  220. root_folder = FileService.get_root_folder(tenant_id)
  221. pf_id = root_folder["id"]
  222. FileService.init_knowledgebase_docs(pf_id, tenant_id)
  223. errors = ""
  224. for doc_id in doc_list:
  225. try:
  226. e, doc = DocumentService.get_by_id(doc_id)
  227. if not e:
  228. return get_error_data_result(retmsg="Document not found!")
  229. tenant_id = DocumentService.get_tenant_id(doc_id)
  230. if not tenant_id:
  231. return get_error_data_result(retmsg="Tenant not found!")
  232. b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
  233. if not DocumentService.remove_document(doc, tenant_id):
  234. return get_error_data_result(
  235. retmsg="Database error (Document removal)!")
  236. f2d = File2DocumentService.get_by_document_id(doc_id)
  237. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
  238. File2DocumentService.delete_by_document_id(doc_id)
  239. STORAGE_IMPL.rm(b, n)
  240. except Exception as e:
  241. errors += str(e)
  242. if errors:
  243. return get_result(retmsg=errors, retcode=RetCode.SERVER_ERROR)
  244. return get_result()
  245. @manager.route('/datasets/<dataset_id>/chunks', methods=['POST'])
  246. @token_required
  247. def parse(tenant_id,dataset_id):
  248. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  249. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}.")
  250. req = request.json
  251. if not req.get("document_ids"):
  252. return get_error_data_result("`document_ids` is required")
  253. for id in req["document_ids"]:
  254. doc = DocumentService.query(id=id,kb_id=dataset_id)
  255. if not doc:
  256. return get_error_data_result(retmsg=f"You don't own the document {id}.")
  257. if doc[0].progress != 0.0:
  258. return get_error_data_result("Can't stop parsing document with progress at 0 or 100")
  259. info = {"run": "1", "progress": 0}
  260. info["progress_msg"] = ""
  261. info["chunk_num"] = 0
  262. info["token_num"] = 0
  263. DocumentService.update_by_id(id, info)
  264. # if str(req["run"]) == TaskStatus.CANCEL.value:
  265. ELASTICSEARCH.deleteByQuery(
  266. Q("match", doc_id=id), idxnm=search.index_name(tenant_id))
  267. TaskService.filter_delete([Task.doc_id == id])
  268. e, doc = DocumentService.get_by_id(id)
  269. doc = doc.to_dict()
  270. doc["tenant_id"] = tenant_id
  271. bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
  272. queue_tasks(doc, bucket, name)
  273. return get_result()
  274. @manager.route('/datasets/<dataset_id>/chunks', methods=['DELETE'])
  275. @token_required
  276. def stop_parsing(tenant_id,dataset_id):
  277. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  278. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}.")
  279. req = request.json
  280. if not req.get("document_ids"):
  281. return get_error_data_result("`document_ids` is required")
  282. for id in req["document_ids"]:
  283. doc = DocumentService.query(id=id, kb_id=dataset_id)
  284. if not doc:
  285. return get_error_data_result(retmsg=f"You don't own the document {id}.")
  286. if doc[0].progress == 100.0 or doc[0].progress == 0.0:
  287. return get_error_data_result("Can't stop parsing document with progress at 0 or 100")
  288. info = {"run": "2", "progress": 0}
  289. DocumentService.update_by_id(id, info)
  290. # if str(req["run"]) == TaskStatus.CANCEL.value:
  291. tenant_id = DocumentService.get_tenant_id(id)
  292. ELASTICSEARCH.deleteByQuery(
  293. Q("match", doc_id=id), idxnm=search.index_name(tenant_id))
  294. return get_result()
  295. @manager.route('/datasets/<dataset_id>/documents/<document_id>/chunks', methods=['GET'])
  296. @token_required
  297. def list_chunks(tenant_id,dataset_id,document_id):
  298. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  299. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}.")
  300. doc=DocumentService.query(id=document_id, kb_id=dataset_id)
  301. if not doc:
  302. return get_error_data_result(retmsg=f"You don't own the document {document_id}.")
  303. doc=doc[0]
  304. req = request.args
  305. doc_id = document_id
  306. page = int(req.get("offset", 1))
  307. size = int(req.get("limit", 30))
  308. question = req.get("keywords", "")
  309. query = {
  310. "doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
  311. }
  312. sres = retrievaler.search(query, search.index_name(tenant_id), highlight=True)
  313. key_mapping = {
  314. "chunk_num": "chunk_count",
  315. "kb_id": "dataset_id",
  316. "token_num": "token_count",
  317. "parser_id": "chunk_method"
  318. }
  319. run_mapping = {
  320. "0": "UNSTART",
  321. "1": "RUNNING",
  322. "2": "CANCEL",
  323. "3": "DONE",
  324. "4": "FAIL"
  325. }
  326. doc=doc.to_dict()
  327. renamed_doc = {}
  328. for key, value in doc.items():
  329. if key == "run":
  330. renamed_doc["run"] = run_mapping.get(str(value))
  331. new_key = key_mapping.get(key, key)
  332. renamed_doc[new_key] = value
  333. res = {"total": sres.total, "chunks": [], "doc": renamed_doc}
  334. origin_chunks = []
  335. sign = 0
  336. for id in sres.ids:
  337. d = {
  338. "chunk_id": id,
  339. "content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[
  340. id].get(
  341. "content_with_weight", ""),
  342. "doc_id": sres.field[id]["doc_id"],
  343. "docnm_kwd": sres.field[id]["docnm_kwd"],
  344. "important_kwd": sres.field[id].get("important_kwd", []),
  345. "img_id": sres.field[id].get("img_id", ""),
  346. "available_int": sres.field[id].get("available_int", 1),
  347. "positions": sres.field[id].get("position_int", "").split("\t")
  348. }
  349. if len(d["positions"]) % 5 == 0:
  350. poss = []
  351. for i in range(0, len(d["positions"]), 5):
  352. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  353. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  354. d["positions"] = poss
  355. origin_chunks.append(d)
  356. if req.get("id"):
  357. if req.get("id") == id:
  358. origin_chunks.clear()
  359. origin_chunks.append(d)
  360. sign = 1
  361. break
  362. if req.get("id"):
  363. if sign == 0:
  364. return get_error_data_result(f"Can't find this chunk {req.get('id')}")
  365. for chunk in origin_chunks:
  366. key_mapping = {
  367. "chunk_id": "id",
  368. "content_with_weight": "content",
  369. "doc_id": "document_id",
  370. "important_kwd": "important_keywords",
  371. "img_id": "image_id"
  372. }
  373. renamed_chunk = {}
  374. for key, value in chunk.items():
  375. new_key = key_mapping.get(key, key)
  376. renamed_chunk[new_key] = value
  377. res["chunks"].append(renamed_chunk)
  378. return get_result(data=res)
  379. @manager.route('/datasets/<dataset_id>/documents/<document_id>/chunks', methods=['POST'])
  380. @token_required
  381. def add_chunk(tenant_id,dataset_id,document_id):
  382. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  383. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}.")
  384. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  385. if not doc:
  386. return get_error_data_result(retmsg=f"You don't own the document {document_id}.")
  387. doc = doc[0]
  388. req = request.json
  389. if not req.get("content"):
  390. return get_error_data_result(retmsg="`content` is required")
  391. if "important_keywords" in req:
  392. if type(req["important_keywords"]) != list:
  393. return get_error_data_result("`important_keywords` is required to be a list")
  394. md5 = hashlib.md5()
  395. md5.update((req["content"] + document_id).encode("utf-8"))
  396. chunk_id = md5.hexdigest()
  397. d = {"id": chunk_id, "content_ltks": rag_tokenizer.tokenize(req["content"]),
  398. "content_with_weight": req["content"]}
  399. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  400. d["important_kwd"] = req.get("important_keywords", [])
  401. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req.get("important_keywords", [])))
  402. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  403. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  404. d["kb_id"] = [doc.kb_id]
  405. d["docnm_kwd"] = doc.name
  406. d["doc_id"] = doc.id
  407. embd_id = DocumentService.get_embd_id(document_id)
  408. embd_mdl = TenantLLMService.model_instance(
  409. tenant_id, LLMType.EMBEDDING.value, embd_id)
  410. v, c = embd_mdl.encode([doc.name, req["content"]])
  411. v = 0.1 * v[0] + 0.9 * v[1]
  412. d["q_%d_vec" % len(v)] = v.tolist()
  413. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  414. DocumentService.increment_chunk_num(
  415. doc.id, doc.kb_id, c, 1, 0)
  416. d["chunk_id"] = chunk_id
  417. # rename keys
  418. key_mapping = {
  419. "chunk_id": "id",
  420. "content_with_weight": "content",
  421. "doc_id": "document_id",
  422. "important_kwd": "important_keywords",
  423. "kb_id": "dataset_id",
  424. "create_timestamp_flt": "create_timestamp",
  425. "create_time": "create_time",
  426. "document_keyword": "document",
  427. }
  428. renamed_chunk = {}
  429. for key, value in d.items():
  430. if key in key_mapping:
  431. new_key = key_mapping.get(key, key)
  432. renamed_chunk[new_key] = value
  433. return get_result(data={"chunk": renamed_chunk})
  434. # return get_result(data={"chunk_id": chunk_id})
  435. @manager.route('datasets/<dataset_id>/documents/<document_id>/chunks', methods=['DELETE'])
  436. @token_required
  437. def rm_chunk(tenant_id,dataset_id,document_id):
  438. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  439. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}.")
  440. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  441. if not doc:
  442. return get_error_data_result(retmsg=f"You don't own the document {document_id}.")
  443. doc = doc[0]
  444. req = request.json
  445. if not req.get("chunk_ids"):
  446. return get_error_data_result("`chunk_ids` is required")
  447. query = {
  448. "doc_ids": [doc.id], "page": 1, "size": 1024, "question": "", "sort": True}
  449. sres = retrievaler.search(query, search.index_name(tenant_id), highlight=True)
  450. for chunk_id in req.get("chunk_ids"):
  451. if chunk_id not in sres.ids:
  452. return get_error_data_result(f"Chunk {chunk_id} not found")
  453. if not ELASTICSEARCH.deleteByQuery(
  454. Q("ids", values=req["chunk_ids"]), search.index_name(tenant_id)):
  455. return get_error_data_result(retmsg="Index updating failure")
  456. deleted_chunk_ids = req["chunk_ids"]
  457. chunk_number = len(deleted_chunk_ids)
  458. DocumentService.decrement_chunk_num(doc.id, doc.kb_id, 1, chunk_number, 0)
  459. return get_result()
  460. @manager.route('/datasets/<dataset_id>/documents/<document_id>/chunks/<chunk_id>', methods=['PUT'])
  461. @token_required
  462. def update_chunk(tenant_id,dataset_id,document_id,chunk_id):
  463. try:
  464. res = ELASTICSEARCH.get(
  465. chunk_id, search.index_name(
  466. tenant_id))
  467. except Exception as e:
  468. return get_error_data_result(f"Can't find this chunk {chunk_id}")
  469. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  470. return get_error_data_result(retmsg=f"You don't own the dataset {dataset_id}.")
  471. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  472. if not doc:
  473. return get_error_data_result(retmsg=f"You don't own the document {document_id}.")
  474. doc = doc[0]
  475. query = {
  476. "doc_ids": [document_id], "page": 1, "size": 1024, "question": "", "sort": True
  477. }
  478. sres = retrievaler.search(query, search.index_name(tenant_id), highlight=True)
  479. if chunk_id not in sres.ids:
  480. return get_error_data_result(f"You don't own the chunk {chunk_id}")
  481. req = request.json
  482. content=res["_source"].get("content_with_weight")
  483. d = {
  484. "id": chunk_id,
  485. "content_with_weight": req.get("content",content)}
  486. d["content_ltks"] = rag_tokenizer.tokenize(d["content_with_weight"])
  487. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  488. if "important_keywords" in req:
  489. if not isinstance(req["important_keywords"],list):
  490. return get_error_data_result("`important_keywords` should be a list")
  491. d["important_kwd"] = req.get("important_keywords")
  492. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
  493. if "available" in req:
  494. d["available_int"] = int(req["available"])
  495. embd_id = DocumentService.get_embd_id(document_id)
  496. embd_mdl = TenantLLMService.model_instance(
  497. tenant_id, LLMType.EMBEDDING.value, embd_id)
  498. if doc.parser_id == ParserType.QA:
  499. arr = [
  500. t for t in re.split(
  501. r"[\n\t]",
  502. d["content_with_weight"]) if len(t) > 1]
  503. if len(arr) != 2:
  504. return get_error_data_result(
  505. retmsg="Q&A must be separated by TAB/ENTER key.")
  506. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  507. d = beAdoc(d, arr[0], arr[1], not any(
  508. [rag_tokenizer.is_chinese(t) for t in q + a]))
  509. v, c = embd_mdl.encode([doc.name, d["content_with_weight"]])
  510. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  511. d["q_%d_vec" % len(v)] = v.tolist()
  512. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  513. return get_result()
  514. @manager.route('/retrieval', methods=['POST'])
  515. @token_required
  516. def retrieval_test(tenant_id):
  517. req = request.json
  518. if not req.get("dataset_ids"):
  519. return get_error_data_result("`datasets` is required.")
  520. kb_ids = req["dataset_ids"]
  521. if not isinstance(kb_ids,list):
  522. return get_error_data_result("`datasets` should be a list")
  523. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  524. for id in kb_ids:
  525. if not KnowledgebaseService.query(id=id,tenant_id=tenant_id):
  526. return get_error_data_result(f"You don't own the dataset {id}.")
  527. embd_nms = list(set([kb.embd_id for kb in kbs]))
  528. if len(embd_nms) != 1:
  529. return get_result(
  530. retmsg='Datasets use different embedding models."',
  531. retcode=RetCode.AUTHENTICATION_ERROR)
  532. if "question" not in req:
  533. return get_error_data_result("`question` is required.")
  534. page = int(req.get("offset", 1))
  535. size = int(req.get("limit", 1024))
  536. question = req["question"]
  537. doc_ids = req.get("document_ids", [])
  538. if not isinstance(doc_ids,list):
  539. return get_error_data_result("`documents` should be a list")
  540. doc_ids_list=KnowledgebaseService.list_documents_by_ids(kb_ids)
  541. for doc_id in doc_ids:
  542. if doc_id not in doc_ids_list:
  543. return get_error_data_result(f"The datasets don't own the document {doc_id}")
  544. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  545. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  546. top = int(req.get("top_k", 1024))
  547. if req.get("highlight")=="False" or req.get("highlight")=="false":
  548. highlight = False
  549. else:
  550. highlight = True
  551. try:
  552. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  553. if not e:
  554. return get_error_data_result(retmsg="Dataset not found!")
  555. embd_mdl = TenantLLMService.model_instance(
  556. kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  557. rerank_mdl = None
  558. if req.get("rerank_id"):
  559. rerank_mdl = TenantLLMService.model_instance(
  560. kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
  561. if req.get("keyword", False):
  562. chat_mdl = TenantLLMService.model_instance(kb.tenant_id, LLMType.CHAT)
  563. question += keyword_extraction(chat_mdl, question)
  564. retr = retrievaler if kb.parser_id != ParserType.KG else kg_retrievaler
  565. ranks = retr.retrieval(question, embd_mdl, kb.tenant_id, kb_ids, page, size,
  566. similarity_threshold, vector_similarity_weight, top,
  567. doc_ids, rerank_mdl=rerank_mdl, highlight=highlight)
  568. for c in ranks["chunks"]:
  569. if "vector" in c:
  570. del c["vector"]
  571. ##rename keys
  572. renamed_chunks = []
  573. for chunk in ranks["chunks"]:
  574. key_mapping = {
  575. "chunk_id": "id",
  576. "content_with_weight": "content",
  577. "doc_id": "document_id",
  578. "important_kwd": "important_keywords",
  579. "docnm_kwd": "document_keyword"
  580. }
  581. rename_chunk = {}
  582. for key, value in chunk.items():
  583. new_key = key_mapping.get(key, key)
  584. rename_chunk[new_key] = value
  585. renamed_chunks.append(rename_chunk)
  586. ranks["chunks"] = renamed_chunks
  587. return get_result(data=ranks)
  588. except Exception as e:
  589. if str(e).find("not_found") > 0:
  590. return get_result(retmsg=f'No chunk found! Check the chunk status please!',
  591. retcode=RetCode.DATA_ERROR)
  592. return server_error_response(e)