Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

dataset_api.py 13KB

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