You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dataset_api.py 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  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 functools import partial
  20. from io import BytesIO
  21. from elasticsearch_dsl import Q
  22. from flask import request, send_file
  23. from flask_login import login_required, current_user
  24. from httpx import HTTPError
  25. from api.contants import NAME_LENGTH_LIMIT
  26. from api.db import FileType, ParserType, FileSource, TaskStatus
  27. from api.db import StatusEnum
  28. from api.db.db_models import File
  29. from api.db.services import duplicate_name
  30. from api.db.services.document_service import DocumentService
  31. from api.db.services.file2document_service import File2DocumentService
  32. from api.db.services.file_service import FileService
  33. from api.db.services.knowledgebase_service import KnowledgebaseService
  34. from api.db.services.user_service import TenantService
  35. from api.settings import RetCode
  36. from api.utils import get_uuid
  37. from api.utils.api_utils import construct_json_result, construct_error_response
  38. from api.utils.api_utils import construct_result, validate_request
  39. from api.utils.file_utils import filename_type, thumbnail
  40. from rag.app import book, laws, manual, naive, one, paper, presentation, qa, resume, table, picture, audio
  41. from rag.nlp import search
  42. from rag.utils.es_conn import ELASTICSEARCH
  43. from rag.utils.minio_conn import MINIO
  44. MAXIMUM_OF_UPLOADING_FILES = 256
  45. # ------------------------------ create a dataset ---------------------------------------
  46. @manager.route("/", methods=["POST"])
  47. @login_required # use login
  48. @validate_request("name") # check name key
  49. def create_dataset():
  50. # Check if Authorization header is present
  51. authorization_token = request.headers.get("Authorization")
  52. if not authorization_token:
  53. return construct_json_result(code=RetCode.AUTHENTICATION_ERROR, message="Authorization header is missing.")
  54. # TODO: Login or API key
  55. # objs = APIToken.query(token=authorization_token)
  56. #
  57. # # Authorization error
  58. # if not objs:
  59. # return construct_json_result(code=RetCode.AUTHENTICATION_ERROR, message="Token is invalid.")
  60. #
  61. # tenant_id = objs[0].tenant_id
  62. tenant_id = current_user.id
  63. request_body = request.json
  64. # In case that there's no name
  65. if "name" not in request_body:
  66. return construct_json_result(code=RetCode.DATA_ERROR, message="Expected 'name' field in request body")
  67. dataset_name = request_body["name"]
  68. # empty dataset_name
  69. if not dataset_name:
  70. return construct_json_result(code=RetCode.DATA_ERROR, message="Empty dataset name")
  71. # In case that there's space in the head or the tail
  72. dataset_name = dataset_name.strip()
  73. # In case that the length of the name exceeds the limit
  74. dataset_name_length = len(dataset_name)
  75. if dataset_name_length > NAME_LENGTH_LIMIT:
  76. return construct_json_result(
  77. code=RetCode.DATA_ERROR,
  78. message=f"Dataset name: {dataset_name} with length {dataset_name_length} exceeds {NAME_LENGTH_LIMIT}!")
  79. # In case that there are other fields in the data-binary
  80. if len(request_body.keys()) > 1:
  81. name_list = []
  82. for key_name in request_body.keys():
  83. if key_name != "name":
  84. name_list.append(key_name)
  85. return construct_json_result(code=RetCode.DATA_ERROR,
  86. message=f"fields: {name_list}, are not allowed in request body.")
  87. # If there is a duplicate name, it will modify it to make it unique
  88. request_body["name"] = duplicate_name(
  89. KnowledgebaseService.query,
  90. name=dataset_name,
  91. tenant_id=tenant_id,
  92. status=StatusEnum.VALID.value)
  93. try:
  94. request_body["id"] = get_uuid()
  95. request_body["tenant_id"] = tenant_id
  96. request_body["created_by"] = tenant_id
  97. exist, t = TenantService.get_by_id(tenant_id)
  98. if not exist:
  99. return construct_result(code=RetCode.AUTHENTICATION_ERROR, message="Tenant not found.")
  100. request_body["embd_id"] = t.embd_id
  101. if not KnowledgebaseService.save(**request_body):
  102. # failed to create new dataset
  103. return construct_result()
  104. return construct_json_result(code=RetCode.SUCCESS,
  105. data={"dataset_name": request_body["name"], "dataset_id": request_body["id"]})
  106. except Exception as e:
  107. return construct_error_response(e)
  108. # -----------------------------list datasets-------------------------------------------------------
  109. @manager.route("/", methods=["GET"])
  110. @login_required
  111. def list_datasets():
  112. offset = request.args.get("offset", 0)
  113. count = request.args.get("count", -1)
  114. orderby = request.args.get("orderby", "create_time")
  115. desc = request.args.get("desc", True)
  116. try:
  117. tenants = TenantService.get_joined_tenants_by_user_id(current_user.id)
  118. datasets = KnowledgebaseService.get_by_tenant_ids_by_offset(
  119. [m["tenant_id"] for m in tenants], current_user.id, int(offset), int(count), orderby, desc)
  120. return construct_json_result(data=datasets, code=RetCode.SUCCESS, message=f"List datasets successfully!")
  121. except Exception as e:
  122. return construct_error_response(e)
  123. except HTTPError as http_err:
  124. return construct_json_result(http_err)
  125. # ---------------------------------delete a dataset ----------------------------
  126. @manager.route("/<dataset_id>", methods=["DELETE"])
  127. @login_required
  128. def remove_dataset(dataset_id):
  129. try:
  130. datasets = KnowledgebaseService.query(created_by=current_user.id, id=dataset_id)
  131. # according to the id, searching for the dataset
  132. if not datasets:
  133. return construct_json_result(message=f"The dataset cannot be found for your current account.",
  134. code=RetCode.OPERATING_ERROR)
  135. # Iterating the documents inside the dataset
  136. for doc in DocumentService.query(kb_id=dataset_id):
  137. if not DocumentService.remove_document(doc, datasets[0].tenant_id):
  138. # the process of deleting failed
  139. return construct_json_result(code=RetCode.DATA_ERROR,
  140. message="There was an error during the document removal process. "
  141. "Please check the status of the RAGFlow server and try the removal again.")
  142. # delete the other files
  143. f2d = File2DocumentService.get_by_document_id(doc.id)
  144. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
  145. File2DocumentService.delete_by_document_id(doc.id)
  146. # delete the dataset
  147. if not KnowledgebaseService.delete_by_id(dataset_id):
  148. return construct_json_result(code=RetCode.DATA_ERROR,
  149. message="There was an error during the dataset removal process. "
  150. "Please check the status of the RAGFlow server and try the removal again.")
  151. # success
  152. return construct_json_result(code=RetCode.SUCCESS, message=f"Remove dataset: {dataset_id} successfully")
  153. except Exception as e:
  154. return construct_error_response(e)
  155. # ------------------------------ get details of a dataset ----------------------------------------
  156. @manager.route("/<dataset_id>", methods=["GET"])
  157. @login_required
  158. def get_dataset(dataset_id):
  159. try:
  160. dataset = KnowledgebaseService.get_detail(dataset_id)
  161. if not dataset:
  162. return construct_json_result(code=RetCode.DATA_ERROR, message="Can't find this dataset!")
  163. return construct_json_result(data=dataset, code=RetCode.SUCCESS)
  164. except Exception as e:
  165. return construct_json_result(e)
  166. # ------------------------------ update a dataset --------------------------------------------
  167. @manager.route("/<dataset_id>", methods=["PUT"])
  168. @login_required
  169. def update_dataset(dataset_id):
  170. req = request.json
  171. try:
  172. # the request cannot be empty
  173. if not req:
  174. return construct_json_result(code=RetCode.DATA_ERROR, message="Please input at least one parameter that "
  175. "you want to update!")
  176. # check whether the dataset can be found
  177. if not KnowledgebaseService.query(created_by=current_user.id, id=dataset_id):
  178. return construct_json_result(message=f"Only the owner of knowledgebase is authorized for this operation!",
  179. code=RetCode.OPERATING_ERROR)
  180. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  181. # check whether there is this dataset
  182. if not exist:
  183. return construct_json_result(code=RetCode.DATA_ERROR, message="This dataset cannot be found!")
  184. if "name" in req:
  185. name = req["name"].strip()
  186. # check whether there is duplicate name
  187. if name.lower() != dataset.name.lower() \
  188. and len(KnowledgebaseService.query(name=name, tenant_id=current_user.id,
  189. status=StatusEnum.VALID.value)) > 1:
  190. return construct_json_result(code=RetCode.DATA_ERROR,
  191. message=f"The name: {name.lower()} is already used by other "
  192. f"datasets. Please choose a different name.")
  193. dataset_updating_data = {}
  194. chunk_num = req.get("chunk_num")
  195. # modify the value of 11 parameters
  196. # 2 parameters: embedding id and chunk method
  197. # only if chunk_num is 0, the user can update the embedding id
  198. if req.get("embedding_model_id"):
  199. if chunk_num == 0:
  200. dataset_updating_data["embd_id"] = req["embedding_model_id"]
  201. else:
  202. return construct_json_result(code=RetCode.DATA_ERROR,
  203. message="You have already parsed the document in this "
  204. "dataset, so you cannot change the embedding "
  205. "model.")
  206. # only if chunk_num is 0, the user can update the chunk_method
  207. if "chunk_method" in req:
  208. type_value = req["chunk_method"]
  209. if is_illegal_value_for_enum(type_value, ParserType):
  210. return construct_json_result(message=f"Illegal value {type_value} for 'chunk_method' field.",
  211. code=RetCode.DATA_ERROR)
  212. if chunk_num != 0:
  213. construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document "
  214. "in this dataset, so you cannot "
  215. "change the chunk method.")
  216. dataset_updating_data["parser_id"] = req["template_type"]
  217. # convert the photo parameter to avatar
  218. if req.get("photo"):
  219. dataset_updating_data["avatar"] = req["photo"]
  220. # layout_recognize
  221. if "layout_recognize" in req:
  222. if "parser_config" not in dataset_updating_data:
  223. dataset_updating_data['parser_config'] = {}
  224. dataset_updating_data['parser_config']['layout_recognize'] = req['layout_recognize']
  225. # TODO: updating use_raptor needs to construct a class
  226. # 6 parameters
  227. for key in ["name", "language", "description", "permission", "id", "token_num"]:
  228. if key in req:
  229. dataset_updating_data[key] = req.get(key)
  230. # update
  231. if not KnowledgebaseService.update_by_id(dataset.id, dataset_updating_data):
  232. return construct_json_result(code=RetCode.OPERATING_ERROR, message="Failed to update! "
  233. "Please check the status of RAGFlow "
  234. "server and try again!")
  235. exist, dataset = KnowledgebaseService.get_by_id(dataset.id)
  236. if not exist:
  237. return construct_json_result(code=RetCode.DATA_ERROR, message="Failed to get the dataset "
  238. "using the dataset ID.")
  239. return construct_json_result(data=dataset.to_json(), code=RetCode.SUCCESS)
  240. except Exception as e:
  241. return construct_error_response(e)
  242. # --------------------------------content management ----------------------------------------------
  243. # ----------------------------upload files-----------------------------------------------------
  244. @manager.route("/<dataset_id>/documents/", methods=["POST"])
  245. @login_required
  246. def upload_documents(dataset_id):
  247. # no files
  248. if not request.files:
  249. return construct_json_result(
  250. message="There is no file!", code=RetCode.ARGUMENT_ERROR)
  251. # the number of uploading files exceeds the limit
  252. file_objs = request.files.getlist("file")
  253. num_file_objs = len(file_objs)
  254. if num_file_objs > MAXIMUM_OF_UPLOADING_FILES:
  255. return construct_json_result(code=RetCode.DATA_ERROR, message=f"You try to upload {num_file_objs} files, "
  256. f"which exceeds the maximum number of uploading files: {MAXIMUM_OF_UPLOADING_FILES}")
  257. # no dataset
  258. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  259. if not exist:
  260. return construct_json_result(message="Can't find this dataset", code=RetCode.DATA_ERROR)
  261. for file_obj in file_objs:
  262. file_name = file_obj.filename
  263. # no name
  264. if not file_name:
  265. return construct_json_result(
  266. message="There is a file without name!", code=RetCode.ARGUMENT_ERROR)
  267. # TODO: support the remote files
  268. if 'http' in file_name:
  269. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message="Remote files have not unsupported.")
  270. # get the root_folder
  271. root_folder = FileService.get_root_folder(current_user.id)
  272. # get the id of the root_folder
  273. parent_file_id = root_folder["id"] # document id
  274. # this is for the new user, create '.knowledgebase' file
  275. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  276. # go inside this folder, get the kb_root_folder
  277. kb_root_folder = FileService.get_kb_folder(current_user.id)
  278. # link the file management to the kb_folder
  279. kb_folder = FileService.new_a_file_from_kb(dataset.tenant_id, dataset.name, kb_root_folder["id"])
  280. # grab all the errs
  281. err = []
  282. MAX_FILE_NUM_PER_USER = int(os.environ.get("MAX_FILE_NUM_PER_USER", 0))
  283. uploaded_docs_json = []
  284. for file in file_objs:
  285. try:
  286. # TODO: get this value from the database as some tenants have this limit while others don't
  287. if MAX_FILE_NUM_PER_USER > 0 and DocumentService.get_doc_count(dataset.tenant_id) >= MAX_FILE_NUM_PER_USER:
  288. return construct_json_result(code=RetCode.DATA_ERROR,
  289. message="Exceed the maximum file number of a free user!")
  290. # deal with the duplicate name
  291. filename = duplicate_name(
  292. DocumentService.query,
  293. name=file.filename,
  294. kb_id=dataset.id)
  295. # deal with the unsupported type
  296. filetype = filename_type(filename)
  297. if filetype == FileType.OTHER.value:
  298. return construct_json_result(code=RetCode.DATA_ERROR,
  299. message="This type of file has not been supported yet!")
  300. # upload to the minio
  301. location = filename
  302. while MINIO.obj_exist(dataset_id, location):
  303. location += "_"
  304. blob = file.read()
  305. # the content is empty, raising a warning
  306. if blob == b'':
  307. warnings.warn(f"[WARNING]: The content of the file {filename} is empty.")
  308. MINIO.put(dataset_id, location, blob)
  309. doc = {
  310. "id": get_uuid(),
  311. "kb_id": dataset.id,
  312. "parser_id": dataset.parser_id,
  313. "parser_config": dataset.parser_config,
  314. "created_by": current_user.id,
  315. "type": filetype,
  316. "name": filename,
  317. "location": location,
  318. "size": len(blob),
  319. "thumbnail": thumbnail(filename, blob)
  320. }
  321. if doc["type"] == FileType.VISUAL:
  322. doc["parser_id"] = ParserType.PICTURE.value
  323. if doc["type"] == FileType.AURAL:
  324. doc["parser_id"] = ParserType.AUDIO.value
  325. if re.search(r"\.(ppt|pptx|pages)$", filename):
  326. doc["parser_id"] = ParserType.PRESENTATION.value
  327. DocumentService.insert(doc)
  328. FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
  329. uploaded_docs_json.append(doc)
  330. except Exception as e:
  331. err.append(file.filename + ": " + str(e))
  332. if err:
  333. # return all the errors
  334. return construct_json_result(message="\n".join(err), code=RetCode.SERVER_ERROR)
  335. # success
  336. return construct_json_result(data=uploaded_docs_json, code=RetCode.SUCCESS)
  337. # ----------------------------delete a file-----------------------------------------------------
  338. @manager.route("/<dataset_id>/documents/<document_id>", methods=["DELETE"])
  339. @login_required
  340. def delete_document(document_id, dataset_id): # string
  341. # get the root folder
  342. root_folder = FileService.get_root_folder(current_user.id)
  343. # parent file's id
  344. parent_file_id = root_folder["id"]
  345. # consider the new user
  346. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  347. # store all the errors that may have
  348. errors = ""
  349. try:
  350. # whether there is this document
  351. exist, doc = DocumentService.get_by_id(document_id)
  352. if not exist:
  353. return construct_json_result(message=f"Document {document_id} not found!", code=RetCode.DATA_ERROR)
  354. # whether this doc is authorized by this tenant
  355. tenant_id = DocumentService.get_tenant_id(document_id)
  356. if not tenant_id:
  357. return construct_json_result(
  358. message=f"You cannot delete this document {document_id} due to the authorization"
  359. f" reason!", code=RetCode.AUTHENTICATION_ERROR)
  360. # get the doc's id and location
  361. real_dataset_id, location = File2DocumentService.get_minio_address(doc_id=document_id)
  362. if real_dataset_id != dataset_id:
  363. return construct_json_result(message=f"The document {document_id} is not in the dataset: {dataset_id}, "
  364. f"but in the dataset: {real_dataset_id}.", code=RetCode.ARGUMENT_ERROR)
  365. # there is an issue when removing
  366. if not DocumentService.remove_document(doc, tenant_id):
  367. return construct_json_result(
  368. message="There was an error during the document removal process. Please check the status of the "
  369. "RAGFlow server and try the removal again.", code=RetCode.OPERATING_ERROR)
  370. # fetch the File2Document record associated with the provided document ID.
  371. file_to_doc = File2DocumentService.get_by_document_id(document_id)
  372. # delete the associated File record.
  373. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == file_to_doc[0].file_id])
  374. # delete the File2Document record itself using the document ID. This removes the
  375. # association between the document and the file after the File record has been deleted.
  376. File2DocumentService.delete_by_document_id(document_id)
  377. # delete it from minio
  378. MINIO.rm(dataset_id, location)
  379. except Exception as e:
  380. errors += str(e)
  381. if errors:
  382. return construct_json_result(data=False, message=errors, code=RetCode.SERVER_ERROR)
  383. return construct_json_result(data=True, code=RetCode.SUCCESS)
  384. # ----------------------------list files-----------------------------------------------------
  385. @manager.route('/<dataset_id>/documents/', methods=['GET'])
  386. @login_required
  387. def list_documents(dataset_id):
  388. if not dataset_id:
  389. return construct_json_result(
  390. data=False, message="Lack of 'dataset_id'", code=RetCode.ARGUMENT_ERROR)
  391. # searching keywords
  392. keywords = request.args.get("keywords", "")
  393. offset = request.args.get("offset", 0)
  394. count = request.args.get("count", -1)
  395. order_by = request.args.get("order_by", "create_time")
  396. descend = request.args.get("descend", True)
  397. try:
  398. docs, total = DocumentService.list_documents_in_dataset(dataset_id, int(offset), int(count), order_by,
  399. descend, keywords)
  400. return construct_json_result(data={"total": total, "docs": docs}, message=RetCode.SUCCESS)
  401. except Exception as e:
  402. return construct_error_response(e)
  403. # ----------------------------update: enable rename-----------------------------------------------------
  404. @manager.route("/<dataset_id>/documents/<document_id>", methods=["PUT"])
  405. @login_required
  406. def update_document(dataset_id, document_id):
  407. req = request.json
  408. try:
  409. legal_parameters = set()
  410. legal_parameters.add("name")
  411. legal_parameters.add("enable")
  412. legal_parameters.add("template_type")
  413. for key in req.keys():
  414. if key not in legal_parameters:
  415. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message=f"{key} is an illegal parameter.")
  416. # The request body cannot be empty
  417. if not req:
  418. return construct_json_result(
  419. code=RetCode.DATA_ERROR,
  420. message="Please input at least one parameter that you want to update!")
  421. # Check whether there is this dataset
  422. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  423. if not exist:
  424. return construct_json_result(code=RetCode.DATA_ERROR, message=f"This dataset {dataset_id} cannot be found!")
  425. # The document does not exist
  426. exist, document = DocumentService.get_by_id(document_id)
  427. if not exist:
  428. return construct_json_result(message=f"This document {document_id} cannot be found!",
  429. code=RetCode.ARGUMENT_ERROR)
  430. # Deal with the different keys
  431. updating_data = {}
  432. if "name" in req:
  433. new_name = req["name"]
  434. updating_data["name"] = new_name
  435. # Check whether the new_name is suitable
  436. # 1. no name value
  437. if not new_name:
  438. return construct_json_result(code=RetCode.DATA_ERROR, message="There is no new name.")
  439. # 2. In case that there's space in the head or the tail
  440. new_name = new_name.strip()
  441. # 3. Check whether the new_name has the same extension of file as before
  442. if pathlib.Path(new_name.lower()).suffix != pathlib.Path(
  443. document.name.lower()).suffix:
  444. return construct_json_result(
  445. data=False,
  446. message="The extension of file cannot be changed",
  447. code=RetCode.ARGUMENT_ERROR)
  448. # 4. Check whether the new name has already been occupied by other file
  449. for d in DocumentService.query(name=new_name, kb_id=document.kb_id):
  450. if d.name == new_name:
  451. return construct_json_result(
  452. message="Duplicated document name in the same dataset.",
  453. code=RetCode.ARGUMENT_ERROR)
  454. if "enable" in req:
  455. enable_value = req["enable"]
  456. if is_illegal_value_for_enum(enable_value, StatusEnum):
  457. return construct_json_result(message=f"Illegal value {enable_value} for 'enable' field.",
  458. code=RetCode.DATA_ERROR)
  459. updating_data["status"] = enable_value
  460. # TODO: Chunk-method - update parameters inside the json object parser_config
  461. if "template_type" in req:
  462. type_value = req["template_type"]
  463. if is_illegal_value_for_enum(type_value, ParserType):
  464. return construct_json_result(message=f"Illegal value {type_value} for 'template_type' field.",
  465. code=RetCode.DATA_ERROR)
  466. updating_data["parser_id"] = req["template_type"]
  467. # The process of updating
  468. if not DocumentService.update_by_id(document_id, updating_data):
  469. return construct_json_result(
  470. code=RetCode.OPERATING_ERROR,
  471. message="Failed to update document in the database! "
  472. "Please check the status of RAGFlow server and try again!")
  473. # name part: file service
  474. if "name" in req:
  475. # Get file by document id
  476. file_information = File2DocumentService.get_by_document_id(document_id)
  477. if file_information:
  478. exist, file = FileService.get_by_id(file_information[0].file_id)
  479. FileService.update_by_id(file.id, {"name": req["name"]})
  480. exist, document = DocumentService.get_by_id(document_id)
  481. # Success
  482. return construct_json_result(data=document.to_json(), message="Success", code=RetCode.SUCCESS)
  483. except Exception as e:
  484. return construct_error_response(e)
  485. # Helper method to judge whether it's an illegal value
  486. def is_illegal_value_for_enum(value, enum_class):
  487. return value not in enum_class.__members__.values()
  488. # ----------------------------download a file-----------------------------------------------------
  489. @manager.route("/<dataset_id>/documents/<document_id>", methods=["GET"])
  490. @login_required
  491. def download_document(dataset_id, document_id):
  492. try:
  493. # Check whether there is this dataset
  494. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  495. if not exist:
  496. return construct_json_result(code=RetCode.DATA_ERROR,
  497. message=f"This dataset '{dataset_id}' cannot be found!")
  498. # Check whether there is this document
  499. exist, document = DocumentService.get_by_id(document_id)
  500. if not exist:
  501. return construct_json_result(message=f"This document '{document_id}' cannot be found!",
  502. code=RetCode.ARGUMENT_ERROR)
  503. # The process of downloading
  504. doc_id, doc_location = File2DocumentService.get_minio_address(doc_id=document_id) # minio address
  505. file_stream = MINIO.get(doc_id, doc_location)
  506. if not file_stream:
  507. return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
  508. file = BytesIO(file_stream)
  509. # Use send_file with a proper filename and MIME type
  510. return send_file(
  511. file,
  512. as_attachment=True,
  513. download_name=document.name,
  514. mimetype='application/octet-stream' # Set a default MIME type
  515. )
  516. # Error
  517. except Exception as e:
  518. return construct_error_response(e)
  519. # ----------------------------start parsing a document-----------------------------------------------------
  520. # helper method for parsing
  521. # callback method
  522. def doc_parse_callback(doc_id, prog=None, msg=""):
  523. cancel = DocumentService.do_cancel(doc_id)
  524. if cancel:
  525. raise Exception("The parsing process has been cancelled!")
  526. """
  527. def doc_parse(binary, doc_name, parser_name, tenant_id, doc_id):
  528. match parser_name:
  529. case "book":
  530. book.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  531. case "laws":
  532. laws.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  533. case "manual":
  534. manual.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  535. case "naive":
  536. # It's the mode by default, which is general in the front-end
  537. naive.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  538. case "one":
  539. one.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  540. case "paper":
  541. paper.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  542. case "picture":
  543. picture.chunk(doc_name, binary=binary, tenant_id=tenant_id, lang="Chinese",
  544. callback=partial(doc_parse_callback, doc_id))
  545. case "presentation":
  546. presentation.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  547. case "qa":
  548. qa.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  549. case "resume":
  550. resume.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  551. case "table":
  552. table.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  553. case "audio":
  554. audio.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  555. case _:
  556. return False
  557. return True
  558. """
  559. @manager.route("/<dataset_id>/documents/<document_id>/status", methods=["POST"])
  560. @login_required
  561. def parse_document(dataset_id, document_id):
  562. try:
  563. # valid dataset
  564. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  565. if not exist:
  566. return construct_json_result(code=RetCode.DATA_ERROR,
  567. message=f"This dataset '{dataset_id}' cannot be found!")
  568. return parsing_document_internal(document_id)
  569. except Exception as e:
  570. return construct_error_response(e)
  571. # ----------------------------start parsing documents-----------------------------------------------------
  572. @manager.route("/<dataset_id>/documents/status", methods=["POST"])
  573. @login_required
  574. def parse_documents(dataset_id):
  575. doc_ids = request.json["doc_ids"]
  576. try:
  577. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  578. if not exist:
  579. return construct_json_result(code=RetCode.DATA_ERROR,
  580. message=f"This dataset '{dataset_id}' cannot be found!")
  581. # two conditions
  582. if not doc_ids:
  583. # documents inside the dataset
  584. docs, total = DocumentService.list_documents_in_dataset(dataset_id, 0, -1, "create_time",
  585. True, "")
  586. doc_ids = [doc["id"] for doc in docs]
  587. message = ""
  588. # for loop
  589. for id in doc_ids:
  590. res = parsing_document_internal(id)
  591. res_body = res.json
  592. if res_body["code"] == RetCode.SUCCESS:
  593. message += res_body["message"]
  594. else:
  595. return res
  596. return construct_json_result(data=True, code=RetCode.SUCCESS, message=message)
  597. except Exception as e:
  598. return construct_error_response(e)
  599. # helper method for parsing the document
  600. def parsing_document_internal(id):
  601. message = ""
  602. try:
  603. # Check whether there is this document
  604. exist, document = DocumentService.get_by_id(id)
  605. if not exist:
  606. return construct_json_result(message=f"This document '{id}' cannot be found!",
  607. code=RetCode.ARGUMENT_ERROR)
  608. tenant_id = DocumentService.get_tenant_id(id)
  609. if not tenant_id:
  610. return construct_json_result(message="Tenant not found!", code=RetCode.AUTHENTICATION_ERROR)
  611. info = {"run": "1", "progress": 0}
  612. info["progress_msg"] = ""
  613. info["chunk_num"] = 0
  614. info["token_num"] = 0
  615. DocumentService.update_by_id(id, info)
  616. ELASTICSEARCH.deleteByQuery(Q("match", doc_id=id), idxnm=search.index_name(tenant_id))
  617. _, doc_attributes = DocumentService.get_by_id(id)
  618. doc_attributes = doc_attributes.to_dict()
  619. doc_id = doc_attributes["id"]
  620. bucket, doc_name = File2DocumentService.get_minio_address(doc_id=doc_id)
  621. binary = MINIO.get(bucket, doc_name)
  622. parser_name = doc_attributes["parser_id"]
  623. if binary:
  624. res = doc_parse(binary, doc_name, parser_name, tenant_id, doc_id)
  625. if res is False:
  626. message += f"The parser id: {parser_name} of the document {doc_id} is not supported; "
  627. else:
  628. message += f"Empty data in the document: {doc_name}; "
  629. # failed in parsing
  630. if doc_attributes["status"] == TaskStatus.FAIL.value:
  631. message += f"Failed in parsing the document: {doc_id}; "
  632. return construct_json_result(code=RetCode.SUCCESS, message=message)
  633. except Exception as e:
  634. return construct_error_response(e)
  635. # ----------------------------stop parsing a doc-----------------------------------------------------
  636. @manager.route("<dataset_id>/documents/<document_id>/status", methods=["DELETE"])
  637. @login_required
  638. def stop_parsing_document(dataset_id, document_id):
  639. try:
  640. # valid dataset
  641. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  642. if not exist:
  643. return construct_json_result(code=RetCode.DATA_ERROR,
  644. message=f"This dataset '{dataset_id}' cannot be found!")
  645. return stop_parsing_document_internal(document_id)
  646. except Exception as e:
  647. return construct_error_response(e)
  648. # ----------------------------stop parsing docs-----------------------------------------------------
  649. @manager.route("<dataset_id>/documents/status", methods=["DELETE"])
  650. @login_required
  651. def stop_parsing_documents(dataset_id):
  652. doc_ids = request.json["doc_ids"]
  653. try:
  654. # valid dataset?
  655. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  656. if not exist:
  657. return construct_json_result(code=RetCode.DATA_ERROR,
  658. message=f"This dataset '{dataset_id}' cannot be found!")
  659. if not doc_ids:
  660. # documents inside the dataset
  661. docs, total = DocumentService.list_documents_in_dataset(dataset_id, 0, -1, "create_time",
  662. True, "")
  663. doc_ids = [doc["id"] for doc in docs]
  664. message = ""
  665. # for loop
  666. for id in doc_ids:
  667. res = stop_parsing_document_internal(id)
  668. res_body = res.json
  669. if res_body["code"] == RetCode.SUCCESS:
  670. message += res_body["message"]
  671. else:
  672. return res
  673. return construct_json_result(data=True, code=RetCode.SUCCESS, message=message)
  674. except Exception as e:
  675. return construct_error_response(e)
  676. # Helper method
  677. def stop_parsing_document_internal(document_id):
  678. try:
  679. # valid doc?
  680. exist, doc = DocumentService.get_by_id(document_id)
  681. if not exist:
  682. return construct_json_result(message=f"This document '{document_id}' cannot be found!",
  683. code=RetCode.ARGUMENT_ERROR)
  684. doc_attributes = doc.to_dict()
  685. # only when the status is parsing, we need to stop it
  686. if doc_attributes["status"] == TaskStatus.RUNNING.value:
  687. tenant_id = DocumentService.get_tenant_id(document_id)
  688. if not tenant_id:
  689. return construct_json_result(message="Tenant not found!", code=RetCode.AUTHENTICATION_ERROR)
  690. # update successfully?
  691. if not DocumentService.update_by_id(document_id, {"status": "2"}): # cancel
  692. return construct_json_result(
  693. code=RetCode.OPERATING_ERROR,
  694. message="There was an error during the stopping parsing the document process. "
  695. "Please check the status of the RAGFlow server and try the update again."
  696. )
  697. _, doc_attributes = DocumentService.get_by_id(document_id)
  698. doc_attributes = doc_attributes.to_dict()
  699. # failed in stop parsing
  700. if doc_attributes["status"] == TaskStatus.RUNNING.value:
  701. return construct_json_result(message=f"Failed in parsing the document: {document_id}; ", code=RetCode.SUCCESS)
  702. return construct_json_result(code=RetCode.SUCCESS, message="")
  703. except Exception as e:
  704. return construct_error_response(e)
  705. # ----------------------------show the status of the file-----------------------------------------------------
  706. @manager.route("/<dataset_id>/documents/<document_id>/status", methods=["GET"])
  707. @login_required
  708. def show_parsing_status(dataset_id, document_id):
  709. try:
  710. # valid dataset
  711. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  712. if not exist:
  713. return construct_json_result(code=RetCode.DATA_ERROR,
  714. message=f"This dataset: '{dataset_id}' cannot be found!")
  715. # valid document
  716. exist, _ = DocumentService.get_by_id(document_id)
  717. if not exist:
  718. return construct_json_result(code=RetCode.DATA_ERROR,
  719. message=f"This document: '{document_id}' is not a valid document.")
  720. _, doc = DocumentService.get_by_id(document_id) # get doc object
  721. doc_attributes = doc.to_dict()
  722. return construct_json_result(
  723. data={"progress": doc_attributes["progress"], "status": TaskStatus(doc_attributes["status"]).name},
  724. code=RetCode.SUCCESS
  725. )
  726. except Exception as e:
  727. return construct_error_response(e)
  728. # ----------------------------list the chunks of the file-----------------------------------------------------
  729. # -- --------------------------delete the chunk-----------------------------------------------------
  730. # ----------------------------edit the status of the chunk-----------------------------------------------------
  731. # ----------------------------insert a new chunk-----------------------------------------------------
  732. # ----------------------------upload a file-----------------------------------------------------
  733. # ----------------------------get a specific chunk-----------------------------------------------------
  734. # ----------------------------retrieval test-----------------------------------------------------