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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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, email
  41. from rag.nlp import search
  42. from rag.utils.es_conn import ELASTICSEARCH
  43. from rag.utils.storage_factory import STORAGE_IMPL
  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 STORAGE_IMPL.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. STORAGE_IMPL.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. if re.search(r"\.(eml)$", filename):
  328. doc["parser_id"] = ParserType.EMAIL.value
  329. DocumentService.insert(doc)
  330. FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
  331. uploaded_docs_json.append(doc)
  332. except Exception as e:
  333. err.append(file.filename + ": " + str(e))
  334. if err:
  335. # return all the errors
  336. return construct_json_result(message="\n".join(err), code=RetCode.SERVER_ERROR)
  337. # success
  338. return construct_json_result(data=uploaded_docs_json, code=RetCode.SUCCESS)
  339. # ----------------------------delete a file-----------------------------------------------------
  340. @manager.route("/<dataset_id>/documents/<document_id>", methods=["DELETE"])
  341. @login_required
  342. def delete_document(document_id, dataset_id): # string
  343. # get the root folder
  344. root_folder = FileService.get_root_folder(current_user.id)
  345. # parent file's id
  346. parent_file_id = root_folder["id"]
  347. # consider the new user
  348. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  349. # store all the errors that may have
  350. errors = ""
  351. try:
  352. # whether there is this document
  353. exist, doc = DocumentService.get_by_id(document_id)
  354. if not exist:
  355. return construct_json_result(message=f"Document {document_id} not found!", code=RetCode.DATA_ERROR)
  356. # whether this doc is authorized by this tenant
  357. tenant_id = DocumentService.get_tenant_id(document_id)
  358. if not tenant_id:
  359. return construct_json_result(
  360. message=f"You cannot delete this document {document_id} due to the authorization"
  361. f" reason!", code=RetCode.AUTHENTICATION_ERROR)
  362. # get the doc's id and location
  363. real_dataset_id, location = File2DocumentService.get_storage_address(doc_id=document_id)
  364. if real_dataset_id != dataset_id:
  365. return construct_json_result(message=f"The document {document_id} is not in the dataset: {dataset_id}, "
  366. f"but in the dataset: {real_dataset_id}.", code=RetCode.ARGUMENT_ERROR)
  367. # there is an issue when removing
  368. if not DocumentService.remove_document(doc, tenant_id):
  369. return construct_json_result(
  370. message="There was an error during the document removal process. Please check the status of the "
  371. "RAGFlow server and try the removal again.", code=RetCode.OPERATING_ERROR)
  372. # fetch the File2Document record associated with the provided document ID.
  373. file_to_doc = File2DocumentService.get_by_document_id(document_id)
  374. # delete the associated File record.
  375. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == file_to_doc[0].file_id])
  376. # delete the File2Document record itself using the document ID. This removes the
  377. # association between the document and the file after the File record has been deleted.
  378. File2DocumentService.delete_by_document_id(document_id)
  379. # delete it from minio
  380. STORAGE_IMPL.rm(dataset_id, location)
  381. except Exception as e:
  382. errors += str(e)
  383. if errors:
  384. return construct_json_result(data=False, message=errors, code=RetCode.SERVER_ERROR)
  385. return construct_json_result(data=True, code=RetCode.SUCCESS)
  386. # ----------------------------list files-----------------------------------------------------
  387. @manager.route('/<dataset_id>/documents/', methods=['GET'])
  388. @login_required
  389. def list_documents(dataset_id):
  390. if not dataset_id:
  391. return construct_json_result(
  392. data=False, message="Lack of 'dataset_id'", code=RetCode.ARGUMENT_ERROR)
  393. # searching keywords
  394. keywords = request.args.get("keywords", "")
  395. offset = request.args.get("offset", 0)
  396. count = request.args.get("count", -1)
  397. order_by = request.args.get("order_by", "create_time")
  398. descend = request.args.get("descend", True)
  399. try:
  400. docs, total = DocumentService.list_documents_in_dataset(dataset_id, int(offset), int(count), order_by,
  401. descend, keywords)
  402. return construct_json_result(data={"total": total, "docs": docs}, message=RetCode.SUCCESS)
  403. except Exception as e:
  404. return construct_error_response(e)
  405. # ----------------------------update: enable rename-----------------------------------------------------
  406. @manager.route("/<dataset_id>/documents/<document_id>", methods=["PUT"])
  407. @login_required
  408. def update_document(dataset_id, document_id):
  409. req = request.json
  410. try:
  411. legal_parameters = set()
  412. legal_parameters.add("name")
  413. legal_parameters.add("enable")
  414. legal_parameters.add("template_type")
  415. for key in req.keys():
  416. if key not in legal_parameters:
  417. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message=f"{key} is an illegal parameter.")
  418. # The request body cannot be empty
  419. if not req:
  420. return construct_json_result(
  421. code=RetCode.DATA_ERROR,
  422. message="Please input at least one parameter that you want to update!")
  423. # Check whether there is this dataset
  424. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  425. if not exist:
  426. return construct_json_result(code=RetCode.DATA_ERROR, message=f"This dataset {dataset_id} cannot be found!")
  427. # The document does not exist
  428. exist, document = DocumentService.get_by_id(document_id)
  429. if not exist:
  430. return construct_json_result(message=f"This document {document_id} cannot be found!",
  431. code=RetCode.ARGUMENT_ERROR)
  432. # Deal with the different keys
  433. updating_data = {}
  434. if "name" in req:
  435. new_name = req["name"]
  436. updating_data["name"] = new_name
  437. # Check whether the new_name is suitable
  438. # 1. no name value
  439. if not new_name:
  440. return construct_json_result(code=RetCode.DATA_ERROR, message="There is no new name.")
  441. # 2. In case that there's space in the head or the tail
  442. new_name = new_name.strip()
  443. # 3. Check whether the new_name has the same extension of file as before
  444. if pathlib.Path(new_name.lower()).suffix != pathlib.Path(
  445. document.name.lower()).suffix:
  446. return construct_json_result(
  447. data=False,
  448. message="The extension of file cannot be changed",
  449. code=RetCode.ARGUMENT_ERROR)
  450. # 4. Check whether the new name has already been occupied by other file
  451. for d in DocumentService.query(name=new_name, kb_id=document.kb_id):
  452. if d.name == new_name:
  453. return construct_json_result(
  454. message="Duplicated document name in the same dataset.",
  455. code=RetCode.ARGUMENT_ERROR)
  456. if "enable" in req:
  457. enable_value = req["enable"]
  458. if is_illegal_value_for_enum(enable_value, StatusEnum):
  459. return construct_json_result(message=f"Illegal value {enable_value} for 'enable' field.",
  460. code=RetCode.DATA_ERROR)
  461. updating_data["status"] = enable_value
  462. # TODO: Chunk-method - update parameters inside the json object parser_config
  463. if "template_type" in req:
  464. type_value = req["template_type"]
  465. if is_illegal_value_for_enum(type_value, ParserType):
  466. return construct_json_result(message=f"Illegal value {type_value} for 'template_type' field.",
  467. code=RetCode.DATA_ERROR)
  468. updating_data["parser_id"] = req["template_type"]
  469. # The process of updating
  470. if not DocumentService.update_by_id(document_id, updating_data):
  471. return construct_json_result(
  472. code=RetCode.OPERATING_ERROR,
  473. message="Failed to update document in the database! "
  474. "Please check the status of RAGFlow server and try again!")
  475. # name part: file service
  476. if "name" in req:
  477. # Get file by document id
  478. file_information = File2DocumentService.get_by_document_id(document_id)
  479. if file_information:
  480. exist, file = FileService.get_by_id(file_information[0].file_id)
  481. FileService.update_by_id(file.id, {"name": req["name"]})
  482. exist, document = DocumentService.get_by_id(document_id)
  483. # Success
  484. return construct_json_result(data=document.to_json(), message="Success", code=RetCode.SUCCESS)
  485. except Exception as e:
  486. return construct_error_response(e)
  487. # Helper method to judge whether it's an illegal value
  488. def is_illegal_value_for_enum(value, enum_class):
  489. return value not in enum_class.__members__.values()
  490. # ----------------------------download a file-----------------------------------------------------
  491. @manager.route("/<dataset_id>/documents/<document_id>", methods=["GET"])
  492. @login_required
  493. def download_document(dataset_id, document_id):
  494. try:
  495. # Check whether there is this dataset
  496. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  497. if not exist:
  498. return construct_json_result(code=RetCode.DATA_ERROR,
  499. message=f"This dataset '{dataset_id}' cannot be found!")
  500. # Check whether there is this document
  501. exist, document = DocumentService.get_by_id(document_id)
  502. if not exist:
  503. return construct_json_result(message=f"This document '{document_id}' cannot be found!",
  504. code=RetCode.ARGUMENT_ERROR)
  505. # The process of downloading
  506. doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
  507. file_stream = STORAGE_IMPL.get(doc_id, doc_location)
  508. if not file_stream:
  509. return construct_json_result(message="This file is empty.", code=RetCode.DATA_ERROR)
  510. file = BytesIO(file_stream)
  511. # Use send_file with a proper filename and MIME type
  512. return send_file(
  513. file,
  514. as_attachment=True,
  515. download_name=document.name,
  516. mimetype='application/octet-stream' # Set a default MIME type
  517. )
  518. # Error
  519. except Exception as e:
  520. return construct_error_response(e)
  521. # ----------------------------start parsing a document-----------------------------------------------------
  522. # helper method for parsing
  523. # callback method
  524. def doc_parse_callback(doc_id, prog=None, msg=""):
  525. cancel = DocumentService.do_cancel(doc_id)
  526. if cancel:
  527. raise Exception("The parsing process has been cancelled!")
  528. """
  529. def doc_parse(binary, doc_name, parser_name, tenant_id, doc_id):
  530. match parser_name:
  531. case "book":
  532. book.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  533. case "laws":
  534. laws.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  535. case "manual":
  536. manual.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  537. case "naive":
  538. # It's the mode by default, which is general in the front-end
  539. naive.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  540. case "one":
  541. one.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  542. case "paper":
  543. paper.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  544. case "picture":
  545. picture.chunk(doc_name, binary=binary, tenant_id=tenant_id, lang="Chinese",
  546. callback=partial(doc_parse_callback, doc_id))
  547. case "presentation":
  548. presentation.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  549. case "qa":
  550. qa.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  551. case "resume":
  552. resume.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  553. case "table":
  554. table.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  555. case "audio":
  556. audio.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  557. case "email":
  558. email.chunk(doc_name, binary=binary, callback=partial(doc_parse_callback, doc_id))
  559. case _:
  560. return False
  561. return True
  562. """
  563. @manager.route("/<dataset_id>/documents/<document_id>/status", methods=["POST"])
  564. @login_required
  565. def parse_document(dataset_id, document_id):
  566. try:
  567. # valid dataset
  568. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  569. if not exist:
  570. return construct_json_result(code=RetCode.DATA_ERROR,
  571. message=f"This dataset '{dataset_id}' cannot be found!")
  572. return parsing_document_internal(document_id)
  573. except Exception as e:
  574. return construct_error_response(e)
  575. # ----------------------------start parsing documents-----------------------------------------------------
  576. @manager.route("/<dataset_id>/documents/status", methods=["POST"])
  577. @login_required
  578. def parse_documents(dataset_id):
  579. doc_ids = request.json["doc_ids"]
  580. try:
  581. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  582. if not exist:
  583. return construct_json_result(code=RetCode.DATA_ERROR,
  584. message=f"This dataset '{dataset_id}' cannot be found!")
  585. # two conditions
  586. if not doc_ids:
  587. # documents inside the dataset
  588. docs, total = DocumentService.list_documents_in_dataset(dataset_id, 0, -1, "create_time",
  589. True, "")
  590. doc_ids = [doc["id"] for doc in docs]
  591. message = ""
  592. # for loop
  593. for id in doc_ids:
  594. res = parsing_document_internal(id)
  595. res_body = res.json
  596. if res_body["code"] == RetCode.SUCCESS:
  597. message += res_body["message"]
  598. else:
  599. return res
  600. return construct_json_result(data=True, code=RetCode.SUCCESS, message=message)
  601. except Exception as e:
  602. return construct_error_response(e)
  603. # helper method for parsing the document
  604. def parsing_document_internal(id):
  605. message = ""
  606. try:
  607. # Check whether there is this document
  608. exist, document = DocumentService.get_by_id(id)
  609. if not exist:
  610. return construct_json_result(message=f"This document '{id}' cannot be found!",
  611. code=RetCode.ARGUMENT_ERROR)
  612. tenant_id = DocumentService.get_tenant_id(id)
  613. if not tenant_id:
  614. return construct_json_result(message="Tenant not found!", code=RetCode.AUTHENTICATION_ERROR)
  615. info = {"run": "1", "progress": 0}
  616. info["progress_msg"] = ""
  617. info["chunk_num"] = 0
  618. info["token_num"] = 0
  619. DocumentService.update_by_id(id, info)
  620. ELASTICSEARCH.deleteByQuery(Q("match", doc_id=id), idxnm=search.index_name(tenant_id))
  621. _, doc_attributes = DocumentService.get_by_id(id)
  622. doc_attributes = doc_attributes.to_dict()
  623. doc_id = doc_attributes["id"]
  624. bucket, doc_name = File2DocumentService.get_storage_address(doc_id=doc_id)
  625. binary = STORAGE_IMPL.get(bucket, doc_name)
  626. parser_name = doc_attributes["parser_id"]
  627. if binary:
  628. res = doc_parse(binary, doc_name, parser_name, tenant_id, doc_id)
  629. if res is False:
  630. message += f"The parser id: {parser_name} of the document {doc_id} is not supported; "
  631. else:
  632. message += f"Empty data in the document: {doc_name}; "
  633. # failed in parsing
  634. if doc_attributes["status"] == TaskStatus.FAIL.value:
  635. message += f"Failed in parsing the document: {doc_id}; "
  636. return construct_json_result(code=RetCode.SUCCESS, message=message)
  637. except Exception as e:
  638. return construct_error_response(e)
  639. # ----------------------------stop parsing a doc-----------------------------------------------------
  640. @manager.route("<dataset_id>/documents/<document_id>/status", methods=["DELETE"])
  641. @login_required
  642. def stop_parsing_document(dataset_id, document_id):
  643. try:
  644. # valid dataset
  645. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  646. if not exist:
  647. return construct_json_result(code=RetCode.DATA_ERROR,
  648. message=f"This dataset '{dataset_id}' cannot be found!")
  649. return stop_parsing_document_internal(document_id)
  650. except Exception as e:
  651. return construct_error_response(e)
  652. # ----------------------------stop parsing docs-----------------------------------------------------
  653. @manager.route("<dataset_id>/documents/status", methods=["DELETE"])
  654. @login_required
  655. def stop_parsing_documents(dataset_id):
  656. doc_ids = request.json["doc_ids"]
  657. try:
  658. # valid dataset?
  659. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  660. if not exist:
  661. return construct_json_result(code=RetCode.DATA_ERROR,
  662. message=f"This dataset '{dataset_id}' cannot be found!")
  663. if not doc_ids:
  664. # documents inside the dataset
  665. docs, total = DocumentService.list_documents_in_dataset(dataset_id, 0, -1, "create_time",
  666. True, "")
  667. doc_ids = [doc["id"] for doc in docs]
  668. message = ""
  669. # for loop
  670. for id in doc_ids:
  671. res = stop_parsing_document_internal(id)
  672. res_body = res.json
  673. if res_body["code"] == RetCode.SUCCESS:
  674. message += res_body["message"]
  675. else:
  676. return res
  677. return construct_json_result(data=True, code=RetCode.SUCCESS, message=message)
  678. except Exception as e:
  679. return construct_error_response(e)
  680. # Helper method
  681. def stop_parsing_document_internal(document_id):
  682. try:
  683. # valid doc?
  684. exist, doc = DocumentService.get_by_id(document_id)
  685. if not exist:
  686. return construct_json_result(message=f"This document '{document_id}' cannot be found!",
  687. code=RetCode.ARGUMENT_ERROR)
  688. doc_attributes = doc.to_dict()
  689. # only when the status is parsing, we need to stop it
  690. if doc_attributes["status"] == TaskStatus.RUNNING.value:
  691. tenant_id = DocumentService.get_tenant_id(document_id)
  692. if not tenant_id:
  693. return construct_json_result(message="Tenant not found!", code=RetCode.AUTHENTICATION_ERROR)
  694. # update successfully?
  695. if not DocumentService.update_by_id(document_id, {"status": "2"}): # cancel
  696. return construct_json_result(
  697. code=RetCode.OPERATING_ERROR,
  698. message="There was an error during the stopping parsing the document process. "
  699. "Please check the status of the RAGFlow server and try the update again."
  700. )
  701. _, doc_attributes = DocumentService.get_by_id(document_id)
  702. doc_attributes = doc_attributes.to_dict()
  703. # failed in stop parsing
  704. if doc_attributes["status"] == TaskStatus.RUNNING.value:
  705. return construct_json_result(message=f"Failed in parsing the document: {document_id}; ", code=RetCode.SUCCESS)
  706. return construct_json_result(code=RetCode.SUCCESS, message="")
  707. except Exception as e:
  708. return construct_error_response(e)
  709. # ----------------------------show the status of the file-----------------------------------------------------
  710. @manager.route("/<dataset_id>/documents/<document_id>/status", methods=["GET"])
  711. @login_required
  712. def show_parsing_status(dataset_id, document_id):
  713. try:
  714. # valid dataset
  715. exist, _ = KnowledgebaseService.get_by_id(dataset_id)
  716. if not exist:
  717. return construct_json_result(code=RetCode.DATA_ERROR,
  718. message=f"This dataset: '{dataset_id}' cannot be found!")
  719. # valid document
  720. exist, _ = DocumentService.get_by_id(document_id)
  721. if not exist:
  722. return construct_json_result(code=RetCode.DATA_ERROR,
  723. message=f"This document: '{document_id}' is not a valid document.")
  724. _, doc = DocumentService.get_by_id(document_id) # get doc object
  725. doc_attributes = doc.to_dict()
  726. return construct_json_result(
  727. data={"progress": doc_attributes["progress"], "status": TaskStatus(doc_attributes["status"]).name},
  728. code=RetCode.SUCCESS
  729. )
  730. except Exception as e:
  731. return construct_error_response(e)
  732. # ----------------------------list the chunks of the file-----------------------------------------------------
  733. # -- --------------------------delete the chunk-----------------------------------------------------
  734. # ----------------------------edit the status of the chunk-----------------------------------------------------
  735. # ----------------------------insert a new chunk-----------------------------------------------------
  736. # ----------------------------upload a file-----------------------------------------------------
  737. # ----------------------------get a specific chunk-----------------------------------------------------
  738. # ----------------------------retrieval test-----------------------------------------------------