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

documents_api.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License
  15. #
  16. import os
  17. import re
  18. import warnings
  19. from flask import request
  20. from flask_login import login_required, current_user
  21. from api.db import FileType, ParserType
  22. from api.db.services import duplicate_name
  23. from api.db.services.document_service import DocumentService
  24. from api.db.services.file2document_service import File2DocumentService
  25. from api.db.services.file_service import FileService
  26. from api.db.services.knowledgebase_service import KnowledgebaseService
  27. from api.settings import RetCode
  28. from api.utils import get_uuid
  29. from api.utils.api_utils import construct_json_result
  30. from api.utils.file_utils import filename_type, thumbnail
  31. from rag.utils.minio_conn import MINIO
  32. from api.db.db_models import Task, File
  33. from api.db import FileType, TaskStatus, ParserType, FileSource
  34. MAXIMUM_OF_UPLOADING_FILES = 256
  35. # ----------------------------upload local files-----------------------------------------------------
  36. @manager.route('/<dataset_id>', methods=['POST'])
  37. @login_required
  38. def upload(dataset_id):
  39. # no files
  40. if not request.files:
  41. return construct_json_result(
  42. message='There is no file!', code=RetCode.ARGUMENT_ERROR)
  43. # the number of uploading files exceeds the limit
  44. file_objs = request.files.getlist('file')
  45. num_file_objs = len(file_objs)
  46. if num_file_objs > MAXIMUM_OF_UPLOADING_FILES:
  47. return construct_json_result(code=RetCode.DATA_ERROR, message=f"You try to upload {num_file_objs} files, "
  48. f"which exceeds the maximum number of uploading files: {MAXIMUM_OF_UPLOADING_FILES}")
  49. for file_obj in file_objs:
  50. # the content of the file
  51. file_content = file_obj.read()
  52. file_name = file_obj.filename
  53. # no name
  54. if not file_name:
  55. return construct_json_result(
  56. message='There is a file without name!', code=RetCode.ARGUMENT_ERROR)
  57. # TODO: support the remote files
  58. if 'http' in file_name:
  59. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message="Remote files have not unsupported.")
  60. # the content is empty, raising a warning
  61. if file_content == b'':
  62. warnings.warn(f"[WARNING]: The file {file_name} is empty.")
  63. # no dataset
  64. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  65. if not exist:
  66. return construct_json_result(message="Can't find this dataset", code=RetCode.DATA_ERROR)
  67. # get the root_folder
  68. root_folder = FileService.get_root_folder(current_user.id)
  69. # get the id of the root_folder
  70. parent_file_id = root_folder["id"] # document id
  71. # this is for the new user, create '.knowledgebase' file
  72. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  73. # go inside this folder, get the kb_root_folder
  74. kb_root_folder = FileService.get_kb_folder(current_user.id)
  75. # link the file management to the kb_folder
  76. kb_folder = FileService.new_a_file_from_kb(dataset.tenant_id, dataset.name, kb_root_folder["id"])
  77. # grab all the errs
  78. err = []
  79. MAX_FILE_NUM_PER_USER = int(os.environ.get('MAX_FILE_NUM_PER_USER', 0))
  80. uploaded_docs_json = []
  81. for file in file_objs:
  82. try:
  83. # TODO: get this value from the database as some tenants have this limit while others don't
  84. if MAX_FILE_NUM_PER_USER > 0 and DocumentService.get_doc_count(dataset.tenant_id) >= MAX_FILE_NUM_PER_USER:
  85. return construct_json_result(code=RetCode.DATA_ERROR,
  86. message="Exceed the maximum file number of a free user!")
  87. # deal with the duplicate name
  88. filename = duplicate_name(
  89. DocumentService.query,
  90. name=file.filename,
  91. kb_id=dataset.id)
  92. # deal with the unsupported type
  93. filetype = filename_type(filename)
  94. if filetype == FileType.OTHER.value:
  95. return construct_json_result(code=RetCode.DATA_ERROR,
  96. message="This type of file has not been supported yet!")
  97. # upload to the minio
  98. location = filename
  99. while MINIO.obj_exist(dataset_id, location):
  100. location += "_"
  101. blob = file.read()
  102. MINIO.put(dataset_id, location, blob)
  103. doc = {
  104. "id": get_uuid(),
  105. "kb_id": dataset.id,
  106. "parser_id": dataset.parser_id,
  107. "parser_config": dataset.parser_config,
  108. "created_by": current_user.id,
  109. "type": filetype,
  110. "name": filename,
  111. "location": location,
  112. "size": len(blob),
  113. "thumbnail": thumbnail(filename, blob)
  114. }
  115. if doc["type"] == FileType.VISUAL:
  116. doc["parser_id"] = ParserType.PICTURE.value
  117. if re.search(r"\.(ppt|pptx|pages)$", filename):
  118. doc["parser_id"] = ParserType.PRESENTATION.value
  119. DocumentService.insert(doc)
  120. FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
  121. uploaded_docs_json.append(doc)
  122. except Exception as e:
  123. err.append(file.filename + ": " + str(e))
  124. if err:
  125. # return all the errors
  126. return construct_json_result(message="\n".join(err), code=RetCode.SERVER_ERROR)
  127. # success
  128. return construct_json_result(data=uploaded_docs_json, code=RetCode.SUCCESS)
  129. # ----------------------------delete a file-----------------------------------------------------
  130. @manager.route('/<dataset_id>/<document_id>', methods=['DELETE'])
  131. @login_required
  132. def delete(document_id, dataset_id): # string
  133. # get the root folder
  134. root_folder = FileService.get_root_folder(current_user.id)
  135. # parent file's id
  136. parent_file_id = root_folder["id"]
  137. # consider the new user
  138. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  139. # store all the errors that may have
  140. errors = ""
  141. try:
  142. # whether there is this document
  143. exist, doc = DocumentService.get_by_id(document_id)
  144. if not exist:
  145. return construct_json_result(message=f"Document {document_id} not found!", code=RetCode.DATA_ERROR)
  146. # whether this doc is authorized by this tenant
  147. tenant_id = DocumentService.get_tenant_id(document_id)
  148. if not tenant_id:
  149. return construct_json_result(message=f"You cannot delete this document {document_id} due to the authorization"
  150. f" reason!", code=RetCode.AUTHENTICATION_ERROR)
  151. # get the doc's id and location
  152. real_dataset_id, location = File2DocumentService.get_minio_address(doc_id=document_id)
  153. if real_dataset_id != dataset_id:
  154. return construct_json_result(message=f"The document {document_id} is not in the dataset: {dataset_id}, "
  155. f"but in the dataset: {real_dataset_id}.", code=RetCode.ARGUMENT_ERROR)
  156. # there is an issue when removing
  157. if not DocumentService.remove_document(doc, tenant_id):
  158. return construct_json_result(
  159. message="There was an error during the document removal process. Please check the status of the "
  160. "RAGFlow server and try the removal again.", code=RetCode.OPERATING_ERROR)
  161. # fetch the File2Document record associated with the provided document ID.
  162. file_to_doc = File2DocumentService.get_by_document_id(document_id)
  163. # delete the associated File record.
  164. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == file_to_doc[0].file_id])
  165. # delete the File2Document record itself using the document ID. This removes the
  166. # association between the document and the file after the File record has been deleted.
  167. File2DocumentService.delete_by_document_id(document_id)
  168. # delete it from minio
  169. MINIO.rm(dataset_id, location)
  170. except Exception as e:
  171. errors += str(e)
  172. if errors:
  173. return construct_json_result(data=False, message=errors, code=RetCode.SERVER_ERROR)
  174. return construct_json_result(data=True, code=RetCode.SUCCESS)
  175. # ----------------------------upload online files------------------------------------------------
  176. # ----------------------------download a file-----------------------------------------------------
  177. # ----------------------------enable rename-----------------------------------------------------
  178. # ----------------------------list files-----------------------------------------------------
  179. # ----------------------------start parsing-----------------------------------------------------
  180. # ----------------------------stop parsing-----------------------------------------------------
  181. # ----------------------------show the status of the file-----------------------------------------------------
  182. # ----------------------------list the chunks of the file-----------------------------------------------------
  183. # ----------------------------delete the chunk-----------------------------------------------------
  184. # ----------------------------edit the status of the chunk-----------------------------------------------------
  185. # ----------------------------insert a new chunk-----------------------------------------------------
  186. # ----------------------------upload a file-----------------------------------------------------
  187. # ----------------------------get a specific chunk-----------------------------------------------------
  188. # ----------------------------retrieval test-----------------------------------------------------