您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

dataset_api.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  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. from flask import request
  16. from flask_login import login_required, current_user
  17. from httpx import HTTPError
  18. from api.contants import NAME_LENGTH_LIMIT
  19. from api.db import FileSource, StatusEnum
  20. from api.db.db_models import File
  21. from api.db.services import duplicate_name
  22. from api.db.services.document_service import DocumentService
  23. from api.db.services.file2document_service import File2DocumentService
  24. from api.db.services.file_service import FileService
  25. from api.db.services.knowledgebase_service import KnowledgebaseService
  26. from api.db.services.user_service import TenantService
  27. from api.settings import RetCode
  28. from api.utils import get_uuid
  29. from api.utils.api_utils import construct_json_result, construct_result, construct_error_response, validate_request
  30. # ------------------------------ create a dataset ---------------------------------------
  31. @manager.route('/', methods=['POST'])
  32. @login_required # use login
  33. @validate_request("name") # check name key
  34. def create_dataset():
  35. # Check if Authorization header is present
  36. authorization_token = request.headers.get('Authorization')
  37. if not authorization_token:
  38. return construct_json_result(code=RetCode.AUTHENTICATION_ERROR, message="Authorization header is missing.")
  39. # TODO: Login or API key
  40. # objs = APIToken.query(token=authorization_token)
  41. #
  42. # # Authorization error
  43. # if not objs:
  44. # return construct_json_result(code=RetCode.AUTHENTICATION_ERROR, message="Token is invalid.")
  45. #
  46. # tenant_id = objs[0].tenant_id
  47. tenant_id = current_user.id
  48. request_body = request.json
  49. # In case that there's no name
  50. if "name" not in request_body:
  51. return construct_json_result(code=RetCode.DATA_ERROR, message="Expected 'name' field in request body")
  52. dataset_name = request_body["name"]
  53. # empty dataset_name
  54. if not dataset_name:
  55. return construct_json_result(code=RetCode.DATA_ERROR, message="Empty dataset name")
  56. # In case that there's space in the head or the tail
  57. dataset_name = dataset_name.strip()
  58. # In case that the length of the name exceeds the limit
  59. dataset_name_length = len(dataset_name)
  60. if dataset_name_length > NAME_LENGTH_LIMIT:
  61. return construct_json_result(code=RetCode.DATA_ERROR,
  62. message=f"Dataset name: {dataset_name} with length {dataset_name_length} exceeds {NAME_LENGTH_LIMIT}!")
  63. # In case that there are other fields in the data-binary
  64. if len(request_body.keys()) > 1:
  65. name_list = []
  66. for key_name in request_body.keys():
  67. if key_name != 'name':
  68. name_list.append(key_name)
  69. return construct_json_result(code=RetCode.DATA_ERROR,
  70. message=f"fields: {name_list}, are not allowed in request body.")
  71. # If there is a duplicate name, it will modify it to make it unique
  72. request_body["name"] = duplicate_name(
  73. KnowledgebaseService.query,
  74. name=dataset_name,
  75. tenant_id=tenant_id,
  76. status=StatusEnum.VALID.value)
  77. try:
  78. request_body["id"] = get_uuid()
  79. request_body["tenant_id"] = tenant_id
  80. request_body["created_by"] = tenant_id
  81. exist, t = TenantService.get_by_id(tenant_id)
  82. if not exist:
  83. return construct_result(code=RetCode.AUTHENTICATION_ERROR, message="Tenant not found.")
  84. request_body["embd_id"] = t.embd_id
  85. if not KnowledgebaseService.save(**request_body):
  86. # failed to create new dataset
  87. return construct_result()
  88. return construct_json_result(code=RetCode.SUCCESS,
  89. data={"dataset_name": request_body["name"], "dataset_id": request_body["id"]})
  90. except Exception as e:
  91. return construct_error_response(e)
  92. # -----------------------------list datasets-------------------------------------------------------
  93. @manager.route('/', methods=['GET'])
  94. @login_required
  95. def list_datasets():
  96. offset = request.args.get("offset", 0)
  97. count = request.args.get("count", -1)
  98. orderby = request.args.get("orderby", "create_time")
  99. desc = request.args.get("desc", True)
  100. try:
  101. tenants = TenantService.get_joined_tenants_by_user_id(current_user.id)
  102. datasets = KnowledgebaseService.get_by_tenant_ids_by_offset(
  103. [m["tenant_id"] for m in tenants], current_user.id, int(offset), int(count), orderby, desc)
  104. return construct_json_result(data=datasets, code=RetCode.SUCCESS, message=f"List datasets successfully!")
  105. except Exception as e:
  106. return construct_error_response(e)
  107. except HTTPError as http_err:
  108. return construct_json_result(http_err)
  109. # ---------------------------------delete a dataset ----------------------------
  110. @manager.route('/<dataset_id>', methods=['DELETE'])
  111. @login_required
  112. def remove_dataset(dataset_id):
  113. try:
  114. datasets = KnowledgebaseService.query(created_by=current_user.id, id=dataset_id)
  115. # according to the id, searching for the dataset
  116. if not datasets:
  117. return construct_json_result(message=f'The dataset cannot be found for your current account.',
  118. code=RetCode.OPERATING_ERROR)
  119. # Iterating the documents inside the dataset
  120. for doc in DocumentService.query(kb_id=dataset_id):
  121. if not DocumentService.remove_document(doc, datasets[0].tenant_id):
  122. # the process of deleting failed
  123. return construct_json_result(code=RetCode.DATA_ERROR,
  124. message="There was an error during the document removal process. "
  125. "Please check the status of the RAGFlow server and try the removal again.")
  126. # delete the other files
  127. f2d = File2DocumentService.get_by_document_id(doc.id)
  128. FileService.filter_delete([File.source_type == FileSource.KNOWLEDGEBASE, File.id == f2d[0].file_id])
  129. File2DocumentService.delete_by_document_id(doc.id)
  130. # delete the dataset
  131. if not KnowledgebaseService.delete_by_id(dataset_id):
  132. return construct_json_result(code=RetCode.DATA_ERROR, message="There was an error during the dataset removal process. "
  133. "Please check the status of the RAGFlow server and try the removal again.")
  134. # success
  135. return construct_json_result(code=RetCode.SUCCESS, message=f"Remove dataset: {dataset_id} successfully")
  136. except Exception as e:
  137. return construct_error_response(e)
  138. # ------------------------------ get details of a dataset ----------------------------------------
  139. @manager.route('/<dataset_id>', methods=['GET'])
  140. @login_required
  141. def get_dataset(dataset_id):
  142. try:
  143. dataset = KnowledgebaseService.get_detail(dataset_id)
  144. if not dataset:
  145. return construct_json_result(code=RetCode.DATA_ERROR, message="Can't find this dataset!")
  146. return construct_json_result(data=dataset, code=RetCode.SUCCESS)
  147. except Exception as e:
  148. return construct_json_result(e)
  149. # ------------------------------ update a dataset --------------------------------------------
  150. @manager.route('/<dataset_id>', methods=['PUT'])
  151. @login_required
  152. def update_dataset(dataset_id):
  153. req = request.json
  154. try:
  155. # the request cannot be empty
  156. if not req:
  157. return construct_json_result(code=RetCode.DATA_ERROR, message="Please input at least one parameter that "
  158. "you want to update!")
  159. # check whether the dataset can be found
  160. if not KnowledgebaseService.query(created_by=current_user.id, id=dataset_id):
  161. return construct_json_result(message=f'Only the owner of knowledgebase is authorized for this operation!',
  162. code=RetCode.OPERATING_ERROR)
  163. exist, dataset = KnowledgebaseService.get_by_id(dataset_id)
  164. # check whether there is this dataset
  165. if not exist:
  166. return construct_json_result(code=RetCode.DATA_ERROR, message="This dataset cannot be found!")
  167. if 'name' in req:
  168. name = req["name"].strip()
  169. # check whether there is duplicate name
  170. if name.lower() != dataset.name.lower() \
  171. and len(KnowledgebaseService.query(name=name, tenant_id=current_user.id,
  172. status=StatusEnum.VALID.value)) > 1:
  173. return construct_json_result(code=RetCode.DATA_ERROR, message=f"The name: {name.lower()} is already used by other "
  174. f"datasets. Please choose a different name.")
  175. dataset_updating_data = {}
  176. chunk_num = req.get("chunk_num")
  177. # modify the value of 11 parameters
  178. # 2 parameters: embedding id and chunk method
  179. # only if chunk_num is 0, the user can update the embedding id
  180. if req.get('embedding_model_id'):
  181. if chunk_num == 0:
  182. dataset_updating_data['embd_id'] = req['embedding_model_id']
  183. else:
  184. construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document in this "
  185. "dataset, so you cannot change the embedding "
  186. "model.")
  187. # only if chunk_num is 0, the user can update the chunk_method
  188. if req.get("chunk_method"):
  189. if chunk_num == 0:
  190. dataset_updating_data['parser_id'] = req["chunk_method"]
  191. else:
  192. construct_json_result(code=RetCode.DATA_ERROR, message="You have already parsed the document "
  193. "in this dataset, so you cannot "
  194. "change the chunk method.")
  195. # convert the photo parameter to avatar
  196. if req.get("photo"):
  197. dataset_updating_data['avatar'] = req["photo"]
  198. # layout_recognize
  199. if 'layout_recognize' in req:
  200. if 'parser_config' not in dataset_updating_data:
  201. dataset_updating_data['parser_config'] = {}
  202. dataset_updating_data['parser_config']['layout_recognize'] = req['layout_recognize']
  203. # TODO: updating use_raptor needs to construct a class
  204. # 6 parameters
  205. for key in ['name', 'language', 'description', 'permission', 'id', 'token_num']:
  206. if key in req:
  207. dataset_updating_data[key] = req.get(key)
  208. # update
  209. if not KnowledgebaseService.update_by_id(dataset.id, dataset_updating_data):
  210. return construct_json_result(code=RetCode.OPERATING_ERROR, message="Failed to update! "
  211. "Please check the status of RAGFlow "
  212. "server and try again!")
  213. exist, dataset = KnowledgebaseService.get_by_id(dataset.id)
  214. if not exist:
  215. return construct_json_result(code=RetCode.DATA_ERROR, message="Failed to get the dataset "
  216. "using the dataset ID.")
  217. return construct_json_result(data=dataset.to_json(), code=RetCode.SUCCESS)
  218. except Exception as e:
  219. return construct_error_response(e)