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ů.

dataset_api.py 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  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. import os
  16. import pathlib
  17. import re
  18. import warnings
  19. from io import BytesIO
  20. from flask import request, send_file
  21. from flask_login import login_required, current_user
  22. from httpx import HTTPError
  23. from minio import S3Error
  24. from api.contants import NAME_LENGTH_LIMIT
  25. from api.db import FileType, ParserType, FileSource
  26. from api.db import StatusEnum
  27. from api.db.db_models import File
  28. from api.db.services import duplicate_name
  29. from api.db.services.document_service import DocumentService
  30. from api.db.services.file2document_service import File2DocumentService
  31. from api.db.services.file_service import FileService
  32. from api.db.services.knowledgebase_service import KnowledgebaseService
  33. from api.db.services.user_service import TenantService
  34. from api.settings import RetCode
  35. from api.utils import get_uuid
  36. from api.utils.api_utils import construct_json_result, construct_error_response
  37. from api.utils.api_utils import construct_result, validate_request
  38. from api.utils.file_utils import filename_type, thumbnail
  39. from rag.utils.minio_conn import MINIO
  40. MAXIMUM_OF_UPLOADING_FILES = 256
  41. # ------------------------------ create a dataset ---------------------------------------
  42. @manager.route("/", methods=["POST"])
  43. @login_required # use login
  44. @validate_request("name") # check name key
  45. def create_dataset():
  46. # Check if Authorization header is present
  47. authorization_token = request.headers.get("Authorization")
  48. if not authorization_token:
  49. return construct_json_result(code=RetCode.AUTHENTICATION_ERROR, message="Authorization header is missing.")
  50. # TODO: Login or API key
  51. # objs = APIToken.query(token=authorization_token)
  52. #
  53. # # Authorization error
  54. # if not objs:
  55. # return construct_json_result(code=RetCode.AUTHENTICATION_ERROR, message="Token is invalid.")
  56. #
  57. # tenant_id = objs[0].tenant_id
  58. tenant_id = current_user.id
  59. request_body = request.json
  60. # In case that there's no name
  61. if "name" not in request_body:
  62. return construct_json_result(code=RetCode.DATA_ERROR, message="Expected 'name' field in request body")
  63. dataset_name = request_body["name"]
  64. # empty dataset_name
  65. if not dataset_name:
  66. return construct_json_result(code=RetCode.DATA_ERROR, message="Empty dataset name")
  67. # In case that there's space in the head or the tail
  68. dataset_name = dataset_name.strip()
  69. # In case that the length of the name exceeds the limit
  70. dataset_name_length = len(dataset_name)
  71. if dataset_name_length > NAME_LENGTH_LIMIT:
  72. return construct_json_result(
  73. code=RetCode.DATA_ERROR,
  74. message=f"Dataset name: {dataset_name} with length {dataset_name_length} exceeds {NAME_LENGTH_LIMIT}!")
  75. # In case that there are other fields in the data-binary
  76. if len(request_body.keys()) > 1:
  77. name_list = []
  78. for key_name in request_body.keys():
  79. if key_name != "name":
  80. name_list.append(key_name)
  81. return construct_json_result(code=RetCode.DATA_ERROR,
  82. message=f"fields: {name_list}, are not allowed in request body.")
  83. # If there is a duplicate name, it will modify it to make it unique
  84. request_body["name"] = duplicate_name(
  85. KnowledgebaseService.query,
  86. name=dataset_name,
  87. tenant_id=tenant_id,
  88. status=StatusEnum.VALID.value)
  89. try:
  90. request_body["id"] = get_uuid()
  91. request_body["tenant_id"] = tenant_id
  92. request_body["created_by"] = tenant_id
  93. exist, t = TenantService.get_by_id(tenant_id)
  94. if not exist:
  95. return construct_result(code=RetCode.AUTHENTICATION_ERROR, message="Tenant not found.")
  96. request_body["embd_id"] = t.embd_id
  97. if not KnowledgebaseService.save(**request_body):
  98. # failed to create new dataset
  99. return construct_result()
  100. return construct_json_result(code=RetCode.SUCCESS,
  101. data={"dataset_name": request_body["name"], "dataset_id": request_body["id"]})
  102. except Exception as e:
  103. return construct_error_response(e)
  104. # -----------------------------list datasets-------------------------------------------------------
  105. @manager.route("/", methods=["GET"])
  106. @login_required
  107. def list_datasets():
  108. offset = request.args.get("offset", 0)
  109. count = request.args.get("count", -1)
  110. orderby = request.args.get("orderby", "create_time")
  111. desc = request.args.get("desc", True)
  112. try:
  113. tenants = TenantService.get_joined_tenants_by_user_id(current_user.id)
  114. datasets = KnowledgebaseService.get_by_tenant_ids_by_offset(
  115. [m["tenant_id"] for m in tenants], current_user.id, int(offset), int(count), orderby, desc)
  116. return construct_json_result(data=datasets, code=RetCode.SUCCESS, message=f"List datasets successfully!")
  117. except Exception as e:
  118. return construct_error_response(e)
  119. except HTTPError as http_err:
  120. return construct_json_result(http_err)
  121. # ---------------------------------delete a dataset ----------------------------
  122. @manager.route("/<dataset_id>", methods=["DELETE"])
  123. @login_required
  124. def remove_dataset(dataset_id):
  125. try:
  126. datasets = KnowledgebaseService.query(created_by=current_user.id, id=dataset_id)
  127. # according to the id, searching for the dataset
  128. if not datasets:
  129. return construct_json_result(message=f"The dataset cannot be found for your current account.",
  130. code=RetCode.OPERATING_ERROR)
  131. # Iterating the documents inside the dataset
  132. for doc in DocumentService.query(kb_id=dataset_id):
  133. if not DocumentService.remove_document(doc, datasets[0].tenant_id):
  134. # the process of deleting failed
  135. return construct_json_result(code=RetCode.DATA_ERROR,
  136. message="There was an error during the document removal process. "
  137. "Please check the status of the RAGFlow server and try the removal again.")
  138. # delete the other files
  139. f2d = File2DocumentService.get_by_document_id(doc.id)
  140. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
  141. File2DocumentService.delete_by_document_id(doc.id)
  142. # delete the dataset
  143. if not KnowledgebaseService.delete_by_id(dataset_id):
  144. return construct_json_result(code=RetCode.DATA_ERROR, message="There was an error during the dataset removal process. "
  145. "Please check the status of the RAGFlow server and try the removal again.")
  146. # success
  147. return construct_json_result(code=RetCode.SUCCESS, message=f"Remove dataset: {dataset_id} successfully")
  148. except Exception as e:
  149. return construct_error_response(e)
  150. # ------------------------------ get details of a dataset ----------------------------------------
  151. @manager.route("/<dataset_id>", methods=["GET"])
  152. @login_required
  153. def get_dataset(dataset_id):
  154. try:
  155. dataset = KnowledgebaseService.get_detail(dataset_id)
  156. if not dataset:
  157. return construct_json_result(code=RetCode.DATA_ERROR, message="Can't find this dataset!")
  158. return construct_json_result(data=dataset, code=RetCode.SUCCESS)
  159. except Exception as e:
  160. return construct_json_result(e)
  161. # ------------------------------ update a dataset --------------------------------------------
  162. @manager.route("/<dataset_id>", methods=["PUT"])
  163. @login_required
  164. def update_dataset(dataset_id):
  165. req = request.json
  166. try:
  167. # the request cannot be empty
  168. if not req:
  169. return construct_json_result(code=RetCode.DATA_ERROR, message="Please input at least one parameter that "
  170. "you want to update!")
  171. # check whether the dataset can be found
  172. if not KnowledgebaseService.query(created_by=current_user.id, id=dataset_id):
  173. return construct_json_result(message=f"Only the owner of knowledgebase is authorized for this operation!",
  174. code=RetCode.OPERATING_ERROR)
  175. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  176. # check whether there is this dataset
  177. if not exist:
  178. return construct_json_result(code=RetCode.DATA_ERROR, message="This dataset cannot be found!")
  179. if "name" in req:
  180. name = req["name"].strip()
  181. # check whether there is duplicate name
  182. if name.lower() != dataset.name.lower() \
  183. and len(KnowledgebaseService.query(name=name, tenant_id=current_user.id,
  184. status=StatusEnum.VALID.value)) > 1:
  185. return construct_json_result(code=RetCode.DATA_ERROR, message=f"The name: {name.lower()} is already used by other "
  186. f"datasets. Please choose a different name.")
  187. dataset_updating_data = {}
  188. chunk_num = req.get("chunk_num")
  189. # modify the value of 11 parameters
  190. # 2 parameters: embedding id and chunk method
  191. # only if chunk_num is 0, the user can update the embedding id
  192. if req.get("embedding_model_id"):
  193. if chunk_num == 0:
  194. dataset_updating_data["embd_id"] = req["embedding_model_id"]
  195. else:
  196. construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document in this "
  197. "dataset, so you cannot change the embedding "
  198. "model.")
  199. # only if chunk_num is 0, the user can update the chunk_method
  200. if req.get("chunk_method"):
  201. if chunk_num == 0:
  202. dataset_updating_data['parser_id'] = req["chunk_method"]
  203. else:
  204. construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document "
  205. "in this dataset, so you cannot "
  206. "change the chunk method.")
  207. # convert the photo parameter to avatar
  208. if req.get("photo"):
  209. dataset_updating_data["avatar"] = req["photo"]
  210. # layout_recognize
  211. if "layout_recognize" in req:
  212. if "parser_config" not in dataset_updating_data:
  213. dataset_updating_data['parser_config'] = {}
  214. dataset_updating_data['parser_config']['layout_recognize'] = req['layout_recognize']
  215. # TODO: updating use_raptor needs to construct a class
  216. # 6 parameters
  217. for key in ["name", "language", "description", "permission", "id", "token_num"]:
  218. if key in req:
  219. dataset_updating_data[key] = req.get(key)
  220. # update
  221. if not KnowledgebaseService.update_by_id(dataset.id, dataset_updating_data):
  222. return construct_json_result(code=RetCode.OPERATING_ERROR, message="Failed to update! "
  223. "Please check the status of RAGFlow "
  224. "server and try again!")
  225. exist, dataset = KnowledgebaseService.get_by_id(dataset.id)
  226. if not exist:
  227. return construct_json_result(code=RetCode.DATA_ERROR, message="Failed to get the dataset "
  228. "using the dataset ID.")
  229. return construct_json_result(data=dataset.to_json(), code=RetCode.SUCCESS)
  230. except Exception as e:
  231. return construct_error_response(e)
  232. # --------------------------------content management ----------------------------------------------
  233. # ----------------------------upload files-----------------------------------------------------
  234. @manager.route("/<dataset_id>/documents/", methods=["POST"])
  235. @login_required
  236. def upload_documents(dataset_id):
  237. # no files
  238. if not request.files:
  239. return construct_json_result(
  240. message="There is no file!", code=RetCode.ARGUMENT_ERROR)
  241. # the number of uploading files exceeds the limit
  242. file_objs = request.files.getlist("file")
  243. num_file_objs = len(file_objs)
  244. if num_file_objs > MAXIMUM_OF_UPLOADING_FILES:
  245. return construct_json_result(code=RetCode.DATA_ERROR, message=f"You try to upload {num_file_objs} files, "
  246. f"which exceeds the maximum number of uploading files: {MAXIMUM_OF_UPLOADING_FILES}")
  247. # no dataset
  248. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  249. if not exist:
  250. return construct_json_result(message="Can't find this dataset", code=RetCode.DATA_ERROR)
  251. for file_obj in file_objs:
  252. file_name = file_obj.filename
  253. # no name
  254. if not file_name:
  255. return construct_json_result(
  256. message="There is a file without name!", code=RetCode.ARGUMENT_ERROR)
  257. # TODO: support the remote files
  258. if 'http' in file_name:
  259. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message="Remote files have not unsupported.")
  260. # get the root_folder
  261. root_folder = FileService.get_root_folder(current_user.id)
  262. # get the id of the root_folder
  263. parent_file_id = root_folder["id"] # document id
  264. # this is for the new user, create '.knowledgebase' file
  265. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  266. # go inside this folder, get the kb_root_folder
  267. kb_root_folder = FileService.get_kb_folder(current_user.id)
  268. # link the file management to the kb_folder
  269. kb_folder = FileService.new_a_file_from_kb(dataset.tenant_id, dataset.name, kb_root_folder["id"])
  270. # grab all the errs
  271. err = []
  272. MAX_FILE_NUM_PER_USER = int(os.environ.get("MAX_FILE_NUM_PER_USER", 0))
  273. uploaded_docs_json = []
  274. for file in file_objs:
  275. try:
  276. # TODO: get this value from the database as some tenants have this limit while others don't
  277. if MAX_FILE_NUM_PER_USER > 0 and DocumentService.get_doc_count(dataset.tenant_id) >= MAX_FILE_NUM_PER_USER:
  278. return construct_json_result(code=RetCode.DATA_ERROR,
  279. message="Exceed the maximum file number of a free user!")
  280. # deal with the duplicate name
  281. filename = duplicate_name(
  282. DocumentService.query,
  283. name=file.filename,
  284. kb_id=dataset.id)
  285. # deal with the unsupported type
  286. filetype = filename_type(filename)
  287. if filetype == FileType.OTHER.value:
  288. return construct_json_result(code=RetCode.DATA_ERROR,
  289. message="This type of file has not been supported yet!")
  290. # upload to the minio
  291. location = filename
  292. while MINIO.obj_exist(dataset_id, location):
  293. location += "_"
  294. blob = file.read()
  295. # the content is empty, raising a warning
  296. if blob == b'':
  297. warnings.warn(f"[WARNING]: The file {filename} is empty.")
  298. MINIO.put(dataset_id, location, blob)
  299. doc = {
  300. "id": get_uuid(),
  301. "kb_id": dataset.id,
  302. "parser_id": dataset.parser_id,
  303. "parser_config": dataset.parser_config,
  304. "created_by": current_user.id,
  305. "type": filetype,
  306. "name": filename,
  307. "location": location,
  308. "size": len(blob),
  309. "thumbnail": thumbnail(filename, blob)
  310. }
  311. if doc["type"] == FileType.VISUAL:
  312. doc["parser_id"] = ParserType.PICTURE.value
  313. if re.search(r"\.(ppt|pptx|pages)$", filename):
  314. doc["parser_id"] = ParserType.PRESENTATION.value
  315. DocumentService.insert(doc)
  316. FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
  317. uploaded_docs_json.append(doc)
  318. except Exception as e:
  319. err.append(file.filename + ": " + str(e))
  320. if err:
  321. # return all the errors
  322. return construct_json_result(message="\n".join(err), code=RetCode.SERVER_ERROR)
  323. # success
  324. return construct_json_result(data=uploaded_docs_json, code=RetCode.SUCCESS)
  325. # ----------------------------delete a file-----------------------------------------------------
  326. @manager.route("/<dataset_id>/documents/<document_id>", methods=["DELETE"])
  327. @login_required
  328. def delete_document(document_id, dataset_id): # string
  329. # get the root folder
  330. root_folder = FileService.get_root_folder(current_user.id)
  331. # parent file's id
  332. parent_file_id = root_folder["id"]
  333. # consider the new user
  334. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  335. # store all the errors that may have
  336. errors = ""
  337. try:
  338. # whether there is this document
  339. exist, doc = DocumentService.get_by_id(document_id)
  340. if not exist:
  341. return construct_json_result(message=f"Document {document_id} not found!", code=RetCode.DATA_ERROR)
  342. # whether this doc is authorized by this tenant
  343. tenant_id = DocumentService.get_tenant_id(document_id)
  344. if not tenant_id:
  345. return construct_json_result(
  346. message=f"You cannot delete this document {document_id} due to the authorization"
  347. f" reason!", code=RetCode.AUTHENTICATION_ERROR)
  348. # get the doc's id and location
  349. real_dataset_id, location = File2DocumentService.get_minio_address(doc_id=document_id)
  350. if real_dataset_id != dataset_id:
  351. return construct_json_result(message=f"The document {document_id} is not in the dataset: {dataset_id}, "
  352. f"but in the dataset: {real_dataset_id}.", code=RetCode.ARGUMENT_ERROR)
  353. # there is an issue when removing
  354. if not DocumentService.remove_document(doc, tenant_id):
  355. return construct_json_result(
  356. message="There was an error during the document removal process. Please check the status of the "
  357. "RAGFlow server and try the removal again.", code=RetCode.OPERATING_ERROR)
  358. # fetch the File2Document record associated with the provided document ID.
  359. file_to_doc = File2DocumentService.get_by_document_id(document_id)
  360. # delete the associated File record.
  361. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == file_to_doc[0].file_id])
  362. # delete the File2Document record itself using the document ID. This removes the
  363. # association between the document and the file after the File record has been deleted.
  364. File2DocumentService.delete_by_document_id(document_id)
  365. # delete it from minio
  366. MINIO.rm(dataset_id, location)
  367. except Exception as e:
  368. errors += str(e)
  369. if errors:
  370. return construct_json_result(data=False, message=errors, code=RetCode.SERVER_ERROR)
  371. return construct_json_result(data=True, code=RetCode.SUCCESS)
  372. # ----------------------------list files-----------------------------------------------------
  373. @manager.route('/<dataset_id>/documents/', methods=['GET'])
  374. @login_required
  375. def list_documents(dataset_id):
  376. if not dataset_id:
  377. return construct_json_result(
  378. data=False, message="Lack of 'dataset_id'", code=RetCode.ARGUMENT_ERROR)
  379. # searching keywords
  380. keywords = request.args.get("keywords", "")
  381. offset = request.args.get("offset", 0)
  382. count = request.args.get("count", -1)
  383. order_by = request.args.get("order_by", "create_time")
  384. descend = request.args.get("descend", True)
  385. try:
  386. docs, total = DocumentService.list_documents_in_dataset(dataset_id, int(offset), int(count), order_by,
  387. descend, keywords)
  388. return construct_json_result(data={"total": total, "docs": docs}, message=RetCode.SUCCESS)
  389. except Exception as e:
  390. return construct_error_response(e)
  391. # ----------------------------update: enable rename-----------------------------------------------------
  392. @manager.route("/<dataset_id>/documents/<document_id>", methods=["PUT"])
  393. @login_required
  394. def update_document(dataset_id, document_id):
  395. req = request.json
  396. try:
  397. legal_parameters = set()
  398. legal_parameters.add("name")
  399. legal_parameters.add("enable")
  400. legal_parameters.add("template_type")
  401. for key in req.keys():
  402. if key not in legal_parameters:
  403. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message=f"{key} is an illegal parameter.")
  404. # The request body cannot be empty
  405. if not req:
  406. return construct_json_result(
  407. code=RetCode.DATA_ERROR,
  408. message="Please input at least one parameter that you want to update!")
  409. # Check whether there is this dataset
  410. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  411. if not exist:
  412. return construct_json_result(code=RetCode.DATA_ERROR, message=f"This dataset {dataset_id} cannot be found!")
  413. # The document does not exist
  414. exist, document = DocumentService.get_by_id(document_id)
  415. if not exist:
  416. return construct_json_result(message=f"This document {document_id} cannot be found!",
  417. code=RetCode.ARGUMENT_ERROR)
  418. # Deal with the different keys
  419. updating_data = {}
  420. if "name" in req:
  421. new_name = req["name"]
  422. updating_data["name"] = new_name
  423. # Check whether the new_name is suitable
  424. # 1. no name value
  425. if not new_name:
  426. return construct_json_result(code=RetCode.DATA_ERROR, message="There is no new name.")
  427. # 2. In case that there's space in the head or the tail
  428. new_name = new_name.strip()
  429. # 3. Check whether the new_name has the same extension of file as before
  430. if pathlib.Path(new_name.lower()).suffix != pathlib.Path(
  431. document.name.lower()).suffix:
  432. return construct_json_result(
  433. data=False,
  434. message="The extension of file cannot be changed",
  435. code=RetCode.ARGUMENT_ERROR)
  436. # 4. Check whether the new name has already been occupied by other file
  437. for d in DocumentService.query(name=new_name, kb_id=document.kb_id):
  438. if d.name == new_name:
  439. return construct_json_result(
  440. message="Duplicated document name in the same dataset.",
  441. code=RetCode.ARGUMENT_ERROR)
  442. if "enable" in req:
  443. enable_value = req["enable"]
  444. if is_illegal_value_for_enum(enable_value, StatusEnum):
  445. return construct_json_result(message=f"Illegal value {enable_value} for 'enable' field.",
  446. code=RetCode.DATA_ERROR)
  447. updating_data["status"] = enable_value
  448. # TODO: Chunk-method - update parameters inside the json object parser_config
  449. if "template_type" in req:
  450. type_value = req["template_type"]
  451. if is_illegal_value_for_enum(type_value, ParserType):
  452. return construct_json_result(message=f"Illegal value {type_value} for 'template_type' field.",
  453. code=RetCode.DATA_ERROR)
  454. updating_data["parser_id"] = req["template_type"]
  455. # The process of updating
  456. if not DocumentService.update_by_id(document_id, updating_data):
  457. return construct_json_result(
  458. code=RetCode.OPERATING_ERROR,
  459. message="Failed to update document in the database! "
  460. "Please check the status of RAGFlow server and try again!")
  461. # name part: file service
  462. if "name" in req:
  463. # Get file by document id
  464. file_information = File2DocumentService.get_by_document_id(document_id)
  465. if file_information:
  466. exist, file = FileService.get_by_id(file_information[0].file_id)
  467. FileService.update_by_id(file.id, {"name": req["name"]})
  468. exist, document = DocumentService.get_by_id(document_id)
  469. # Success
  470. return construct_json_result(data=document.to_json(), message="Success", code=RetCode.SUCCESS)
  471. except Exception as e:
  472. return construct_error_response(e)
  473. # Helper method to judge whether it's an illegal value
  474. def is_illegal_value_for_enum(value, enum_class):
  475. return value not in enum_class.__members__.values()
  476. # ----------------------------download a file-----------------------------------------------------
  477. @manager.route("/<dataset_id>/documents/<document_id>", methods=["GET"])
  478. @login_required
  479. def download_document(dataset_id, document_id):
  480. try:
  481. # Check whether there is this dataset
  482. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  483. if not exist:
  484. return construct_json_result(code=RetCode.DATA_ERROR, message=f"This dataset '{dataset_id}' cannot be found!")
  485. # Check whether there is this document
  486. exist, document = DocumentService.get_by_id(document_id)
  487. if not exist:
  488. return construct_json_result(message=f"This document '{document_id}' cannot be found!",
  489. code=RetCode.ARGUMENT_ERROR)
  490. # The process of downloading
  491. doc_id, doc_location = File2DocumentService.get_minio_address(doc_id=document_id) # minio address
  492. file_stream = MINIO.get(doc_id, doc_location)
  493. if not file_stream:
  494. return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
  495. file = BytesIO(file_stream)
  496. # Use send_file with a proper filename and MIME type
  497. return send_file(
  498. file,
  499. as_attachment=True,
  500. download_name=document.name,
  501. mimetype='application/octet-stream' # Set a default MIME type
  502. )
  503. # Error
  504. except Exception as e:
  505. return construct_error_response(e)
  506. # ----------------------------start parsing-----------------------------------------------------
  507. # ----------------------------stop parsing-----------------------------------------------------
  508. # ----------------------------show the status of the file-----------------------------------------------------
  509. # ----------------------------list the chunks of the file-----------------------------------------------------
  510. # -- --------------------------delete the chunk-----------------------------------------------------
  511. # ----------------------------edit the status of the chunk-----------------------------------------------------
  512. # ----------------------------insert a new chunk-----------------------------------------------------
  513. # ----------------------------upload a file-----------------------------------------------------
  514. # ----------------------------get a specific chunk-----------------------------------------------------
  515. # ----------------------------retrieval test-----------------------------------------------------