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

doc.py 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387
  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, LLMBundle
  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. if req.get("id"):
  817. chunk = settings.docStoreConn.get(req.get("id"), search.index_name(tenant_id), [dataset_id])
  818. k = []
  819. for n in chunk.keys():
  820. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  821. k.append(n)
  822. for n in k:
  823. del chunk[n]
  824. if not chunk:
  825. return get_error_data_result(f"Chunk `{req.get('id')}` not found.")
  826. res['total'] = 1
  827. final_chunk = {
  828. "id":chunk.get("id",chunk.get("chunk_id")),
  829. "content":chunk["content_with_weight"],
  830. "document_id":chunk.get("doc_id",chunk.get("document_id")),
  831. "docnm_kwd":chunk["docnm_kwd"],
  832. "important_keywords":chunk.get("important_kwd",[]),
  833. "questions":chunk.get("question_kwd",[]),
  834. "dataset_id":chunk.get("kb_id",chunk.get("dataset_id")),
  835. "image_id":chunk["img_id"],
  836. "available":bool(chunk.get("available_int",1)),
  837. "positions":chunk.get("position_int",[]),
  838. }
  839. res["chunks"].append(final_chunk)
  840. _ = Chunk(**final_chunk)
  841. elif settings.docStoreConn.indexExist(search.index_name(tenant_id), dataset_id):
  842. sres = settings.retrievaler.search(query, search.index_name(tenant_id), [dataset_id], emb_mdl=None,
  843. highlight=True)
  844. res["total"] = sres.total
  845. for id in sres.ids:
  846. d = {
  847. "id": id,
  848. "content": (
  849. rmSpace(sres.highlight[id])
  850. if question and id in sres.highlight
  851. else sres.field[id].get("content_with_weight", "")
  852. ),
  853. "document_id": sres.field[id]["doc_id"],
  854. "docnm_kwd": sres.field[id]["docnm_kwd"],
  855. "important_keywords": sres.field[id].get("important_kwd", []),
  856. "questions": sres.field[id].get("question_kwd", []),
  857. "dataset_id": sres.field[id].get("kb_id", sres.field[id].get("dataset_id")),
  858. "image_id": sres.field[id].get("img_id", ""),
  859. "available": bool(sres.field[id].get("available_int", 1)),
  860. "positions": sres.field[id].get("position_int",[]),
  861. }
  862. res["chunks"].append(d)
  863. _ = Chunk(**d) # validate the chunk
  864. return get_result(data=res)
  865. @manager.route( # noqa: F821
  866. "/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["POST"]
  867. )
  868. @token_required
  869. def add_chunk(tenant_id, dataset_id, document_id):
  870. """
  871. Add a chunk to a document.
  872. ---
  873. tags:
  874. - Chunks
  875. security:
  876. - ApiKeyAuth: []
  877. parameters:
  878. - in: path
  879. name: dataset_id
  880. type: string
  881. required: true
  882. description: ID of the dataset.
  883. - in: path
  884. name: document_id
  885. type: string
  886. required: true
  887. description: ID of the document.
  888. - in: body
  889. name: body
  890. description: Chunk data.
  891. required: true
  892. schema:
  893. type: object
  894. properties:
  895. content:
  896. type: string
  897. required: true
  898. description: Content of the chunk.
  899. important_keywords:
  900. type: array
  901. items:
  902. type: string
  903. description: Important keywords.
  904. - in: header
  905. name: Authorization
  906. type: string
  907. required: true
  908. description: Bearer token for authentication.
  909. responses:
  910. 200:
  911. description: Chunk added successfully.
  912. schema:
  913. type: object
  914. properties:
  915. chunk:
  916. type: object
  917. properties:
  918. id:
  919. type: string
  920. description: Chunk ID.
  921. content:
  922. type: string
  923. description: Chunk content.
  924. document_id:
  925. type: string
  926. description: ID of the document.
  927. important_keywords:
  928. type: array
  929. items:
  930. type: string
  931. description: Important keywords.
  932. """
  933. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  934. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  935. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  936. if not doc:
  937. return get_error_data_result(
  938. message=f"You don't own the document {document_id}."
  939. )
  940. doc = doc[0]
  941. req = request.json
  942. if not req.get("content"):
  943. return get_error_data_result(message="`content` is required")
  944. if "important_keywords" in req:
  945. if not isinstance(req["important_keywords"], list):
  946. return get_error_data_result(
  947. "`important_keywords` is required to be a list"
  948. )
  949. if "questions" in req:
  950. if not isinstance(req["questions"], list):
  951. return get_error_data_result(
  952. "`questions` is required to be a list"
  953. )
  954. chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
  955. d = {
  956. "id": chunk_id,
  957. "content_ltks": rag_tokenizer.tokenize(req["content"]),
  958. "content_with_weight": req["content"],
  959. }
  960. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  961. d["important_kwd"] = req.get("important_keywords", [])
  962. d["important_tks"] = rag_tokenizer.tokenize(
  963. " ".join(req.get("important_keywords", []))
  964. )
  965. d["question_kwd"] = req.get("questions", [])
  966. d["question_tks"] = rag_tokenizer.tokenize(
  967. "\n".join(req.get("questions", []))
  968. )
  969. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  970. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  971. d["kb_id"] = dataset_id
  972. d["docnm_kwd"] = doc.name
  973. d["doc_id"] = document_id
  974. embd_id = DocumentService.get_embd_id(document_id)
  975. embd_mdl = TenantLLMService.model_instance(
  976. tenant_id, LLMType.EMBEDDING.value, embd_id
  977. )
  978. v, c = embd_mdl.encode([doc.name, req["content"] if not d["question_kwd"] else "\n".join(d["question_kwd"])])
  979. v = 0.1 * v[0] + 0.9 * v[1]
  980. d["q_%d_vec" % len(v)] = v.tolist()
  981. settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
  982. DocumentService.increment_chunk_num(doc.id, doc.kb_id, c, 1, 0)
  983. # rename keys
  984. key_mapping = {
  985. "id": "id",
  986. "content_with_weight": "content",
  987. "doc_id": "document_id",
  988. "important_kwd": "important_keywords",
  989. "question_kwd": "questions",
  990. "kb_id": "dataset_id",
  991. "create_timestamp_flt": "create_timestamp",
  992. "create_time": "create_time",
  993. "document_keyword": "document",
  994. }
  995. renamed_chunk = {}
  996. for key, value in d.items():
  997. if key in key_mapping:
  998. new_key = key_mapping.get(key, key)
  999. renamed_chunk[new_key] = value
  1000. _ = Chunk(**renamed_chunk) # validate the chunk
  1001. return get_result(data={"chunk": renamed_chunk})
  1002. # return get_result(data={"chunk_id": chunk_id})
  1003. @manager.route( # noqa: F821
  1004. "datasets/<dataset_id>/documents/<document_id>/chunks", methods=["DELETE"]
  1005. )
  1006. @token_required
  1007. def rm_chunk(tenant_id, dataset_id, document_id):
  1008. """
  1009. Remove chunks from a document.
  1010. ---
  1011. tags:
  1012. - Chunks
  1013. security:
  1014. - ApiKeyAuth: []
  1015. parameters:
  1016. - in: path
  1017. name: dataset_id
  1018. type: string
  1019. required: true
  1020. description: ID of the dataset.
  1021. - in: path
  1022. name: document_id
  1023. type: string
  1024. required: true
  1025. description: ID of the document.
  1026. - in: body
  1027. name: body
  1028. description: Chunk removal parameters.
  1029. required: true
  1030. schema:
  1031. type: object
  1032. properties:
  1033. chunk_ids:
  1034. type: array
  1035. items:
  1036. type: string
  1037. description: List of chunk IDs to remove.
  1038. - in: header
  1039. name: Authorization
  1040. type: string
  1041. required: true
  1042. description: Bearer token for authentication.
  1043. responses:
  1044. 200:
  1045. description: Chunks removed successfully.
  1046. schema:
  1047. type: object
  1048. """
  1049. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1050. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1051. req = request.json
  1052. condition = {"doc_id": document_id}
  1053. if "chunk_ids" in req:
  1054. condition["id"] = req["chunk_ids"]
  1055. chunk_number = settings.docStoreConn.delete(condition, search.index_name(tenant_id), dataset_id)
  1056. if chunk_number != 0:
  1057. DocumentService.decrement_chunk_num(document_id, dataset_id, 1, chunk_number, 0)
  1058. if "chunk_ids" in req and chunk_number != len(req["chunk_ids"]):
  1059. return get_error_data_result(message=f"rm_chunk deleted chunks {chunk_number}, expect {len(req['chunk_ids'])}")
  1060. return get_result(message=f"deleted {chunk_number} chunks")
  1061. @manager.route( # noqa: F821
  1062. "/datasets/<dataset_id>/documents/<document_id>/chunks/<chunk_id>", methods=["PUT"]
  1063. )
  1064. @token_required
  1065. def update_chunk(tenant_id, dataset_id, document_id, chunk_id):
  1066. """
  1067. Update a chunk within a document.
  1068. ---
  1069. tags:
  1070. - Chunks
  1071. security:
  1072. - ApiKeyAuth: []
  1073. parameters:
  1074. - in: path
  1075. name: dataset_id
  1076. type: string
  1077. required: true
  1078. description: ID of the dataset.
  1079. - in: path
  1080. name: document_id
  1081. type: string
  1082. required: true
  1083. description: ID of the document.
  1084. - in: path
  1085. name: chunk_id
  1086. type: string
  1087. required: true
  1088. description: ID of the chunk to update.
  1089. - in: body
  1090. name: body
  1091. description: Chunk update parameters.
  1092. required: true
  1093. schema:
  1094. type: object
  1095. properties:
  1096. content:
  1097. type: string
  1098. description: Updated content of the chunk.
  1099. important_keywords:
  1100. type: array
  1101. items:
  1102. type: string
  1103. description: Updated important keywords.
  1104. available:
  1105. type: boolean
  1106. description: Availability status of the chunk.
  1107. - in: header
  1108. name: Authorization
  1109. type: string
  1110. required: true
  1111. description: Bearer token for authentication.
  1112. responses:
  1113. 200:
  1114. description: Chunk updated successfully.
  1115. schema:
  1116. type: object
  1117. """
  1118. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), [dataset_id])
  1119. if chunk is None:
  1120. return get_error_data_result(f"Can't find this chunk {chunk_id}")
  1121. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1122. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1123. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  1124. if not doc:
  1125. return get_error_data_result(
  1126. message=f"You don't own the document {document_id}."
  1127. )
  1128. doc = doc[0]
  1129. req = request.json
  1130. if "content" in req:
  1131. content = req["content"]
  1132. else:
  1133. content = chunk.get("content_with_weight", "")
  1134. d = {"id": chunk_id, "content_with_weight": content}
  1135. d["content_ltks"] = rag_tokenizer.tokenize(d["content_with_weight"])
  1136. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1137. if "important_keywords" in req:
  1138. if not isinstance(req["important_keywords"], list):
  1139. return get_error_data_result("`important_keywords` should be a list")
  1140. d["important_kwd"] = req.get("important_keywords", [])
  1141. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
  1142. if "questions" in req:
  1143. if not isinstance(req["questions"], list):
  1144. return get_error_data_result("`questions` should be a list")
  1145. d["question_kwd"] = req.get("questions")
  1146. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req["questions"]))
  1147. if "available" in req:
  1148. d["available_int"] = int(req["available"])
  1149. embd_id = DocumentService.get_embd_id(document_id)
  1150. embd_mdl = TenantLLMService.model_instance(
  1151. tenant_id, LLMType.EMBEDDING.value, embd_id
  1152. )
  1153. if doc.parser_id == ParserType.QA:
  1154. arr = [t for t in re.split(r"[\n\t]", d["content_with_weight"]) if len(t) > 1]
  1155. if len(arr) != 2:
  1156. return get_error_data_result(
  1157. message="Q&A must be separated by TAB/ENTER key."
  1158. )
  1159. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  1160. d = beAdoc(
  1161. d, arr[0], arr[1], not any([rag_tokenizer.is_chinese(t) for t in q + a])
  1162. )
  1163. v, c = embd_mdl.encode([doc.name, d["content_with_weight"] if not d.get("question_kwd") else "\n".join(d["question_kwd"])])
  1164. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  1165. d["q_%d_vec" % len(v)] = v.tolist()
  1166. settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)
  1167. return get_result()
  1168. @manager.route("/retrieval", methods=["POST"]) # noqa: F821
  1169. @token_required
  1170. def retrieval_test(tenant_id):
  1171. """
  1172. Retrieve chunks based on a query.
  1173. ---
  1174. tags:
  1175. - Retrieval
  1176. security:
  1177. - ApiKeyAuth: []
  1178. parameters:
  1179. - in: body
  1180. name: body
  1181. description: Retrieval parameters.
  1182. required: true
  1183. schema:
  1184. type: object
  1185. properties:
  1186. dataset_ids:
  1187. type: array
  1188. items:
  1189. type: string
  1190. required: true
  1191. description: List of dataset IDs to search in.
  1192. question:
  1193. type: string
  1194. required: true
  1195. description: Query string.
  1196. document_ids:
  1197. type: array
  1198. items:
  1199. type: string
  1200. description: List of document IDs to filter.
  1201. similarity_threshold:
  1202. type: number
  1203. format: float
  1204. description: Similarity threshold.
  1205. vector_similarity_weight:
  1206. type: number
  1207. format: float
  1208. description: Vector similarity weight.
  1209. top_k:
  1210. type: integer
  1211. description: Maximum number of chunks to return.
  1212. highlight:
  1213. type: boolean
  1214. description: Whether to highlight matched content.
  1215. - in: header
  1216. name: Authorization
  1217. type: string
  1218. required: true
  1219. description: Bearer token for authentication.
  1220. responses:
  1221. 200:
  1222. description: Retrieval results.
  1223. schema:
  1224. type: object
  1225. properties:
  1226. chunks:
  1227. type: array
  1228. items:
  1229. type: object
  1230. properties:
  1231. id:
  1232. type: string
  1233. description: Chunk ID.
  1234. content:
  1235. type: string
  1236. description: Chunk content.
  1237. document_id:
  1238. type: string
  1239. description: ID of the document.
  1240. dataset_id:
  1241. type: string
  1242. description: ID of the dataset.
  1243. similarity:
  1244. type: number
  1245. format: float
  1246. description: Similarity score.
  1247. """
  1248. req = request.json
  1249. if not req.get("dataset_ids"):
  1250. return get_error_data_result("`dataset_ids` is required.")
  1251. kb_ids = req["dataset_ids"]
  1252. if not isinstance(kb_ids, list):
  1253. return get_error_data_result("`dataset_ids` should be a list")
  1254. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  1255. for id in kb_ids:
  1256. if not KnowledgebaseService.accessible(kb_id=id, user_id=tenant_id):
  1257. return get_error_data_result(f"You don't own the dataset {id}.")
  1258. embd_nms = list(set([kb.embd_id for kb in kbs]))
  1259. if len(embd_nms) != 1:
  1260. return get_result(
  1261. message='Datasets use different embedding models."',
  1262. code=settings.RetCode.AUTHENTICATION_ERROR,
  1263. )
  1264. if "question" not in req:
  1265. return get_error_data_result("`question` is required.")
  1266. page = int(req.get("page", 1))
  1267. size = int(req.get("page_size", 30))
  1268. question = req["question"]
  1269. doc_ids = req.get("document_ids", [])
  1270. if not isinstance(doc_ids, list):
  1271. return get_error_data_result("`documents` should be a list")
  1272. doc_ids_list = KnowledgebaseService.list_documents_by_ids(kb_ids)
  1273. for doc_id in doc_ids:
  1274. if doc_id not in doc_ids_list:
  1275. return get_error_data_result(
  1276. f"The datasets don't own the document {doc_id}"
  1277. )
  1278. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  1279. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  1280. top = int(req.get("top_k", 1024))
  1281. if req.get("highlight") == "False" or req.get("highlight") == "false":
  1282. highlight = False
  1283. else:
  1284. highlight = True
  1285. try:
  1286. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  1287. if not e:
  1288. return get_error_data_result(message="Dataset not found!")
  1289. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id)
  1290. rerank_mdl = None
  1291. if req.get("rerank_id"):
  1292. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK, llm_name=req["rerank_id"])
  1293. if req.get("keyword", False):
  1294. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  1295. question += keyword_extraction(chat_mdl, question)
  1296. retr = settings.retrievaler if kb.parser_id != ParserType.KG else settings.kg_retrievaler
  1297. ranks = retr.retrieval(
  1298. question,
  1299. embd_mdl,
  1300. kb.tenant_id,
  1301. kb_ids,
  1302. page,
  1303. size,
  1304. similarity_threshold,
  1305. vector_similarity_weight,
  1306. top,
  1307. doc_ids,
  1308. rerank_mdl=rerank_mdl,
  1309. highlight=highlight,
  1310. )
  1311. for c in ranks["chunks"]:
  1312. c.pop("vector", None)
  1313. ##rename keys
  1314. renamed_chunks = []
  1315. for chunk in ranks["chunks"]:
  1316. key_mapping = {
  1317. "chunk_id": "id",
  1318. "content_with_weight": "content",
  1319. "doc_id": "document_id",
  1320. "important_kwd": "important_keywords",
  1321. "question_kwd": "questions",
  1322. "docnm_kwd": "document_keyword",
  1323. "kb_id":"dataset_id"
  1324. }
  1325. rename_chunk = {}
  1326. for key, value in chunk.items():
  1327. new_key = key_mapping.get(key, key)
  1328. rename_chunk[new_key] = value
  1329. renamed_chunks.append(rename_chunk)
  1330. ranks["chunks"] = renamed_chunks
  1331. return get_result(data=ranks)
  1332. except Exception as e:
  1333. if str(e).find("not_found") > 0:
  1334. return get_result(
  1335. message="No chunk found! Check the chunk status please!",
  1336. code=settings.RetCode.DATA_ERROR,
  1337. )
  1338. return server_error_response(e)