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

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