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 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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.file_service import FileService
  25. from api.db.services.knowledgebase_service import KnowledgebaseService
  26. from api.settings import RetCode
  27. from api.utils import get_uuid
  28. from api.utils.api_utils import construct_json_result
  29. from api.utils.file_utils import filename_type, thumbnail
  30. from rag.utils.minio_conn import MINIO
  31. MAXIMUM_OF_UPLOADING_FILES = 256
  32. # ----------------------------upload local files-----------------------------------------------------
  33. @manager.route('/<dataset_id>', methods=['POST'])
  34. @login_required
  35. def upload(dataset_id):
  36. # no files
  37. if not request.files:
  38. return construct_json_result(
  39. message='There is no file!', code=RetCode.ARGUMENT_ERROR)
  40. # the number of uploading files exceeds the limit
  41. file_objs = request.files.getlist('file')
  42. num_file_objs = len(file_objs)
  43. if num_file_objs > MAXIMUM_OF_UPLOADING_FILES:
  44. return construct_json_result(code=RetCode.DATA_ERROR, message=f"You try to upload {num_file_objs} files, "
  45. f"which exceeds the maximum number of uploading files: {MAXIMUM_OF_UPLOADING_FILES}")
  46. for file_obj in file_objs:
  47. # the content of the file
  48. file_content = file_obj.read()
  49. file_name = file_obj.filename
  50. # no name
  51. if not file_name:
  52. return construct_json_result(
  53. message='There is a file without name!', code=RetCode.ARGUMENT_ERROR)
  54. # TODO: support the remote files
  55. if 'http' in file_name:
  56. return construct_json_result(code=RetCode.ARGUMENT_ERROR, message="Remote files have not unsupported.")
  57. # the content is empty, raising a warning
  58. if file_content == b'':
  59. warnings.warn(f"[WARNING]: The file {file_name} is empty.")
  60. # no dataset
  61. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  62. if not exist:
  63. return construct_json_result(message="Can't find this dataset", code=RetCode.DATA_ERROR)
  64. # get the root_folder
  65. root_folder = FileService.get_root_folder(current_user.id)
  66. # get the id of the root_folder
  67. parent_file_id = root_folder["id"] # document id
  68. # this is for the new user, create '.knowledgebase' file
  69. FileService.init_knowledgebase_docs(parent_file_id, current_user.id)
  70. # go inside this folder, get the kb_root_folder
  71. kb_root_folder = FileService.get_kb_folder(current_user.id)
  72. # link the file management to the kb_folder
  73. kb_folder = FileService.new_a_file_from_kb(dataset.tenant_id, dataset.name, kb_root_folder["id"])
  74. # grab all the errs
  75. err = []
  76. MAX_FILE_NUM_PER_USER = int(os.environ.get('MAX_FILE_NUM_PER_USER', 0))
  77. for file in file_objs:
  78. try:
  79. # TODO: get this value from the database as some tenants have this limit while others don't
  80. if MAX_FILE_NUM_PER_USER > 0 and DocumentService.get_doc_count(dataset.tenant_id) >= MAX_FILE_NUM_PER_USER:
  81. return construct_json_result(code=RetCode.DATA_ERROR,
  82. message="Exceed the maximum file number of a free user!")
  83. # deal with the duplicate name
  84. filename = duplicate_name(
  85. DocumentService.query,
  86. name=file.filename,
  87. kb_id=dataset.id)
  88. # deal with the unsupported type
  89. filetype = filename_type(filename)
  90. if filetype == FileType.OTHER.value:
  91. return construct_json_result(code=RetCode.DATA_ERROR,
  92. message="This type of file has not been supported yet!")
  93. # upload to the minio
  94. location = filename
  95. while MINIO.obj_exist(dataset_id, location):
  96. location += "_"
  97. blob = file.read()
  98. MINIO.put(dataset_id, location, blob)
  99. doc = {
  100. "id": get_uuid(),
  101. "kb_id": dataset.id,
  102. "parser_id": dataset.parser_id,
  103. "parser_config": dataset.parser_config,
  104. "created_by": current_user.id,
  105. "type": filetype,
  106. "name": filename,
  107. "location": location,
  108. "size": len(blob),
  109. "thumbnail": thumbnail(filename, blob)
  110. }
  111. if doc["type"] == FileType.VISUAL:
  112. doc["parser_id"] = ParserType.PICTURE.value
  113. if re.search(r"\.(ppt|pptx|pages)$", filename):
  114. doc["parser_id"] = ParserType.PRESENTATION.value
  115. DocumentService.insert(doc)
  116. FileService.add_file_from_kb(doc, kb_folder["id"], dataset.tenant_id)
  117. except Exception as e:
  118. err.append(file.filename + ": " + str(e))
  119. if err:
  120. # return all the errors
  121. return construct_json_result(message="\n".join(err), code=RetCode.SERVER_ERROR)
  122. # success
  123. return construct_json_result(data=True, code=RetCode.SUCCESS)
  124. # ----------------------------upload online files------------------------------------------------
  125. # ----------------------------download a file-----------------------------------------------------
  126. # ----------------------------delete a file-----------------------------------------------------
  127. # ----------------------------enable rename-----------------------------------------------------
  128. # ----------------------------list files-----------------------------------------------------
  129. # ----------------------------start parsing-----------------------------------------------------
  130. # ----------------------------stop parsing-----------------------------------------------------
  131. # ----------------------------show the status of the file-----------------------------------------------------
  132. # ----------------------------list the chunks of the file-----------------------------------------------------
  133. # ----------------------------delete the chunk-----------------------------------------------------
  134. # ----------------------------edit the status of the chunk-----------------------------------------------------
  135. # ----------------------------insert a new chunk-----------------------------------------------------
  136. # ----------------------------upload a file-----------------------------------------------------
  137. # ----------------------------get a specific chunk-----------------------------------------------------
  138. # ----------------------------retrieval test-----------------------------------------------------