Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

doc.py 46KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394
  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 import settings
  24. import xxhash
  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 flask import request, send_file
  33. from api.db import FileSource, TaskStatus, FileType
  34. from api.db.db_models import File
  35. from api.db.services.document_service import DocumentService
  36. from api.db.services.file2document_service import File2DocumentService
  37. from api.db.services.file_service import FileService
  38. from api.db.services.knowledgebase_service import KnowledgebaseService
  39. from api.utils.api_utils import construct_json_result, get_parser_config
  40. from rag.nlp import search
  41. from rag.utils import rmSpace
  42. from rag.utils.storage_factory import STORAGE_IMPL
  43. from pydantic import BaseModel, Field, validator
  44. MAXIMUM_OF_UPLOADING_FILES = 256
  45. class Chunk(BaseModel):
  46. id: str = ""
  47. content: str = ""
  48. document_id: str = ""
  49. docnm_kwd: str = ""
  50. important_keywords: list = Field(default_factory=list)
  51. questions: list = Field(default_factory=list)
  52. question_tks: str = ""
  53. image_id: str = ""
  54. available: bool = True
  55. positions: list[list[int]] = Field(default_factory=list)
  56. @validator('positions')
  57. def validate_positions(cls, value):
  58. for sublist in value:
  59. if len(sublist) != 5:
  60. raise ValueError("Each sublist in positions must have a length of 5")
  61. return value
  62. @manager.route("/datasets/<dataset_id>/documents", methods=["POST"]) # noqa: F821
  63. @token_required
  64. def upload(dataset_id, tenant_id):
  65. """
  66. Upload documents to a dataset.
  67. ---
  68. tags:
  69. - Documents
  70. security:
  71. - ApiKeyAuth: []
  72. parameters:
  73. - in: path
  74. name: dataset_id
  75. type: string
  76. required: true
  77. description: ID of the dataset.
  78. - in: header
  79. name: Authorization
  80. type: string
  81. required: true
  82. description: Bearer token for authentication.
  83. - in: formData
  84. name: file
  85. type: file
  86. required: true
  87. description: Document files to upload.
  88. responses:
  89. 200:
  90. description: Successfully uploaded documents.
  91. schema:
  92. type: object
  93. properties:
  94. data:
  95. type: array
  96. items:
  97. type: object
  98. properties:
  99. id:
  100. type: string
  101. description: Document ID.
  102. name:
  103. type: string
  104. description: Document name.
  105. chunk_count:
  106. type: integer
  107. description: Number of chunks.
  108. token_count:
  109. type: integer
  110. description: Number of tokens.
  111. dataset_id:
  112. type: string
  113. description: ID of the dataset.
  114. chunk_method:
  115. type: string
  116. description: Chunking method used.
  117. run:
  118. type: string
  119. description: Processing status.
  120. """
  121. if "file" not in request.files:
  122. return get_error_data_result(
  123. message="No file part!", code=settings.RetCode.ARGUMENT_ERROR
  124. )
  125. file_objs = request.files.getlist("file")
  126. for file_obj in file_objs:
  127. if file_obj.filename == "":
  128. return get_result(
  129. message="No file selected!", code=settings.RetCode.ARGUMENT_ERROR
  130. )
  131. '''
  132. # total size
  133. total_size = 0
  134. for file_obj in file_objs:
  135. file_obj.seek(0, os.SEEK_END)
  136. total_size += file_obj.tell()
  137. file_obj.seek(0)
  138. MAX_TOTAL_FILE_SIZE = 10 * 1024 * 1024
  139. if total_size > MAX_TOTAL_FILE_SIZE:
  140. return get_result(
  141. message=f"Total file size exceeds 10MB limit! ({total_size / (1024 * 1024):.2f} MB)",
  142. code=settings.RetCode.ARGUMENT_ERROR,
  143. )
  144. '''
  145. e, kb = KnowledgebaseService.get_by_id(dataset_id)
  146. if not e:
  147. raise LookupError(f"Can't find the dataset with ID {dataset_id}!")
  148. err, files = FileService.upload_document(kb, file_objs, tenant_id)
  149. if err:
  150. return get_result(message="\n".join(err), code=settings.RetCode.SERVER_ERROR)
  151. # rename key's name
  152. renamed_doc_list = []
  153. for file in files:
  154. doc = file[0]
  155. key_mapping = {
  156. "chunk_num": "chunk_count",
  157. "kb_id": "dataset_id",
  158. "token_num": "token_count",
  159. "parser_id": "chunk_method",
  160. }
  161. renamed_doc = {}
  162. for key, value in doc.items():
  163. new_key = key_mapping.get(key, key)
  164. renamed_doc[new_key] = value
  165. renamed_doc["run"] = "UNSTART"
  166. renamed_doc_list.append(renamed_doc)
  167. return get_result(data=renamed_doc_list)
  168. @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["PUT"]) # noqa: F821
  169. @token_required
  170. def update_doc(tenant_id, dataset_id, document_id):
  171. """
  172. Update a document within a dataset.
  173. ---
  174. tags:
  175. - Documents
  176. security:
  177. - ApiKeyAuth: []
  178. parameters:
  179. - in: path
  180. name: dataset_id
  181. type: string
  182. required: true
  183. description: ID of the dataset.
  184. - in: path
  185. name: document_id
  186. type: string
  187. required: true
  188. description: ID of the document to update.
  189. - in: header
  190. name: Authorization
  191. type: string
  192. required: true
  193. description: Bearer token for authentication.
  194. - in: body
  195. name: body
  196. description: Document update parameters.
  197. required: true
  198. schema:
  199. type: object
  200. properties:
  201. name:
  202. type: string
  203. description: New name of the document.
  204. parser_config:
  205. type: object
  206. description: Parser configuration.
  207. chunk_method:
  208. type: string
  209. description: Chunking method.
  210. responses:
  211. 200:
  212. description: Document updated successfully.
  213. schema:
  214. type: object
  215. """
  216. req = request.json
  217. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  218. return get_error_data_result(message="You don't own the dataset.")
  219. doc = DocumentService.query(kb_id=dataset_id, id=document_id)
  220. if not doc:
  221. return get_error_data_result(message="The dataset doesn't own the document.")
  222. doc = doc[0]
  223. if "chunk_count" in req:
  224. if req["chunk_count"] != doc.chunk_num:
  225. return get_error_data_result(message="Can't change `chunk_count`.")
  226. if "token_count" in req:
  227. if req["token_count"] != doc.token_num:
  228. return get_error_data_result(message="Can't change `token_count`.")
  229. if "progress" in req:
  230. if req["progress"] != doc.progress:
  231. return get_error_data_result(message="Can't change `progress`.")
  232. if "name" in req and req["name"] != doc.name:
  233. if (
  234. pathlib.Path(req["name"].lower()).suffix
  235. != pathlib.Path(doc.name.lower()).suffix
  236. ):
  237. return get_result(
  238. message="The extension of file can't be changed",
  239. code=settings.RetCode.ARGUMENT_ERROR,
  240. )
  241. for d in DocumentService.query(name=req["name"], kb_id=doc.kb_id):
  242. if d.name == req["name"]:
  243. return get_error_data_result(
  244. message="Duplicated document name in the same dataset."
  245. )
  246. if not DocumentService.update_by_id(document_id, {"name": req["name"]}):
  247. return get_error_data_result(message="Database error (Document rename)!")
  248. informs = File2DocumentService.get_by_document_id(document_id)
  249. if informs:
  250. e, file = FileService.get_by_id(informs[0].file_id)
  251. FileService.update_by_id(file.id, {"name": req["name"]})
  252. if "parser_config" in req:
  253. DocumentService.update_parser_config(doc.id, req["parser_config"])
  254. if "chunk_method" in req:
  255. valid_chunk_method = {
  256. "naive",
  257. "manual",
  258. "qa",
  259. "table",
  260. "paper",
  261. "book",
  262. "laws",
  263. "presentation",
  264. "picture",
  265. "one",
  266. "knowledge_graph",
  267. "email",
  268. }
  269. if req.get("chunk_method") not in valid_chunk_method:
  270. return get_error_data_result(
  271. f"`chunk_method` {req['chunk_method']} doesn't exist"
  272. )
  273. if doc.parser_id.lower() == req["chunk_method"].lower():
  274. return get_result()
  275. if doc.type == FileType.VISUAL or re.search(r"\.(ppt|pptx|pages)$", doc.name):
  276. return get_error_data_result(message="Not supported yet!")
  277. e = DocumentService.update_by_id(
  278. doc.id,
  279. {
  280. "parser_id": req["chunk_method"],
  281. "progress": 0,
  282. "progress_msg": "",
  283. "run": TaskStatus.UNSTART.value,
  284. },
  285. )
  286. if not e:
  287. return get_error_data_result(message="Document not found!")
  288. req["parser_config"] = get_parser_config(
  289. req["chunk_method"], req.get("parser_config")
  290. )
  291. DocumentService.update_parser_config(doc.id, req["parser_config"])
  292. if doc.token_num > 0:
  293. e = DocumentService.increment_chunk_num(
  294. doc.id,
  295. doc.kb_id,
  296. doc.token_num * -1,
  297. doc.chunk_num * -1,
  298. doc.process_duation * -1,
  299. )
  300. if not e:
  301. return get_error_data_result(message="Document not found!")
  302. settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), dataset_id)
  303. return get_result()
  304. @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["GET"]) # noqa: F821
  305. @token_required
  306. def download(tenant_id, dataset_id, document_id):
  307. """
  308. Download a document from a dataset.
  309. ---
  310. tags:
  311. - Documents
  312. security:
  313. - ApiKeyAuth: []
  314. produces:
  315. - application/octet-stream
  316. parameters:
  317. - in: path
  318. name: dataset_id
  319. type: string
  320. required: true
  321. description: ID of the dataset.
  322. - in: path
  323. name: document_id
  324. type: string
  325. required: true
  326. description: ID of the document to download.
  327. - in: header
  328. name: Authorization
  329. type: string
  330. required: true
  331. description: Bearer token for authentication.
  332. responses:
  333. 200:
  334. description: Document file stream.
  335. schema:
  336. type: file
  337. 400:
  338. description: Error message.
  339. schema:
  340. type: object
  341. """
  342. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  343. return get_error_data_result(message=f"You do not own the dataset {dataset_id}.")
  344. doc = DocumentService.query(kb_id=dataset_id, id=document_id)
  345. if not doc:
  346. return get_error_data_result(
  347. message=f"The dataset not own the document {document_id}."
  348. )
  349. # The process of downloading
  350. doc_id, doc_location = File2DocumentService.get_storage_address(
  351. doc_id=document_id
  352. ) # minio address
  353. file_stream = STORAGE_IMPL.get(doc_id, doc_location)
  354. if not file_stream:
  355. return construct_json_result(
  356. message="This file is empty.", code=settings.RetCode.DATA_ERROR
  357. )
  358. file = BytesIO(file_stream)
  359. # Use send_file with a proper filename and MIME type
  360. return send_file(
  361. file,
  362. as_attachment=True,
  363. download_name=doc[0].name,
  364. mimetype="application/octet-stream", # Set a default MIME type
  365. )
  366. @manager.route("/datasets/<dataset_id>/documents", methods=["GET"]) # noqa: F821
  367. @token_required
  368. def list_docs(dataset_id, tenant_id):
  369. """
  370. List documents in a dataset.
  371. ---
  372. tags:
  373. - Documents
  374. security:
  375. - ApiKeyAuth: []
  376. parameters:
  377. - in: path
  378. name: dataset_id
  379. type: string
  380. required: true
  381. description: ID of the dataset.
  382. - in: query
  383. name: id
  384. type: string
  385. required: false
  386. description: Filter by document ID.
  387. - in: query
  388. name: page
  389. type: integer
  390. required: false
  391. default: 1
  392. description: Page number.
  393. - in: query
  394. name: page_size
  395. type: integer
  396. required: false
  397. default: 30
  398. description: Number of items per page.
  399. - in: query
  400. name: orderby
  401. type: string
  402. required: false
  403. default: "create_time"
  404. description: Field to order by.
  405. - in: query
  406. name: desc
  407. type: boolean
  408. required: false
  409. default: true
  410. description: Order in descending.
  411. - in: header
  412. name: Authorization
  413. type: string
  414. required: true
  415. description: Bearer token for authentication.
  416. responses:
  417. 200:
  418. description: List of documents.
  419. schema:
  420. type: object
  421. properties:
  422. total:
  423. type: integer
  424. description: Total number of documents.
  425. docs:
  426. type: array
  427. items:
  428. type: object
  429. properties:
  430. id:
  431. type: string
  432. description: Document ID.
  433. name:
  434. type: string
  435. description: Document name.
  436. chunk_count:
  437. type: integer
  438. description: Number of chunks.
  439. token_count:
  440. type: integer
  441. description: Number of tokens.
  442. dataset_id:
  443. type: string
  444. description: ID of the dataset.
  445. chunk_method:
  446. type: string
  447. description: Chunking method used.
  448. run:
  449. type: string
  450. description: Processing status.
  451. """
  452. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  453. return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
  454. id = request.args.get("id")
  455. name = request.args.get("name")
  456. if not DocumentService.query(id=id, kb_id=dataset_id):
  457. return get_error_data_result(message=f"You don't own the document {id}.")
  458. if not DocumentService.query(name=name, kb_id=dataset_id):
  459. return get_error_data_result(message=f"You don't own the document {name}.")
  460. page = int(request.args.get("page", 1))
  461. keywords = request.args.get("keywords", "")
  462. page_size = int(request.args.get("page_size", 30))
  463. orderby = request.args.get("orderby", "create_time")
  464. if request.args.get("desc") == "False":
  465. desc = False
  466. else:
  467. desc = True
  468. docs, tol = DocumentService.get_list(
  469. dataset_id, page, page_size, orderby, desc, keywords, id, name
  470. )
  471. # rename key's name
  472. renamed_doc_list = []
  473. for doc in docs:
  474. key_mapping = {
  475. "chunk_num": "chunk_count",
  476. "kb_id": "dataset_id",
  477. "token_num": "token_count",
  478. "parser_id": "chunk_method",
  479. }
  480. run_mapping = {
  481. "0": "UNSTART",
  482. "1": "RUNNING",
  483. "2": "CANCEL",
  484. "3": "DONE",
  485. "4": "FAIL",
  486. }
  487. renamed_doc = {}
  488. for key, value in doc.items():
  489. if key == "run":
  490. renamed_doc["run"] = run_mapping.get(str(value))
  491. new_key = key_mapping.get(key, key)
  492. renamed_doc[new_key] = value
  493. if key == "run":
  494. renamed_doc["run"] = run_mapping.get(value)
  495. renamed_doc_list.append(renamed_doc)
  496. return get_result(data={"total": tol, "docs": renamed_doc_list})
  497. @manager.route("/datasets/<dataset_id>/documents", methods=["DELETE"]) # noqa: F821
  498. @token_required
  499. def delete(tenant_id, dataset_id):
  500. """
  501. Delete documents from a dataset.
  502. ---
  503. tags:
  504. - Documents
  505. security:
  506. - ApiKeyAuth: []
  507. parameters:
  508. - in: path
  509. name: dataset_id
  510. type: string
  511. required: true
  512. description: ID of the dataset.
  513. - in: body
  514. name: body
  515. description: Document deletion parameters.
  516. required: true
  517. schema:
  518. type: object
  519. properties:
  520. ids:
  521. type: array
  522. items:
  523. type: string
  524. description: List of document IDs to delete.
  525. - in: header
  526. name: Authorization
  527. type: string
  528. required: true
  529. description: Bearer token for authentication.
  530. responses:
  531. 200:
  532. description: Documents deleted successfully.
  533. schema:
  534. type: object
  535. """
  536. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  537. return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
  538. req = request.json
  539. if not req:
  540. doc_ids = None
  541. else:
  542. doc_ids = req.get("ids")
  543. if not doc_ids:
  544. doc_list = []
  545. docs = DocumentService.query(kb_id=dataset_id)
  546. for doc in docs:
  547. doc_list.append(doc.id)
  548. else:
  549. doc_list = doc_ids
  550. root_folder = FileService.get_root_folder(tenant_id)
  551. pf_id = root_folder["id"]
  552. FileService.init_knowledgebase_docs(pf_id, tenant_id)
  553. errors = ""
  554. for doc_id in doc_list:
  555. try:
  556. e, doc = DocumentService.get_by_id(doc_id)
  557. if not e:
  558. return get_error_data_result(message="Document not found!")
  559. tenant_id = DocumentService.get_tenant_id(doc_id)
  560. if not tenant_id:
  561. return get_error_data_result(message="Tenant not found!")
  562. b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
  563. if not DocumentService.remove_document(doc, tenant_id):
  564. return get_error_data_result(
  565. message="Database error (Document removal)!"
  566. )
  567. f2d = File2DocumentService.get_by_document_id(doc_id)
  568. FileService.filter_delete(
  569. [
  570. File.source_type == FileSource.KNOWLEDGEBASE,
  571. File.id == f2d[0].file_id,
  572. ]
  573. )
  574. File2DocumentService.delete_by_document_id(doc_id)
  575. STORAGE_IMPL.rm(b, n)
  576. except Exception as e:
  577. errors += str(e)
  578. if errors:
  579. return get_result(message=errors, code=settings.RetCode.SERVER_ERROR)
  580. return get_result()
  581. @manager.route("/datasets/<dataset_id>/chunks", methods=["POST"]) # noqa: F821
  582. @token_required
  583. def parse(tenant_id, dataset_id):
  584. """
  585. Start parsing documents into chunks.
  586. ---
  587. tags:
  588. - Chunks
  589. security:
  590. - ApiKeyAuth: []
  591. parameters:
  592. - in: path
  593. name: dataset_id
  594. type: string
  595. required: true
  596. description: ID of the dataset.
  597. - in: body
  598. name: body
  599. description: Parsing parameters.
  600. required: true
  601. schema:
  602. type: object
  603. properties:
  604. document_ids:
  605. type: array
  606. items:
  607. type: string
  608. description: List of document IDs to parse.
  609. - in: header
  610. name: Authorization
  611. type: string
  612. required: true
  613. description: Bearer token for authentication.
  614. responses:
  615. 200:
  616. description: Parsing started successfully.
  617. schema:
  618. type: object
  619. """
  620. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  621. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  622. req = request.json
  623. if not req.get("document_ids"):
  624. return get_error_data_result("`document_ids` is required")
  625. for id in req["document_ids"]:
  626. doc = DocumentService.query(id=id, kb_id=dataset_id)
  627. if not doc:
  628. return get_error_data_result(message=f"You don't own the document {id}.")
  629. if doc[0].progress != 0.0:
  630. return get_error_data_result(
  631. "Can't stop parsing document with progress at 0 or 100"
  632. )
  633. info = {"run": "1", "progress": 0}
  634. info["progress_msg"] = ""
  635. info["chunk_num"] = 0
  636. info["token_num"] = 0
  637. DocumentService.update_by_id(id, info)
  638. settings.docStoreConn.delete({"doc_id": id}, search.index_name(tenant_id), dataset_id)
  639. TaskService.filter_delete([Task.doc_id == id])
  640. e, doc = DocumentService.get_by_id(id)
  641. doc = doc.to_dict()
  642. doc["tenant_id"] = tenant_id
  643. bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
  644. queue_tasks(doc, bucket, name)
  645. return get_result()
  646. @manager.route("/datasets/<dataset_id>/chunks", methods=["DELETE"]) # noqa: F821
  647. @token_required
  648. def stop_parsing(tenant_id, dataset_id):
  649. """
  650. Stop parsing documents into chunks.
  651. ---
  652. tags:
  653. - Chunks
  654. security:
  655. - ApiKeyAuth: []
  656. parameters:
  657. - in: path
  658. name: dataset_id
  659. type: string
  660. required: true
  661. description: ID of the dataset.
  662. - in: body
  663. name: body
  664. description: Stop parsing parameters.
  665. required: true
  666. schema:
  667. type: object
  668. properties:
  669. document_ids:
  670. type: array
  671. items:
  672. type: string
  673. description: List of document IDs to stop parsing.
  674. - in: header
  675. name: Authorization
  676. type: string
  677. required: true
  678. description: Bearer token for authentication.
  679. responses:
  680. 200:
  681. description: Parsing stopped successfully.
  682. schema:
  683. type: object
  684. """
  685. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  686. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  687. req = request.json
  688. if not req.get("document_ids"):
  689. return get_error_data_result("`document_ids` is required")
  690. for id in req["document_ids"]:
  691. doc = DocumentService.query(id=id, kb_id=dataset_id)
  692. if not doc:
  693. return get_error_data_result(message=f"You don't own the document {id}.")
  694. if int(doc[0].progress) == 1 or int(doc[0].progress) == 0:
  695. return get_error_data_result(
  696. "Can't stop parsing document with progress at 0 or 1"
  697. )
  698. info = {"run": "2", "progress": 0, "chunk_num": 0}
  699. DocumentService.update_by_id(id, info)
  700. settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), dataset_id)
  701. return get_result()
  702. @manager.route("/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["GET"]) # noqa: F821
  703. @token_required
  704. def list_chunks(tenant_id, dataset_id, document_id):
  705. """
  706. List chunks of a document.
  707. ---
  708. tags:
  709. - Chunks
  710. security:
  711. - ApiKeyAuth: []
  712. parameters:
  713. - in: path
  714. name: dataset_id
  715. type: string
  716. required: true
  717. description: ID of the dataset.
  718. - in: path
  719. name: document_id
  720. type: string
  721. required: true
  722. description: ID of the document.
  723. - in: query
  724. name: page
  725. type: integer
  726. required: false
  727. default: 1
  728. description: Page number.
  729. - in: query
  730. name: page_size
  731. type: integer
  732. required: false
  733. default: 30
  734. description: Number of items per page.
  735. - in: header
  736. name: Authorization
  737. type: string
  738. required: true
  739. description: Bearer token for authentication.
  740. responses:
  741. 200:
  742. description: List of chunks.
  743. schema:
  744. type: object
  745. properties:
  746. total:
  747. type: integer
  748. description: Total number of chunks.
  749. chunks:
  750. type: array
  751. items:
  752. type: object
  753. properties:
  754. id:
  755. type: string
  756. description: Chunk ID.
  757. content:
  758. type: string
  759. description: Chunk content.
  760. document_id:
  761. type: string
  762. description: ID of the document.
  763. important_keywords:
  764. type: array
  765. items:
  766. type: string
  767. description: Important keywords.
  768. image_id:
  769. type: string
  770. description: Image ID associated with the chunk.
  771. doc:
  772. type: object
  773. description: Document details.
  774. """
  775. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  776. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  777. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  778. if not doc:
  779. return get_error_data_result(
  780. message=f"You don't own the document {document_id}."
  781. )
  782. doc = doc[0]
  783. req = request.args
  784. doc_id = document_id
  785. page = int(req.get("page", 1))
  786. size = int(req.get("page_size", 30))
  787. question = req.get("keywords", "")
  788. query = {
  789. "doc_ids": [doc_id],
  790. "page": page,
  791. "size": size,
  792. "question": question,
  793. "sort": True,
  794. }
  795. key_mapping = {
  796. "chunk_num": "chunk_count",
  797. "kb_id": "dataset_id",
  798. "token_num": "token_count",
  799. "parser_id": "chunk_method",
  800. }
  801. run_mapping = {
  802. "0": "UNSTART",
  803. "1": "RUNNING",
  804. "2": "CANCEL",
  805. "3": "DONE",
  806. "4": "FAIL",
  807. }
  808. doc = doc.to_dict()
  809. renamed_doc = {}
  810. for key, value in doc.items():
  811. new_key = key_mapping.get(key, key)
  812. renamed_doc[new_key] = value
  813. if key == "run":
  814. renamed_doc["run"] = run_mapping.get(str(value))
  815. res = {"total": 0, "chunks": [], "doc": renamed_doc}
  816. origin_chunks = []
  817. if settings.docStoreConn.indexExist(search.index_name(tenant_id), dataset_id):
  818. sres = settings.retrievaler.search(query, search.index_name(tenant_id), [dataset_id], emb_mdl=None,
  819. highlight=True)
  820. res["total"] = sres.total
  821. sign = 0
  822. for id in sres.ids:
  823. d = {
  824. "id": id,
  825. "content_with_weight": (
  826. rmSpace(sres.highlight[id])
  827. if question and id in sres.highlight
  828. else sres.field[id].get("content_with_weight", "")
  829. ),
  830. "doc_id": sres.field[id]["doc_id"],
  831. "docnm_kwd": sres.field[id]["docnm_kwd"],
  832. "important_kwd": sres.field[id].get("important_kwd", []),
  833. "question_kwd": sres.field[id].get("question_kwd", []),
  834. "img_id": sres.field[id].get("img_id", ""),
  835. "available_int": sres.field[id].get("available_int", 1),
  836. "positions": sres.field[id].get("position_int", []),
  837. }
  838. origin_chunks.append(d)
  839. if req.get("id"):
  840. if req.get("id") == id:
  841. origin_chunks.clear()
  842. origin_chunks.append(d)
  843. sign = 1
  844. break
  845. if req.get("id"):
  846. if sign == 0:
  847. return get_error_data_result(f"Can't find this chunk {req.get('id')}")
  848. for chunk in origin_chunks:
  849. key_mapping = {
  850. "id": "id",
  851. "content_with_weight": "content",
  852. "doc_id": "document_id",
  853. "important_kwd": "important_keywords",
  854. "question_kwd": "questions",
  855. "img_id": "image_id",
  856. "available_int": "available",
  857. }
  858. renamed_chunk = {}
  859. for key, value in chunk.items():
  860. new_key = key_mapping.get(key, key)
  861. renamed_chunk[new_key] = value
  862. if renamed_chunk["available"] == 0:
  863. renamed_chunk["available"] = False
  864. if renamed_chunk["available"] == 1:
  865. renamed_chunk["available"] = True
  866. res["chunks"].append(renamed_chunk)
  867. _ = Chunk(**renamed_chunk) # validate the chunk
  868. return get_result(data=res)
  869. @manager.route( # noqa: F821
  870. "/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["POST"]
  871. )
  872. @token_required
  873. def add_chunk(tenant_id, dataset_id, document_id):
  874. """
  875. Add a chunk to a document.
  876. ---
  877. tags:
  878. - Chunks
  879. security:
  880. - ApiKeyAuth: []
  881. parameters:
  882. - in: path
  883. name: dataset_id
  884. type: string
  885. required: true
  886. description: ID of the dataset.
  887. - in: path
  888. name: document_id
  889. type: string
  890. required: true
  891. description: ID of the document.
  892. - in: body
  893. name: body
  894. description: Chunk data.
  895. required: true
  896. schema:
  897. type: object
  898. properties:
  899. content:
  900. type: string
  901. required: true
  902. description: Content of the chunk.
  903. important_keywords:
  904. type: array
  905. items:
  906. type: string
  907. description: Important keywords.
  908. - in: header
  909. name: Authorization
  910. type: string
  911. required: true
  912. description: Bearer token for authentication.
  913. responses:
  914. 200:
  915. description: Chunk added successfully.
  916. schema:
  917. type: object
  918. properties:
  919. chunk:
  920. type: object
  921. properties:
  922. id:
  923. type: string
  924. description: Chunk ID.
  925. content:
  926. type: string
  927. description: Chunk content.
  928. document_id:
  929. type: string
  930. description: ID of the document.
  931. important_keywords:
  932. type: array
  933. items:
  934. type: string
  935. description: Important keywords.
  936. """
  937. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  938. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  939. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  940. if not doc:
  941. return get_error_data_result(
  942. message=f"You don't own the document {document_id}."
  943. )
  944. doc = doc[0]
  945. req = request.json
  946. if not req.get("content"):
  947. return get_error_data_result(message="`content` is required")
  948. if "important_keywords" in req:
  949. if not isinstance(req["important_keywords"], list):
  950. return get_error_data_result(
  951. "`important_keywords` is required to be a list"
  952. )
  953. if "questions" in req:
  954. if not isinstance(req["questions"], list):
  955. return get_error_data_result(
  956. "`questions` is required to be a list"
  957. )
  958. chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
  959. d = {
  960. "id": chunk_id,
  961. "content_ltks": rag_tokenizer.tokenize(req["content"]),
  962. "content_with_weight": req["content"],
  963. }
  964. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  965. d["important_kwd"] = req.get("important_keywords", [])
  966. d["important_tks"] = rag_tokenizer.tokenize(
  967. " ".join(req.get("important_keywords", []))
  968. )
  969. d["question_kwd"] = req.get("questions", [])
  970. d["question_tks"] = rag_tokenizer.tokenize(
  971. "\n".join(req.get("questions", []))
  972. )
  973. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  974. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  975. d["kb_id"] = dataset_id
  976. d["docnm_kwd"] = doc.name
  977. d["doc_id"] = document_id
  978. embd_id = DocumentService.get_embd_id(document_id)
  979. embd_mdl = TenantLLMService.model_instance(
  980. tenant_id, LLMType.EMBEDDING.value, embd_id
  981. )
  982. v, c = embd_mdl.encode([doc.name, req["content"] if not d["question_kwd"] else "\n".join(d["question_kwd"])])
  983. v = 0.1 * v[0] + 0.9 * v[1]
  984. d["q_%d_vec" % len(v)] = v.tolist()
  985. settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
  986. DocumentService.increment_chunk_num(doc.id, doc.kb_id, c, 1, 0)
  987. # rename keys
  988. key_mapping = {
  989. "id": "id",
  990. "content_with_weight": "content",
  991. "doc_id": "document_id",
  992. "important_kwd": "important_keywords",
  993. "question_kwd": "questions",
  994. "kb_id": "dataset_id",
  995. "create_timestamp_flt": "create_timestamp",
  996. "create_time": "create_time",
  997. "document_keyword": "document",
  998. }
  999. renamed_chunk = {}
  1000. for key, value in d.items():
  1001. if key in key_mapping:
  1002. new_key = key_mapping.get(key, key)
  1003. renamed_chunk[new_key] = value
  1004. _ = Chunk(**renamed_chunk) # validate the chunk
  1005. return get_result(data={"chunk": renamed_chunk})
  1006. # return get_result(data={"chunk_id": chunk_id})
  1007. @manager.route( # noqa: F821
  1008. "datasets/<dataset_id>/documents/<document_id>/chunks", methods=["DELETE"]
  1009. )
  1010. @token_required
  1011. def rm_chunk(tenant_id, dataset_id, document_id):
  1012. """
  1013. Remove chunks from a document.
  1014. ---
  1015. tags:
  1016. - Chunks
  1017. security:
  1018. - ApiKeyAuth: []
  1019. parameters:
  1020. - in: path
  1021. name: dataset_id
  1022. type: string
  1023. required: true
  1024. description: ID of the dataset.
  1025. - in: path
  1026. name: document_id
  1027. type: string
  1028. required: true
  1029. description: ID of the document.
  1030. - in: body
  1031. name: body
  1032. description: Chunk removal parameters.
  1033. required: true
  1034. schema:
  1035. type: object
  1036. properties:
  1037. chunk_ids:
  1038. type: array
  1039. items:
  1040. type: string
  1041. description: List of chunk IDs to remove.
  1042. - in: header
  1043. name: Authorization
  1044. type: string
  1045. required: true
  1046. description: Bearer token for authentication.
  1047. responses:
  1048. 200:
  1049. description: Chunks removed successfully.
  1050. schema:
  1051. type: object
  1052. """
  1053. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1054. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1055. req = request.json
  1056. condition = {"doc_id": document_id}
  1057. if "chunk_ids" in req:
  1058. condition["id"] = req["chunk_ids"]
  1059. chunk_number = settings.docStoreConn.delete(condition, search.index_name(tenant_id), dataset_id)
  1060. if chunk_number != 0:
  1061. DocumentService.decrement_chunk_num(document_id, dataset_id, 1, chunk_number, 0)
  1062. if "chunk_ids" in req and chunk_number != len(req["chunk_ids"]):
  1063. return get_error_data_result(message=f"rm_chunk deleted chunks {chunk_number}, expect {len(req['chunk_ids'])}")
  1064. return get_result(message=f"deleted {chunk_number} chunks")
  1065. @manager.route( # noqa: F821
  1066. "/datasets/<dataset_id>/documents/<document_id>/chunks/<chunk_id>", methods=["PUT"]
  1067. )
  1068. @token_required
  1069. def update_chunk(tenant_id, dataset_id, document_id, chunk_id):
  1070. """
  1071. Update a chunk within a document.
  1072. ---
  1073. tags:
  1074. - Chunks
  1075. security:
  1076. - ApiKeyAuth: []
  1077. parameters:
  1078. - in: path
  1079. name: dataset_id
  1080. type: string
  1081. required: true
  1082. description: ID of the dataset.
  1083. - in: path
  1084. name: document_id
  1085. type: string
  1086. required: true
  1087. description: ID of the document.
  1088. - in: path
  1089. name: chunk_id
  1090. type: string
  1091. required: true
  1092. description: ID of the chunk to update.
  1093. - in: body
  1094. name: body
  1095. description: Chunk update parameters.
  1096. required: true
  1097. schema:
  1098. type: object
  1099. properties:
  1100. content:
  1101. type: string
  1102. description: Updated content of the chunk.
  1103. important_keywords:
  1104. type: array
  1105. items:
  1106. type: string
  1107. description: Updated important keywords.
  1108. available:
  1109. type: boolean
  1110. description: Availability status of the chunk.
  1111. - in: header
  1112. name: Authorization
  1113. type: string
  1114. required: true
  1115. description: Bearer token for authentication.
  1116. responses:
  1117. 200:
  1118. description: Chunk updated successfully.
  1119. schema:
  1120. type: object
  1121. """
  1122. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), [dataset_id])
  1123. if chunk is None:
  1124. return get_error_data_result(f"Can't find this chunk {chunk_id}")
  1125. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1126. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1127. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  1128. if not doc:
  1129. return get_error_data_result(
  1130. message=f"You don't own the document {document_id}."
  1131. )
  1132. doc = doc[0]
  1133. req = request.json
  1134. if "content" in req:
  1135. content = req["content"]
  1136. else:
  1137. content = chunk.get("content_with_weight", "")
  1138. d = {"id": chunk_id, "content_with_weight": content}
  1139. d["content_ltks"] = rag_tokenizer.tokenize(d["content_with_weight"])
  1140. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1141. if "important_keywords" in req:
  1142. if not isinstance(req["important_keywords"], list):
  1143. return get_error_data_result("`important_keywords` should be a list")
  1144. d["important_kwd"] = req.get("important_keywords", [])
  1145. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
  1146. if "questions" in req:
  1147. if not isinstance(req["questions"], list):
  1148. return get_error_data_result("`questions` should be a list")
  1149. d["question_kwd"] = req.get("questions")
  1150. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req["questions"]))
  1151. if "available" in req:
  1152. d["available_int"] = int(req["available"])
  1153. embd_id = DocumentService.get_embd_id(document_id)
  1154. embd_mdl = TenantLLMService.model_instance(
  1155. tenant_id, LLMType.EMBEDDING.value, embd_id
  1156. )
  1157. if doc.parser_id == ParserType.QA:
  1158. arr = [t for t in re.split(r"[\n\t]", d["content_with_weight"]) if len(t) > 1]
  1159. if len(arr) != 2:
  1160. return get_error_data_result(
  1161. message="Q&A must be separated by TAB/ENTER key."
  1162. )
  1163. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  1164. d = beAdoc(
  1165. d, arr[0], arr[1], not any([rag_tokenizer.is_chinese(t) for t in q + a])
  1166. )
  1167. v, c = embd_mdl.encode([doc.name, d["content_with_weight"] if not d.get("question_kwd") else "\n".join(d["question_kwd"])])
  1168. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  1169. d["q_%d_vec" % len(v)] = v.tolist()
  1170. settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)
  1171. return get_result()
  1172. @manager.route("/retrieval", methods=["POST"]) # noqa: F821
  1173. @token_required
  1174. def retrieval_test(tenant_id):
  1175. """
  1176. Retrieve chunks based on a query.
  1177. ---
  1178. tags:
  1179. - Retrieval
  1180. security:
  1181. - ApiKeyAuth: []
  1182. parameters:
  1183. - in: body
  1184. name: body
  1185. description: Retrieval parameters.
  1186. required: true
  1187. schema:
  1188. type: object
  1189. properties:
  1190. dataset_ids:
  1191. type: array
  1192. items:
  1193. type: string
  1194. required: true
  1195. description: List of dataset IDs to search in.
  1196. question:
  1197. type: string
  1198. required: true
  1199. description: Query string.
  1200. document_ids:
  1201. type: array
  1202. items:
  1203. type: string
  1204. description: List of document IDs to filter.
  1205. similarity_threshold:
  1206. type: number
  1207. format: float
  1208. description: Similarity threshold.
  1209. vector_similarity_weight:
  1210. type: number
  1211. format: float
  1212. description: Vector similarity weight.
  1213. top_k:
  1214. type: integer
  1215. description: Maximum number of chunks to return.
  1216. highlight:
  1217. type: boolean
  1218. description: Whether to highlight matched content.
  1219. - in: header
  1220. name: Authorization
  1221. type: string
  1222. required: true
  1223. description: Bearer token for authentication.
  1224. responses:
  1225. 200:
  1226. description: Retrieval results.
  1227. schema:
  1228. type: object
  1229. properties:
  1230. chunks:
  1231. type: array
  1232. items:
  1233. type: object
  1234. properties:
  1235. id:
  1236. type: string
  1237. description: Chunk ID.
  1238. content:
  1239. type: string
  1240. description: Chunk content.
  1241. document_id:
  1242. type: string
  1243. description: ID of the document.
  1244. dataset_id:
  1245. type: string
  1246. description: ID of the dataset.
  1247. similarity:
  1248. type: number
  1249. format: float
  1250. description: Similarity score.
  1251. """
  1252. req = request.json
  1253. if not req.get("dataset_ids"):
  1254. return get_error_data_result("`dataset_ids` is required.")
  1255. kb_ids = req["dataset_ids"]
  1256. if not isinstance(kb_ids, list):
  1257. return get_error_data_result("`dataset_ids` should be a list")
  1258. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  1259. for id in kb_ids:
  1260. if not KnowledgebaseService.accessible(kb_id=id, user_id=tenant_id):
  1261. return get_error_data_result(f"You don't own the dataset {id}.")
  1262. embd_nms = list(set([kb.embd_id for kb in kbs]))
  1263. if len(embd_nms) != 1:
  1264. return get_result(
  1265. message='Datasets use different embedding models."',
  1266. code=settings.RetCode.AUTHENTICATION_ERROR,
  1267. )
  1268. if "question" not in req:
  1269. return get_error_data_result("`question` is required.")
  1270. page = int(req.get("page", 1))
  1271. size = int(req.get("page_size", 30))
  1272. question = req["question"]
  1273. doc_ids = req.get("document_ids", [])
  1274. if not isinstance(doc_ids, list):
  1275. return get_error_data_result("`documents` should be a list")
  1276. doc_ids_list = KnowledgebaseService.list_documents_by_ids(kb_ids)
  1277. for doc_id in doc_ids:
  1278. if doc_id not in doc_ids_list:
  1279. return get_error_data_result(
  1280. f"The datasets don't own the document {doc_id}"
  1281. )
  1282. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  1283. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  1284. top = int(req.get("top_k", 1024))
  1285. if req.get("highlight") == "False" or req.get("highlight") == "false":
  1286. highlight = False
  1287. else:
  1288. highlight = True
  1289. try:
  1290. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  1291. if not e:
  1292. return get_error_data_result(message="Dataset not found!")
  1293. embd_mdl = TenantLLMService.model_instance(
  1294. kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id
  1295. )
  1296. rerank_mdl = None
  1297. if req.get("rerank_id"):
  1298. rerank_mdl = TenantLLMService.model_instance(
  1299. kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"]
  1300. )
  1301. if req.get("keyword", False):
  1302. chat_mdl = TenantLLMService.model_instance(kb.tenant_id, LLMType.CHAT)
  1303. question += keyword_extraction(chat_mdl, question)
  1304. retr = settings.retrievaler if kb.parser_id != ParserType.KG else settings.kg_retrievaler
  1305. ranks = retr.retrieval(
  1306. question,
  1307. embd_mdl,
  1308. kb.tenant_id,
  1309. kb_ids,
  1310. page,
  1311. size,
  1312. similarity_threshold,
  1313. vector_similarity_weight,
  1314. top,
  1315. doc_ids,
  1316. rerank_mdl=rerank_mdl,
  1317. highlight=highlight,
  1318. )
  1319. for c in ranks["chunks"]:
  1320. c.pop("vector", None)
  1321. ##rename keys
  1322. renamed_chunks = []
  1323. for chunk in ranks["chunks"]:
  1324. key_mapping = {
  1325. "chunk_id": "id",
  1326. "content_with_weight": "content",
  1327. "doc_id": "document_id",
  1328. "important_kwd": "important_keywords",
  1329. "question_kwd": "questions",
  1330. "docnm_kwd": "document_keyword",
  1331. }
  1332. rename_chunk = {}
  1333. for key, value in chunk.items():
  1334. new_key = key_mapping.get(key, key)
  1335. rename_chunk[new_key] = value
  1336. renamed_chunks.append(rename_chunk)
  1337. ranks["chunks"] = renamed_chunks
  1338. return get_result(data=ranks)
  1339. except Exception as e:
  1340. if str(e).find("not_found") > 0:
  1341. return get_result(
  1342. message="No chunk found! Check the chunk status please!",
  1343. code=settings.RetCode.DATA_ERROR,
  1344. )
  1345. return server_error_response(e)