Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

doc.py 27KB

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